summaryrefslogtreecommitdiffstats
path: root/mobile/android/exoplayer2/src/main/java/org/mozilla/thirdparty/com/google/android/exoplayer2/upstream/RawResourceDataSource.java
blob: ec5263d8ac6c56f34ba758bc3037d7f368d354d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mozilla.thirdparty.com.google.android.exoplayer2.upstream;

import static org.mozilla.thirdparty.com.google.android.exoplayer2.util.Util.castNonNull;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.net.Uri;
import android.text.TextUtils;
import androidx.annotation.Nullable;
import org.mozilla.thirdparty.com.google.android.exoplayer2.C;
import org.mozilla.thirdparty.com.google.android.exoplayer2.util.Assertions;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * A {@link DataSource} for reading a raw resource inside the APK.
 *
 * <p>URIs supported by this source are of the form {@code rawresource:///rawResourceId}, where
 * rawResourceId is the integer identifier of a raw resource. {@link #buildRawResourceUri(int)} can
 * be used to build {@link Uri}s in this format.
 */
public final class RawResourceDataSource extends BaseDataSource {

  /**
   * Thrown when an {@link IOException} is encountered reading from a raw resource.
   */
  public static class RawResourceDataSourceException extends IOException {
    public RawResourceDataSourceException(String message) {
      super(message);
    }

    public RawResourceDataSourceException(IOException e) {
      super(e);
    }
  }

  /**
   * Builds a {@link Uri} for the specified raw resource identifier.
   *
   * @param rawResourceId A raw resource identifier (i.e. a constant defined in {@code R.raw}).
   * @return The corresponding {@link Uri}.
   */
  public static Uri buildRawResourceUri(int rawResourceId) {
    return Uri.parse(RAW_RESOURCE_SCHEME + ":///" + rawResourceId);
  }

  /** The scheme part of a raw resource URI. */
  public static final String RAW_RESOURCE_SCHEME = "rawresource";

  private final Resources resources;

  @Nullable private Uri uri;
  @Nullable private AssetFileDescriptor assetFileDescriptor;
  @Nullable private InputStream inputStream;
  private long bytesRemaining;
  private boolean opened;

  /**
   * @param context A context.
   */
  public RawResourceDataSource(Context context) {
    super(/* isNetwork= */ false);
    this.resources = context.getResources();
  }

  @Override
  public long open(DataSpec dataSpec) throws RawResourceDataSourceException {
    try {
      Uri uri = dataSpec.uri;
      this.uri = uri;
      if (!TextUtils.equals(RAW_RESOURCE_SCHEME, uri.getScheme())) {
        throw new RawResourceDataSourceException("URI must use scheme " + RAW_RESOURCE_SCHEME);
      }

      int resourceId;
      try {
        resourceId = Integer.parseInt(Assertions.checkNotNull(uri.getLastPathSegment()));
      } catch (NumberFormatException e) {
        throw new RawResourceDataSourceException("Resource identifier must be an integer.");
      }

      transferInitializing(dataSpec);
      AssetFileDescriptor assetFileDescriptor = resources.openRawResourceFd(resourceId);
      this.assetFileDescriptor = assetFileDescriptor;
      if (assetFileDescriptor == null) {
        throw new RawResourceDataSourceException("Resource is compressed: " + uri);
      }
      FileInputStream inputStream = new FileInputStream(assetFileDescriptor.getFileDescriptor());
      this.inputStream = inputStream;

      inputStream.skip(assetFileDescriptor.getStartOffset());
      long skipped = inputStream.skip(dataSpec.position);
      if (skipped < dataSpec.position) {
        // We expect the skip to be satisfied in full. If it isn't then we're probably trying to
        // skip beyond the end of the data.
        throw new EOFException();
      }
      if (dataSpec.length != C.LENGTH_UNSET) {
        bytesRemaining = dataSpec.length;
      } else {
        long assetFileDescriptorLength = assetFileDescriptor.getLength();
        // If the length is UNKNOWN_LENGTH then the asset extends to the end of the file.
        bytesRemaining = assetFileDescriptorLength == AssetFileDescriptor.UNKNOWN_LENGTH
            ? C.LENGTH_UNSET : (assetFileDescriptorLength - dataSpec.position);
      }
    } catch (IOException e) {
      throw new RawResourceDataSourceException(e);
    }

    opened = true;
    transferStarted(dataSpec);

    return bytesRemaining;
  }

  @Override
  public int read(byte[] buffer, int offset, int readLength) throws RawResourceDataSourceException {
    if (readLength == 0) {
      return 0;
    } else if (bytesRemaining == 0) {
      return C.RESULT_END_OF_INPUT;
    }

    int bytesRead;
    try {
      int bytesToRead = bytesRemaining == C.LENGTH_UNSET ? readLength
          : (int) Math.min(bytesRemaining, readLength);
      bytesRead = castNonNull(inputStream).read(buffer, offset, bytesToRead);
    } catch (IOException e) {
      throw new RawResourceDataSourceException(e);
    }

    if (bytesRead == -1) {
      if (bytesRemaining != C.LENGTH_UNSET) {
        // End of stream reached having not read sufficient data.
        throw new RawResourceDataSourceException(new EOFException());
      }
      return C.RESULT_END_OF_INPUT;
    }
    if (bytesRemaining != C.LENGTH_UNSET) {
      bytesRemaining -= bytesRead;
    }
    bytesTransferred(bytesRead);
    return bytesRead;
  }

  @Override
  @Nullable
  public Uri getUri() {
    return uri;
  }

  @SuppressWarnings("Finally")
  @Override
  public void close() throws RawResourceDataSourceException {
    uri = null;
    try {
      if (inputStream != null) {
        inputStream.close();
      }
    } catch (IOException e) {
      throw new RawResourceDataSourceException(e);
    } finally {
      inputStream = null;
      try {
        if (assetFileDescriptor != null) {
          assetFileDescriptor.close();
        }
      } catch (IOException e) {
        throw new RawResourceDataSourceException(e);
      } finally {
        assetFileDescriptor = null;
        if (opened) {
          opened = false;
          transferEnded();
        }
      }
    }
  }

}