/
MediaResourceGetter.java
423 lines (385 loc) · 15 KB
/
MediaResourceGetter.java
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.content.browser;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.MediaMetadataRetriever;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import org.chromium.base.Log;
import org.chromium.base.PathUtils;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Java counterpart of android MediaResourceGetter.
*/
@JNINamespace("content")
class MediaResourceGetter {
private static final String TAG = "cr_MediaResource";
private static final MediaMetadata EMPTY_METADATA = new MediaMetadata(0, 0, 0, false);
private final MediaMetadataRetriever mRetriever = new MediaMetadataRetriever();
@VisibleForTesting
static class MediaMetadata {
private final int mDurationInMilliseconds;
private final int mWidth;
private final int mHeight;
private final boolean mSuccess;
MediaMetadata(int durationInMilliseconds, int width, int height, boolean success) {
mDurationInMilliseconds = durationInMilliseconds;
mWidth = width;
mHeight = height;
mSuccess = success;
}
// TODO(andrewhayden): according to the spec, if duration is unknown
// then we must return NaN. If it is unbounded, then positive infinity.
// http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html
@CalledByNative("MediaMetadata")
int getDurationInMilliseconds() {
return mDurationInMilliseconds;
}
@CalledByNative("MediaMetadata")
int getWidth() {
return mWidth;
}
@CalledByNative("MediaMetadata")
int getHeight() {
return mHeight;
}
@CalledByNative("MediaMetadata")
boolean isSuccess() {
return mSuccess;
}
@Override
public String toString() {
return "MediaMetadata["
+ "durationInMilliseconds=" + mDurationInMilliseconds
+ ", width=" + mWidth
+ ", height=" + mHeight
+ ", success=" + mSuccess
+ "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + mDurationInMilliseconds;
result = prime * result + mHeight;
result = prime * result + (mSuccess ? 1231 : 1237);
result = prime * result + mWidth;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
MediaMetadata other = (MediaMetadata) obj;
if (mDurationInMilliseconds != other.mDurationInMilliseconds) return false;
if (mHeight != other.mHeight) return false;
if (mSuccess != other.mSuccess) return false;
if (mWidth != other.mWidth) return false;
return true;
}
}
@CalledByNative
private static MediaMetadata extractMediaMetadata(final Context context,
final String url,
final String cookies,
final String userAgent) {
return new MediaResourceGetter().extract(
context, url, cookies, userAgent);
}
@CalledByNative
private static MediaMetadata extractMediaMetadataFromFd(int fd,
long offset,
long length) {
return new MediaResourceGetter().extract(fd, offset, length);
}
@VisibleForTesting
MediaMetadata extract(int fd, long offset, long length) {
configure(fd, offset, length);
return doExtractMetadata();
}
@VisibleForTesting
MediaMetadata extract(final Context context, final String url,
final String cookies, final String userAgent) {
if (!configure(context, url, cookies, userAgent)) {
Log.e(TAG, "Unable to configure metadata extractor");
return EMPTY_METADATA;
}
return doExtractMetadata();
}
private MediaMetadata doExtractMetadata() {
try {
String durationString = extractMetadata(
MediaMetadataRetriever.METADATA_KEY_DURATION);
if (durationString == null) {
Log.w(TAG, "missing duration metadata");
return EMPTY_METADATA;
}
int durationMillis = 0;
try {
durationMillis = Integer.parseInt(durationString);
} catch (NumberFormatException e) {
Log.w(TAG, "non-numeric duration: %s", durationString);
return EMPTY_METADATA;
}
int width = 0;
int height = 0;
boolean hasVideo = "yes".equals(extractMetadata(
MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO));
Log.d(TAG, (hasVideo ? "resource has video" : "resource doesn't have video"));
if (hasVideo) {
String widthString = extractMetadata(
MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
if (widthString == null) {
Log.w(TAG, "missing video width metadata");
return EMPTY_METADATA;
}
try {
width = Integer.parseInt(widthString);
} catch (NumberFormatException e) {
Log.w(TAG, "non-numeric width: %s", widthString);
return EMPTY_METADATA;
}
String heightString = extractMetadata(
MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
if (heightString == null) {
Log.w(TAG, "missing video height metadata");
return EMPTY_METADATA;
}
try {
height = Integer.parseInt(heightString);
} catch (NumberFormatException e) {
Log.w(TAG, "non-numeric height: %s", heightString);
return EMPTY_METADATA;
}
}
MediaMetadata result = new MediaMetadata(durationMillis, width, height, true);
Log.d(TAG, "extracted valid metadata: %s", result);
return result;
} catch (RuntimeException e) {
Log.e(TAG, "Unable to extract metadata: %s", e);
return EMPTY_METADATA;
}
}
@VisibleForTesting
boolean configure(Context context, String url, String cookies, String userAgent) {
URI uri;
try {
uri = URI.create(url);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Cannot parse uri: %s", e);
return false;
}
String scheme = uri.getScheme();
if (scheme == null || scheme.equals("file")) {
File file = uriToFile(uri.getPath());
if (!file.exists()) {
Log.e(TAG, "File does not exist.");
return false;
}
if (!filePathAcceptable(file, context)) {
Log.e(TAG, "Refusing to read from unsafe file location.");
return false;
}
try {
configure(file.getAbsolutePath());
return true;
} catch (RuntimeException e) {
Log.e(TAG, "Error configuring data source: %s", e);
return false;
}
}
if (scheme.equals("content")) {
try {
configure(context, Uri.parse(uri.toString()));
return true;
} catch (RuntimeException e) {
Log.e(TAG, "Error configuring data source: %s", e);
return false;
}
}
if (uri.getPath() != null && uri.getPath().endsWith(".m3u8")) {
// MediaMetadataRetriever does not work with HLS correctly.
return false;
}
final String host = uri.getHost();
if (!isLoopbackAddress(host) && !isNetworkReliable(context)) {
Log.w(TAG, "non-file URI can't be read due to unsuitable network conditions");
return false;
}
Map<String, String> headersMap = new HashMap<String, String>();
if (!TextUtils.isEmpty(cookies)) {
headersMap.put("Cookie", cookies);
}
if (!TextUtils.isEmpty(userAgent)) {
headersMap.put("User-Agent", userAgent);
}
try {
configure(url, headersMap);
return true;
} catch (RuntimeException e) {
Log.e(TAG, "Error configuring data source: %s", e);
return false;
}
}
/**
* @return true if the device is on an ethernet or wifi network.
* If anything goes wrong (e.g., permission denied while trying to access
* the network state), returns false.
*/
@VisibleForTesting
boolean isNetworkReliable(Context context) {
if (context.checkCallingOrSelfPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
!= PackageManager.PERMISSION_GRANTED) {
Log.w(TAG, "permission denied to access network state");
return false;
}
Integer networkType = getNetworkType(context);
if (networkType == null) {
return false;
}
switch (networkType.intValue()) {
case ConnectivityManager.TYPE_ETHERNET:
case ConnectivityManager.TYPE_WIFI:
Log.d(TAG, "ethernet/wifi connection detected");
return true;
case ConnectivityManager.TYPE_WIMAX:
case ConnectivityManager.TYPE_MOBILE:
default:
Log.d(TAG, "no ethernet/wifi connection detected");
return false;
}
}
// This method covers only typcial expressions for the loopback address
// to resolve the hostname without a DNS loopup.
private boolean isLoopbackAddress(String host) {
return host != null && (host.equalsIgnoreCase("localhost") // typical hostnames
|| host.equalsIgnoreCase("localhost.localdomain")
|| host.equalsIgnoreCase("localhost6")
|| host.equalsIgnoreCase("localhost6.localdomain6")
|| host.toLowerCase(Locale.US).endsWith(".localhost")
|| host.equals("127.0.0.1") // typical IP v4 expression
|| host.equals("[::1]")); // typical IP v6 expression
}
/**
* @param file the file whose path should be checked
* @return true if and only if the file is in a location that we consider
* safe to read from, such as /mnt/sdcard.
*/
@VisibleForTesting
boolean filePathAcceptable(File file, Context context) {
final String path;
try {
path = file.getCanonicalPath();
} catch (IOException e) {
// Canonicalization has failed. Assume malicious, give up.
Log.w(TAG, "canonicalization of file path failed");
return false;
}
// In order to properly match the roots we must also canonicalize the
// well-known paths we are matching against. If we don't, then we can
// get unusual results in testing systems or possibly on rooted devices.
// Note that canonicalized directory paths always end with '/'.
List<String> acceptablePaths = canonicalize(getRawAcceptableDirectories(context));
acceptablePaths.add(getExternalStorageDirectory());
Log.d(TAG, "canonicalized file path: %s", path);
for (String acceptablePath : acceptablePaths) {
if (path.startsWith(acceptablePath)) {
return true;
}
}
return false;
}
// The methods below can be used by unit tests to fake functionality.
@VisibleForTesting
File uriToFile(String path) {
return new File(path);
}
@VisibleForTesting
Integer getNetworkType(Context context) {
// TODO(qinmin): use ConnectionTypeObserver to listen to the network type change.
ConnectivityManager mConnectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (mConnectivityManager == null) {
Log.w(TAG, "no connectivity manager available");
return null;
}
NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
if (info == null) {
Log.d(TAG, "no active network");
return null;
}
return info.getType();
}
@SuppressLint("SdCardPath")
private List<String> getRawAcceptableDirectories(Context context) {
List<String> result = new ArrayList<String>();
result.add("/mnt/sdcard/");
result.add("/sdcard/");
result.add("/data/data/" + context.getPackageName() + "/cache/");
return result;
}
private List<String> canonicalize(List<String> paths) {
List<String> result = new ArrayList<String>(paths.size());
try {
for (String path : paths) {
result.add(new File(path).getCanonicalPath());
}
return result;
} catch (IOException e) {
// Canonicalization has failed. Assume malicious, give up.
Log.w(TAG, "canonicalization of file path failed");
}
return result;
}
@VisibleForTesting
String getExternalStorageDirectory() {
return PathUtils.getExternalStorageDirectory();
}
@VisibleForTesting
void configure(int fd, long offset, long length) {
ParcelFileDescriptor parcelFd = ParcelFileDescriptor.adoptFd(fd);
try {
mRetriever.setDataSource(parcelFd.getFileDescriptor(),
offset, length);
} finally {
try {
parcelFd.close();
} catch (IOException e) {
Log.e(TAG, "Failed to close file descriptor: %s", e);
}
}
}
@VisibleForTesting
void configure(String url, Map<String, String> headers) {
mRetriever.setDataSource(url, headers);
}
@VisibleForTesting
void configure(String path) {
mRetriever.setDataSource(path);
}
@VisibleForTesting
void configure(Context context, Uri uri) {
mRetriever.setDataSource(context, uri);
}
@VisibleForTesting
String extractMetadata(int key) {
return mRetriever.extractMetadata(key);
}
}