Commit 82061e9a by olly Committed by Oliver Woodman

Improve progress reporting logic

- Listener based reporting of progress allows the content length
  to be persisted into the download index (and notified via a
  download state change) as soon as it's available.
- Moved contentLength back into Download proper. It should only
  ever change once, so I'm not sure it belongs in the mutable part
  of Download.
- Made a DownloadProgress class, for naming sanity.

PiperOrigin-RevId: 244242487
parent 0ccda60a
Showing with 513 additions and 394 deletions
...@@ -18,6 +18,7 @@ package com.google.android.exoplayer2.offline; ...@@ -18,6 +18,7 @@ package com.google.android.exoplayer2.offline;
import static com.google.android.exoplayer2.offline.Download.STATE_QUEUED; import static com.google.android.exoplayer2.offline.Download.STATE_QUEUED;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
...@@ -97,10 +98,11 @@ public final class ActionFileUpgradeUtil { ...@@ -97,10 +98,11 @@ public final class ActionFileUpgradeUtil {
new Download( new Download(
request, request,
STATE_QUEUED, STATE_QUEUED,
Download.FAILURE_REASON_NONE,
Download.STOP_REASON_NONE,
/* startTimeMs= */ nowMs, /* startTimeMs= */ nowMs,
/* updateTimeMs= */ nowMs); /* updateTimeMs= */ nowMs,
/* contentLength= */ C.LENGTH_UNSET,
Download.STOP_REASON_NONE,
Download.FAILURE_REASON_NONE);
} }
downloadIndex.putDownload(download); downloadIndex.putDownload(download);
} }
......
...@@ -27,7 +27,6 @@ import android.text.TextUtils; ...@@ -27,7 +27,6 @@ import android.text.TextUtils;
import com.google.android.exoplayer2.database.DatabaseIOException; import com.google.android.exoplayer2.database.DatabaseIOException;
import com.google.android.exoplayer2.database.DatabaseProvider; import com.google.android.exoplayer2.database.DatabaseProvider;
import com.google.android.exoplayer2.database.VersionTable; import com.google.android.exoplayer2.database.VersionTable;
import com.google.android.exoplayer2.upstream.cache.CacheUtil.CachingCounters;
import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Util; import com.google.android.exoplayer2.util.Util;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -210,15 +209,15 @@ public final class DefaultDownloadIndex implements WritableDownloadIndex { ...@@ -210,15 +209,15 @@ public final class DefaultDownloadIndex implements WritableDownloadIndex {
values.put(COLUMN_CUSTOM_CACHE_KEY, download.request.customCacheKey); values.put(COLUMN_CUSTOM_CACHE_KEY, download.request.customCacheKey);
values.put(COLUMN_DATA, download.request.data); values.put(COLUMN_DATA, download.request.data);
values.put(COLUMN_STATE, download.state); values.put(COLUMN_STATE, download.state);
values.put(COLUMN_DOWNLOAD_PERCENTAGE, download.getDownloadPercentage()); values.put(COLUMN_START_TIME_MS, download.startTimeMs);
values.put(COLUMN_DOWNLOADED_BYTES, download.getDownloadedBytes()); values.put(COLUMN_UPDATE_TIME_MS, download.updateTimeMs);
values.put(COLUMN_TOTAL_BYTES, download.getTotalBytes()); values.put(COLUMN_TOTAL_BYTES, download.contentLength);
values.put(COLUMN_STOP_REASON, download.stopReason);
values.put(COLUMN_FAILURE_REASON, download.failureReason); values.put(COLUMN_FAILURE_REASON, download.failureReason);
values.put(COLUMN_DOWNLOAD_PERCENTAGE, download.getPercentDownloaded());
values.put(COLUMN_DOWNLOADED_BYTES, download.getBytesDownloaded());
values.put(COLUMN_STOP_FLAGS, 0); values.put(COLUMN_STOP_FLAGS, 0);
values.put(COLUMN_NOT_MET_REQUIREMENTS, 0); values.put(COLUMN_NOT_MET_REQUIREMENTS, 0);
values.put(COLUMN_STOP_REASON, download.stopReason);
values.put(COLUMN_START_TIME_MS, download.startTimeMs);
values.put(COLUMN_UPDATE_TIME_MS, download.updateTimeMs);
try { try {
SQLiteDatabase writableDatabase = databaseProvider.getWritableDatabase(); SQLiteDatabase writableDatabase = databaseProvider.getWritableDatabase();
writableDatabase.replaceOrThrow(tableName, /* nullColumnHack= */ null, values); writableDatabase.replaceOrThrow(tableName, /* nullColumnHack= */ null, values);
...@@ -337,18 +336,18 @@ public final class DefaultDownloadIndex implements WritableDownloadIndex { ...@@ -337,18 +336,18 @@ public final class DefaultDownloadIndex implements WritableDownloadIndex {
decodeStreamKeys(cursor.getString(COLUMN_INDEX_STREAM_KEYS)), decodeStreamKeys(cursor.getString(COLUMN_INDEX_STREAM_KEYS)),
cursor.getString(COLUMN_INDEX_CUSTOM_CACHE_KEY), cursor.getString(COLUMN_INDEX_CUSTOM_CACHE_KEY),
cursor.getBlob(COLUMN_INDEX_DATA)); cursor.getBlob(COLUMN_INDEX_DATA));
CachingCounters cachingCounters = new CachingCounters(); DownloadProgress downloadProgress = new DownloadProgress();
cachingCounters.alreadyCachedBytes = cursor.getLong(COLUMN_INDEX_DOWNLOADED_BYTES); downloadProgress.bytesDownloaded = cursor.getLong(COLUMN_INDEX_DOWNLOADED_BYTES);
cachingCounters.contentLength = cursor.getLong(COLUMN_INDEX_TOTAL_BYTES); downloadProgress.percentDownloaded = cursor.getFloat(COLUMN_INDEX_DOWNLOAD_PERCENTAGE);
cachingCounters.percentage = cursor.getFloat(COLUMN_INDEX_DOWNLOAD_PERCENTAGE);
return new Download( return new Download(
request, request,
cursor.getInt(COLUMN_INDEX_STATE), cursor.getInt(COLUMN_INDEX_STATE),
cursor.getInt(COLUMN_INDEX_FAILURE_REASON),
cursor.getInt(COLUMN_INDEX_STOP_REASON),
cursor.getLong(COLUMN_INDEX_START_TIME_MS), cursor.getLong(COLUMN_INDEX_START_TIME_MS),
cursor.getLong(COLUMN_INDEX_UPDATE_TIME_MS), cursor.getLong(COLUMN_INDEX_UPDATE_TIME_MS),
cachingCounters); cursor.getLong(COLUMN_INDEX_TOTAL_BYTES),
cursor.getInt(COLUMN_INDEX_STOP_REASON),
cursor.getInt(COLUMN_INDEX_FAILURE_REASON),
downloadProgress);
} }
private static String encodeStreamKeys(List<StreamKey> streamKeys) { private static String encodeStreamKeys(List<StreamKey> streamKeys) {
......
...@@ -17,7 +17,6 @@ package com.google.android.exoplayer2.offline; ...@@ -17,7 +17,6 @@ package com.google.android.exoplayer2.offline;
import androidx.annotation.IntDef; import androidx.annotation.IntDef;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.upstream.cache.CacheUtil.CachingCounters;
import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.Assertions;
import java.lang.annotation.Documented; import java.lang.annotation.Documented;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
...@@ -96,60 +95,65 @@ public final class Download { ...@@ -96,60 +95,65 @@ public final class Download {
/** The download request. */ /** The download request. */
public final DownloadRequest request; public final DownloadRequest request;
/** The state of the download. */ /** The state of the download. */
@State public final int state; @State public final int state;
/** The first time when download entry is created. */ /** The first time when download entry is created. */
public final long startTimeMs; public final long startTimeMs;
/** The last update time. */ /** The last update time. */
public final long updateTimeMs; public final long updateTimeMs;
/** The total size of the content in bytes, or {@link C#LENGTH_UNSET} if unknown. */
public final long contentLength;
/** The reason the download is stopped, or {@link #STOP_REASON_NONE}. */
public final int stopReason;
/** /**
* If {@link #state} is {@link #STATE_FAILED} then this is the cause, otherwise {@link * If {@link #state} is {@link #STATE_FAILED} then this is the cause, otherwise {@link
* #FAILURE_REASON_NONE}. * #FAILURE_REASON_NONE}.
*/ */
@FailureReason public final int failureReason; @FailureReason public final int failureReason;
/** The reason the download is stopped, or {@link #STOP_REASON_NONE}. */
public final int stopReason;
/* package */ CachingCounters counters; /* package */ final DownloadProgress progress;
/* package */ Download( public Download(
DownloadRequest request, DownloadRequest request,
@State int state, @State int state,
@FailureReason int failureReason,
int stopReason,
long startTimeMs, long startTimeMs,
long updateTimeMs) { long updateTimeMs,
long contentLength,
int stopReason,
@FailureReason int failureReason) {
this( this(
request, request,
state, state,
failureReason,
stopReason,
startTimeMs, startTimeMs,
updateTimeMs, updateTimeMs,
new CachingCounters()); contentLength,
stopReason,
failureReason,
new DownloadProgress());
} }
/* package */ Download( public Download(
DownloadRequest request, DownloadRequest request,
@State int state, @State int state,
@FailureReason int failureReason,
int stopReason,
long startTimeMs, long startTimeMs,
long updateTimeMs, long updateTimeMs,
CachingCounters counters) { long contentLength,
Assertions.checkNotNull(counters); int stopReason,
@FailureReason int failureReason,
DownloadProgress progress) {
Assertions.checkNotNull(progress);
Assertions.checkState((failureReason == FAILURE_REASON_NONE) == (state != STATE_FAILED)); Assertions.checkState((failureReason == FAILURE_REASON_NONE) == (state != STATE_FAILED));
if (stopReason != 0) { if (stopReason != 0) {
Assertions.checkState(state != STATE_DOWNLOADING && state != STATE_QUEUED); Assertions.checkState(state != STATE_DOWNLOADING && state != STATE_QUEUED);
} }
this.request = request; this.request = request;
this.state = state; this.state = state;
this.failureReason = failureReason;
this.stopReason = stopReason;
this.startTimeMs = startTimeMs; this.startTimeMs = startTimeMs;
this.updateTimeMs = updateTimeMs; this.updateTimeMs = updateTimeMs;
this.counters = counters; this.contentLength = contentLength;
this.stopReason = stopReason;
this.failureReason = failureReason;
this.progress = progress;
} }
/** Returns whether the download is completed or failed. These are terminal states. */ /** Returns whether the download is completed or failed. These are terminal states. */
...@@ -158,30 +162,15 @@ public final class Download { ...@@ -158,30 +162,15 @@ public final class Download {
} }
/** Returns the total number of downloaded bytes. */ /** Returns the total number of downloaded bytes. */
public long getDownloadedBytes() { public long getBytesDownloaded() {
return counters.totalCachedBytes(); return progress.bytesDownloaded;
}
/** Returns the total size of the media, or {@link C#LENGTH_UNSET} if unknown. */
public long getTotalBytes() {
return counters.contentLength;
} }
/** /**
* Returns the estimated download percentage, or {@link C#PERCENTAGE_UNSET} if no estimate is * Returns the estimated download percentage, or {@link C#PERCENTAGE_UNSET} if no estimate is
* available. * available.
*/ */
public float getDownloadPercentage() { public float getPercentDownloaded() {
return counters.percentage; return progress.percentDownloaded;
}
/**
* Sets counters which are updated by a {@link Downloader}.
*
* @param counters An instance of {@link CachingCounters}.
*/
protected void setCounters(CachingCounters counters) {
Assertions.checkNotNull(counters);
this.counters = counters;
} }
} }
/*
* Copyright (C) 2019 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 com.google.android.exoplayer2.offline;
import com.google.android.exoplayer2.C;
/** Mutable {@link Download} progress. */
public class DownloadProgress {
/** The number of bytes that have been downloaded. */
public long bytesDownloaded;
/** The percentage that has been downloaded, or {@link C#PERCENTAGE_UNSET} if unknown. */
public float percentDownloaded;
}
...@@ -15,44 +15,44 @@ ...@@ -15,44 +15,44 @@
*/ */
package com.google.android.exoplayer2.offline; package com.google.android.exoplayer2.offline;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.upstream.cache.CacheUtil.CachingCounters;
import java.io.IOException; import java.io.IOException;
/** /** Downloads and removes a piece of content. */
* An interface for stream downloaders.
*/
public interface Downloader { public interface Downloader {
/** Receives progress updates during download operations. */
interface ProgressListener {
/**
* Called when progress is made during a download operation.
*
* @param contentLength The length of the content in bytes, or {@link C#LENGTH_UNSET} if
* unknown.
* @param bytesDownloaded The number of bytes that have been downloaded.
* @param percentDownloaded The percentage of the content that has been downloaded, or {@link
* C#PERCENTAGE_UNSET}.
*/
void onProgress(long contentLength, long bytesDownloaded, float percentDownloaded);
}
/** /**
* Downloads the media. * Downloads the content.
* *
* @throws DownloadException Thrown if the media cannot be downloaded. * @param progressListener A listener to receive progress updates, or {@code null}.
* @throws DownloadException Thrown if the content cannot be downloaded.
* @throws InterruptedException If the thread has been interrupted. * @throws InterruptedException If the thread has been interrupted.
* @throws IOException Thrown when there is an io error while downloading. * @throws IOException Thrown when there is an io error while downloading.
*/ */
void download() throws InterruptedException, IOException; void download(@Nullable ProgressListener progressListener)
throws InterruptedException, IOException;
/** Interrupts any current download operation and prevents future operations from running. */ /** Cancels the download operation and prevents future download operations from running. */
void cancel(); void cancel();
/** Returns the total number of downloaded bytes. */
long getDownloadedBytes();
/** Returns the total size of the media, or {@link C#LENGTH_UNSET} if unknown. */
long getTotalBytes();
/**
* Returns the estimated download percentage, or {@link C#PERCENTAGE_UNSET} if no estimate is
* available.
*/
float getDownloadPercentage();
/** Returns a {@link CachingCounters} which holds download counters. */
CachingCounters getCounters();
/** /**
* Removes the media. * Removes the content.
* *
* @throws InterruptedException Thrown if the thread was interrupted. * @throws InterruptedException Thrown if the thread was interrupted.
*/ */
......
...@@ -23,7 +23,6 @@ import com.google.android.exoplayer2.upstream.cache.Cache; ...@@ -23,7 +23,6 @@ import com.google.android.exoplayer2.upstream.cache.Cache;
import com.google.android.exoplayer2.upstream.cache.CacheDataSource; import com.google.android.exoplayer2.upstream.cache.CacheDataSource;
import com.google.android.exoplayer2.upstream.cache.CacheKeyFactory; import com.google.android.exoplayer2.upstream.cache.CacheKeyFactory;
import com.google.android.exoplayer2.upstream.cache.CacheUtil; import com.google.android.exoplayer2.upstream.cache.CacheUtil;
import com.google.android.exoplayer2.upstream.cache.CacheUtil.CachingCounters;
import com.google.android.exoplayer2.util.PriorityTaskManager; import com.google.android.exoplayer2.util.PriorityTaskManager;
import java.io.IOException; import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
...@@ -40,7 +39,6 @@ public final class ProgressiveDownloader implements Downloader { ...@@ -40,7 +39,6 @@ public final class ProgressiveDownloader implements Downloader {
private final CacheDataSource dataSource; private final CacheDataSource dataSource;
private final CacheKeyFactory cacheKeyFactory; private final CacheKeyFactory cacheKeyFactory;
private final PriorityTaskManager priorityTaskManager; private final PriorityTaskManager priorityTaskManager;
private final CacheUtil.CachingCounters cachingCounters;
private final AtomicBoolean isCanceled; private final AtomicBoolean isCanceled;
/** /**
...@@ -62,12 +60,12 @@ public final class ProgressiveDownloader implements Downloader { ...@@ -62,12 +60,12 @@ public final class ProgressiveDownloader implements Downloader {
this.dataSource = constructorHelper.createCacheDataSource(); this.dataSource = constructorHelper.createCacheDataSource();
this.cacheKeyFactory = constructorHelper.getCacheKeyFactory(); this.cacheKeyFactory = constructorHelper.getCacheKeyFactory();
this.priorityTaskManager = constructorHelper.getPriorityTaskManager(); this.priorityTaskManager = constructorHelper.getPriorityTaskManager();
cachingCounters = new CachingCounters();
isCanceled = new AtomicBoolean(); isCanceled = new AtomicBoolean();
} }
@Override @Override
public void download() throws InterruptedException, IOException { public void download(@Nullable ProgressListener progressListener)
throws InterruptedException, IOException {
priorityTaskManager.add(C.PRIORITY_DOWNLOAD); priorityTaskManager.add(C.PRIORITY_DOWNLOAD);
try { try {
CacheUtil.cache( CacheUtil.cache(
...@@ -78,7 +76,7 @@ public final class ProgressiveDownloader implements Downloader { ...@@ -78,7 +76,7 @@ public final class ProgressiveDownloader implements Downloader {
new byte[BUFFER_SIZE_BYTES], new byte[BUFFER_SIZE_BYTES],
priorityTaskManager, priorityTaskManager,
C.PRIORITY_DOWNLOAD, C.PRIORITY_DOWNLOAD,
cachingCounters, progressListener == null ? null : new ProgressForwarder(progressListener),
isCanceled, isCanceled,
/* enableEOFException= */ true); /* enableEOFException= */ true);
} finally { } finally {
...@@ -92,27 +90,25 @@ public final class ProgressiveDownloader implements Downloader { ...@@ -92,27 +90,25 @@ public final class ProgressiveDownloader implements Downloader {
} }
@Override @Override
public long getDownloadedBytes() { public void remove() {
return cachingCounters.totalCachedBytes(); CacheUtil.remove(dataSpec, cache, cacheKeyFactory);
} }
@Override private static final class ProgressForwarder implements CacheUtil.ProgressListener {
public long getTotalBytes() {
return cachingCounters.contentLength;
}
@Override private final ProgressListener progessListener;
public float getDownloadPercentage() {
return cachingCounters.percentage;
}
@Override public ProgressForwarder(ProgressListener progressListener) {
public CachingCounters getCounters() { this.progessListener = progressListener;
return cachingCounters; }
}
@Override @Override
public void remove() { public void onProgress(long contentLength, long bytesCached, long newBytesCached) {
CacheUtil.remove(dataSpec, cache, cacheKeyFactory); float percentDownloaded =
contentLength == C.LENGTH_UNSET || contentLength == 0
? C.PERCENTAGE_UNSET
: ((bytesCached * 100f) / contentLength);
progessListener.onProgress(contentLength, bytesCached, percentDownloaded);
}
} }
} }
...@@ -76,9 +76,9 @@ public class DefaultDownloadIndexTest { ...@@ -76,9 +76,9 @@ public class DefaultDownloadIndexTest {
.setUri("different uri") .setUri("different uri")
.setCacheKey("different cacheKey") .setCacheKey("different cacheKey")
.setState(Download.STATE_FAILED) .setState(Download.STATE_FAILED)
.setDownloadPercentage(50) .setPercentDownloaded(50)
.setDownloadedBytes(200) .setBytesDownloaded(200)
.setTotalBytes(400) .setContentLength(400)
.setFailureReason(Download.FAILURE_REASON_UNKNOWN) .setFailureReason(Download.FAILURE_REASON_UNKNOWN)
.setStopReason(0x12345678) .setStopReason(0x12345678)
.setStartTimeMs(10) .setStartTimeMs(10)
...@@ -300,10 +300,10 @@ public class DefaultDownloadIndexTest { ...@@ -300,10 +300,10 @@ public class DefaultDownloadIndexTest {
assertThat(download.state).isEqualTo(that.state); assertThat(download.state).isEqualTo(that.state);
assertThat(download.startTimeMs).isEqualTo(that.startTimeMs); assertThat(download.startTimeMs).isEqualTo(that.startTimeMs);
assertThat(download.updateTimeMs).isEqualTo(that.updateTimeMs); assertThat(download.updateTimeMs).isEqualTo(that.updateTimeMs);
assertThat(download.failureReason).isEqualTo(that.failureReason); assertThat(download.contentLength).isEqualTo(that.contentLength);
assertThat(download.stopReason).isEqualTo(that.stopReason); assertThat(download.stopReason).isEqualTo(that.stopReason);
assertThat(download.getDownloadPercentage()).isEqualTo(that.getDownloadPercentage()); assertThat(download.failureReason).isEqualTo(that.failureReason);
assertThat(download.getDownloadedBytes()).isEqualTo(that.getDownloadedBytes()); assertThat(download.getPercentDownloaded()).isEqualTo(that.getPercentDownloaded());
assertThat(download.getTotalBytes()).isEqualTo(that.getTotalBytes()); assertThat(download.getBytesDownloaded()).isEqualTo(that.getBytesDownloaded());
} }
} }
...@@ -17,7 +17,7 @@ package com.google.android.exoplayer2.offline; ...@@ -17,7 +17,7 @@ package com.google.android.exoplayer2.offline;
import android.net.Uri; import android.net.Uri;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import com.google.android.exoplayer2.upstream.cache.CacheUtil.CachingCounters; import com.google.android.exoplayer2.C;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
...@@ -29,52 +29,61 @@ import java.util.List; ...@@ -29,52 +29,61 @@ import java.util.List;
* creation for tests. Tests must avoid depending on the default values but explicitly set tested * creation for tests. Tests must avoid depending on the default values but explicitly set tested
* parameters during test initialization. * parameters during test initialization.
*/ */
class DownloadBuilder { /* package */ final class DownloadBuilder {
private final CachingCounters counters;
private final DownloadProgress progress;
private String id; private String id;
private String type; private String type;
private Uri uri; private Uri uri;
private List<StreamKey> streamKeys;
@Nullable private String cacheKey; @Nullable private String cacheKey;
private byte[] customMetadata;
private int state; private int state;
private int failureReason;
private int stopReason;
private long startTimeMs; private long startTimeMs;
private long updateTimeMs; private long updateTimeMs;
private List<StreamKey> streamKeys; private long contentLength;
private byte[] customMetadata; private int stopReason;
private int failureReason;
DownloadBuilder(String id) { /* package */ DownloadBuilder(String id) {
this(id, "type", Uri.parse("uri"), /* cacheKey= */ null, new byte[0], Collections.emptyList()); this(
id,
"type",
Uri.parse("uri"),
/* streamKeys= */ Collections.emptyList(),
/* cacheKey= */ null,
new byte[0]);
} }
DownloadBuilder(DownloadRequest request) { /* package */ DownloadBuilder(DownloadRequest request) {
this( this(
request.id, request.id,
request.type, request.type,
request.uri, request.uri,
request.streamKeys,
request.customCacheKey, request.customCacheKey,
request.data, request.data);
request.streamKeys);
} }
DownloadBuilder( /* package */ DownloadBuilder(
String id, String id,
String type, String type,
Uri uri, Uri uri,
List<StreamKey> streamKeys,
String cacheKey, String cacheKey,
byte[] customMetadata, byte[] customMetadata) {
List<StreamKey> streamKeys) {
this.id = id; this.id = id;
this.type = type; this.type = type;
this.uri = uri; this.uri = uri;
this.streamKeys = streamKeys;
this.cacheKey = cacheKey; this.cacheKey = cacheKey;
this.customMetadata = customMetadata;
this.state = Download.STATE_QUEUED; this.state = Download.STATE_QUEUED;
this.contentLength = C.LENGTH_UNSET;
this.failureReason = Download.FAILURE_REASON_NONE; this.failureReason = Download.FAILURE_REASON_NONE;
this.startTimeMs = (long) 0; this.progress = new DownloadProgress();
this.updateTimeMs = (long) 0;
this.streamKeys = streamKeys;
this.customMetadata = customMetadata;
this.counters = new CachingCounters();
} }
public DownloadBuilder setId(String id) { public DownloadBuilder setId(String id) {
...@@ -107,18 +116,18 @@ class DownloadBuilder { ...@@ -107,18 +116,18 @@ class DownloadBuilder {
return this; return this;
} }
public DownloadBuilder setDownloadPercentage(float downloadPercentage) { public DownloadBuilder setPercentDownloaded(float percentDownloaded) {
counters.percentage = downloadPercentage; progress.percentDownloaded = percentDownloaded;
return this; return this;
} }
public DownloadBuilder setDownloadedBytes(long downloadedBytes) { public DownloadBuilder setBytesDownloaded(long bytesDownloaded) {
counters.alreadyCachedBytes = downloadedBytes; progress.bytesDownloaded = bytesDownloaded;
return this; return this;
} }
public DownloadBuilder setTotalBytes(long totalBytes) { public DownloadBuilder setContentLength(long contentLength) {
counters.contentLength = totalBytes; this.contentLength = contentLength;
return this; return this;
} }
...@@ -156,6 +165,13 @@ class DownloadBuilder { ...@@ -156,6 +165,13 @@ class DownloadBuilder {
DownloadRequest request = DownloadRequest request =
new DownloadRequest(id, type, uri, streamKeys, cacheKey, customMetadata); new DownloadRequest(id, type, uri, streamKeys, cacheKey, customMetadata);
return new Download( return new Download(
request, state, failureReason, stopReason, startTimeMs, updateTimeMs, counters); request,
state,
startTimeMs,
updateTimeMs,
contentLength,
stopReason,
failureReason,
progress);
} }
} }
...@@ -20,13 +20,13 @@ import static com.google.common.truth.Truth.assertThat; ...@@ -20,13 +20,13 @@ import static com.google.common.truth.Truth.assertThat;
import android.net.Uri; import android.net.Uri;
import androidx.test.core.app.ApplicationProvider; import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.offline.Download.State; import com.google.android.exoplayer2.offline.Download.State;
import com.google.android.exoplayer2.scheduler.Requirements; import com.google.android.exoplayer2.scheduler.Requirements;
import com.google.android.exoplayer2.testutil.DummyMainThread; import com.google.android.exoplayer2.testutil.DummyMainThread;
import com.google.android.exoplayer2.testutil.DummyMainThread.TestRunnable; import com.google.android.exoplayer2.testutil.DummyMainThread.TestRunnable;
import com.google.android.exoplayer2.testutil.TestDownloadManagerListener; import com.google.android.exoplayer2.testutil.TestDownloadManagerListener;
import com.google.android.exoplayer2.testutil.TestUtil; import com.google.android.exoplayer2.testutil.TestUtil;
import com.google.android.exoplayer2.upstream.cache.CacheUtil.CachingCounters;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
...@@ -184,7 +184,7 @@ public class DownloadManagerTest { ...@@ -184,7 +184,7 @@ public class DownloadManagerTest {
int tooManyRetries = MIN_RETRY_COUNT + 10; int tooManyRetries = MIN_RETRY_COUNT + 10;
for (int i = 0; i < tooManyRetries; i++) { for (int i = 0; i < tooManyRetries; i++) {
downloader.increaseDownloadedByteCount(); downloader.incrementBytesDownloaded();
downloader.assertStarted(MAX_RETRY_DELAY).fail(); downloader.assertStarted(MAX_RETRY_DELAY).fail();
} }
downloader.assertStarted(MAX_RETRY_DELAY).unblock(); downloader.assertStarted(MAX_RETRY_DELAY).unblock();
...@@ -555,11 +555,11 @@ public class DownloadManagerTest { ...@@ -555,11 +555,11 @@ public class DownloadManagerTest {
private static void assertEqualIgnoringTimeFields(Download download, Download that) { private static void assertEqualIgnoringTimeFields(Download download, Download that) {
assertThat(download.request).isEqualTo(that.request); assertThat(download.request).isEqualTo(that.request);
assertThat(download.state).isEqualTo(that.state); assertThat(download.state).isEqualTo(that.state);
assertThat(download.contentLength).isEqualTo(that.contentLength);
assertThat(download.failureReason).isEqualTo(that.failureReason); assertThat(download.failureReason).isEqualTo(that.failureReason);
assertThat(download.stopReason).isEqualTo(that.stopReason); assertThat(download.stopReason).isEqualTo(that.stopReason);
assertThat(download.getDownloadPercentage()).isEqualTo(that.getDownloadPercentage()); assertThat(download.getPercentDownloaded()).isEqualTo(that.getPercentDownloaded());
assertThat(download.getDownloadedBytes()).isEqualTo(that.getDownloadedBytes()); assertThat(download.getBytesDownloaded()).isEqualTo(that.getBytesDownloaded());
assertThat(download.getTotalBytes()).isEqualTo(that.getTotalBytes());
} }
private static DownloadRequest createDownloadRequest() { private static DownloadRequest createDownloadRequest() {
...@@ -722,21 +722,23 @@ public class DownloadManagerTest { ...@@ -722,21 +722,23 @@ public class DownloadManagerTest {
private volatile boolean cancelled; private volatile boolean cancelled;
private volatile boolean enableDownloadIOException; private volatile boolean enableDownloadIOException;
private volatile int startCount; private volatile int startCount;
private CachingCounters counters; private volatile int bytesDownloaded;
private FakeDownloader() { private FakeDownloader() {
this.started = new CountDownLatch(1); this.started = new CountDownLatch(1);
this.blocker = new com.google.android.exoplayer2.util.ConditionVariable(); this.blocker = new com.google.android.exoplayer2.util.ConditionVariable();
counters = new CachingCounters();
} }
@SuppressWarnings({"NonAtomicOperationOnVolatileField", "NonAtomicVolatileUpdate"}) @SuppressWarnings({"NonAtomicOperationOnVolatileField", "NonAtomicVolatileUpdate"})
@Override @Override
public void download() throws InterruptedException, IOException { public void download(ProgressListener listener) throws InterruptedException, IOException {
// It's ok to update this directly as no other thread will update it. // It's ok to update this directly as no other thread will update it.
startCount++; startCount++;
started.countDown(); started.countDown();
block(); block();
if (bytesDownloaded > 0) {
listener.onProgress(C.LENGTH_UNSET, bytesDownloaded, C.PERCENTAGE_UNSET);
}
if (enableDownloadIOException) { if (enableDownloadIOException) {
enableDownloadIOException = false; enableDownloadIOException = false;
throw new IOException(); throw new IOException();
...@@ -783,7 +785,7 @@ public class DownloadManagerTest { ...@@ -783,7 +785,7 @@ public class DownloadManagerTest {
return this; return this;
} }
private FakeDownloader assertStartCount(int count) throws InterruptedException { private FakeDownloader assertStartCount(int count) {
assertThat(startCount).isEqualTo(count); assertThat(startCount).isEqualTo(count);
return this; return this;
} }
...@@ -823,34 +825,14 @@ public class DownloadManagerTest { ...@@ -823,34 +825,14 @@ public class DownloadManagerTest {
return unblock(); return unblock();
} }
@Override
public long getDownloadedBytes() {
return counters.newlyCachedBytes;
}
@Override
public long getTotalBytes() {
return counters.contentLength;
}
@Override
public float getDownloadPercentage() {
return counters.percentage;
}
@Override
public CachingCounters getCounters() {
return counters;
}
private void assertDoesNotStart() throws InterruptedException { private void assertDoesNotStart() throws InterruptedException {
Thread.sleep(ASSERT_FALSE_TIME); Thread.sleep(ASSERT_FALSE_TIME);
assertThat(started.getCount()).isEqualTo(1); assertThat(started.getCount()).isEqualTo(1);
} }
@SuppressWarnings({"NonAtomicOperationOnVolatileField", "NonAtomicVolatileUpdate"}) @SuppressWarnings({"NonAtomicOperationOnVolatileField", "NonAtomicVolatileUpdate"})
private void increaseDownloadedByteCount() { private void incrementBytesDownloaded() {
counters.newlyCachedBytes++; bytesDownloaded++;
} }
} }
} }
...@@ -343,7 +343,7 @@ public final class CacheDataSourceTest { ...@@ -343,7 +343,7 @@ public final class CacheDataSourceTest {
cache, cache,
/* cacheKeyFactory= */ null, /* cacheKeyFactory= */ null,
upstream2, upstream2,
/* counters= */ null, /* progressListener= */ null,
/* isCanceled= */ null); /* isCanceled= */ null);
// Read the rest of the data. // Read the rest of the data.
...@@ -392,7 +392,7 @@ public final class CacheDataSourceTest { ...@@ -392,7 +392,7 @@ public final class CacheDataSourceTest {
cache, cache,
/* cacheKeyFactory= */ null, /* cacheKeyFactory= */ null,
upstream2, upstream2,
/* counters= */ null, /* progressListener= */ null,
/* isCanceled= */ null); /* isCanceled= */ null);
// Read the rest of the data. // Read the rest of the data.
...@@ -416,7 +416,7 @@ public final class CacheDataSourceTest { ...@@ -416,7 +416,7 @@ public final class CacheDataSourceTest {
cache, cache,
/* cacheKeyFactory= */ null, /* cacheKeyFactory= */ null,
upstream, upstream,
/* counters= */ null, /* progressListener= */ null,
/* isCanceled= */ null); /* isCanceled= */ null);
// Create cache read-only CacheDataSource. // Create cache read-only CacheDataSource.
...@@ -452,7 +452,7 @@ public final class CacheDataSourceTest { ...@@ -452,7 +452,7 @@ public final class CacheDataSourceTest {
cache, cache,
/* cacheKeyFactory= */ null, /* cacheKeyFactory= */ null,
upstream, upstream,
/* counters= */ null, /* progressListener= */ null,
/* isCanceled= */ null); /* isCanceled= */ null);
// Create blocking CacheDataSource. // Create blocking CacheDataSource.
......
...@@ -45,7 +45,7 @@ import java.util.List; ...@@ -45,7 +45,7 @@ import java.util.List;
* <p>Example usage: * <p>Example usage:
* *
* <pre>{@code * <pre>{@code
* SimpleCache cache = new SimpleCache(downloadFolder, new NoOpCacheEvictor()); * SimpleCache cache = new SimpleCache(downloadFolder, new NoOpCacheEvictor(), databaseProvider);
* DefaultHttpDataSourceFactory factory = new DefaultHttpDataSourceFactory("ExoPlayer", null); * DefaultHttpDataSourceFactory factory = new DefaultHttpDataSourceFactory("ExoPlayer", null);
* DownloaderConstructorHelper constructorHelper = * DownloaderConstructorHelper constructorHelper =
* new DownloaderConstructorHelper(cache, factory); * new DownloaderConstructorHelper(cache, factory);
...@@ -55,7 +55,7 @@ import java.util.List; ...@@ -55,7 +55,7 @@ import java.util.List;
* new DashDownloader( * new DashDownloader(
* manifestUrl, Collections.singletonList(new StreamKey(0, 0, 0)), constructorHelper); * manifestUrl, Collections.singletonList(new StreamKey(0, 0, 0)), constructorHelper);
* // Perform the download. * // Perform the download.
* dashDownloader.download(); * dashDownloader.download(progressListener);
* // Access downloaded data using CacheDataSource * // Access downloaded data using CacheDataSource
* CacheDataSource cacheDataSource = * CacheDataSource cacheDataSource =
* new CacheDataSource(cache, factory.createDataSource(), CacheDataSource.FLAG_BLOCK_ON_CACHE); * new CacheDataSource(cache, factory.createDataSource(), CacheDataSource.FLAG_BLOCK_ON_CACHE);
......
...@@ -62,6 +62,7 @@ public class DashDownloaderTest { ...@@ -62,6 +62,7 @@ public class DashDownloaderTest {
private SimpleCache cache; private SimpleCache cache;
private File tempFolder; private File tempFolder;
private ProgressListener progressListener;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
...@@ -69,6 +70,7 @@ public class DashDownloaderTest { ...@@ -69,6 +70,7 @@ public class DashDownloaderTest {
tempFolder = tempFolder =
Util.createTempDirectory(ApplicationProvider.getApplicationContext(), "ExoPlayerTest"); Util.createTempDirectory(ApplicationProvider.getApplicationContext(), "ExoPlayerTest");
cache = new SimpleCache(tempFolder, new NoOpCacheEvictor()); cache = new SimpleCache(tempFolder, new NoOpCacheEvictor());
progressListener = new ProgressListener();
} }
@After @After
...@@ -77,7 +79,7 @@ public class DashDownloaderTest { ...@@ -77,7 +79,7 @@ public class DashDownloaderTest {
} }
@Test @Test
public void testCreateWithDefaultDownloaderFactory() throws Exception { public void testCreateWithDefaultDownloaderFactory() {
DownloaderConstructorHelper constructorHelper = DownloaderConstructorHelper constructorHelper =
new DownloaderConstructorHelper(Mockito.mock(Cache.class), DummyDataSource.FACTORY); new DownloaderConstructorHelper(Mockito.mock(Cache.class), DummyDataSource.FACTORY);
DownloaderFactory factory = new DefaultDownloaderFactory(constructorHelper); DownloaderFactory factory = new DefaultDownloaderFactory(constructorHelper);
...@@ -105,7 +107,7 @@ public class DashDownloaderTest { ...@@ -105,7 +107,7 @@ public class DashDownloaderTest {
.setRandomData("audio_segment_3", 6); .setRandomData("audio_segment_3", 6);
DashDownloader dashDownloader = getDashDownloader(fakeDataSet, new StreamKey(0, 0, 0)); DashDownloader dashDownloader = getDashDownloader(fakeDataSet, new StreamKey(0, 0, 0));
dashDownloader.download(); dashDownloader.download(progressListener);
assertCachedData(cache, fakeDataSet); assertCachedData(cache, fakeDataSet);
} }
...@@ -124,7 +126,7 @@ public class DashDownloaderTest { ...@@ -124,7 +126,7 @@ public class DashDownloaderTest {
.setRandomData("audio_segment_3", 6); .setRandomData("audio_segment_3", 6);
DashDownloader dashDownloader = getDashDownloader(fakeDataSet, new StreamKey(0, 0, 0)); DashDownloader dashDownloader = getDashDownloader(fakeDataSet, new StreamKey(0, 0, 0));
dashDownloader.download(); dashDownloader.download(progressListener);
assertCachedData(cache, fakeDataSet); assertCachedData(cache, fakeDataSet);
} }
...@@ -143,7 +145,7 @@ public class DashDownloaderTest { ...@@ -143,7 +145,7 @@ public class DashDownloaderTest {
DashDownloader dashDownloader = DashDownloader dashDownloader =
getDashDownloader(fakeDataSet, new StreamKey(0, 0, 0), new StreamKey(0, 1, 0)); getDashDownloader(fakeDataSet, new StreamKey(0, 0, 0), new StreamKey(0, 1, 0));
dashDownloader.download(); dashDownloader.download(progressListener);
assertCachedData(cache, fakeDataSet); assertCachedData(cache, fakeDataSet);
} }
...@@ -164,7 +166,7 @@ public class DashDownloaderTest { ...@@ -164,7 +166,7 @@ public class DashDownloaderTest {
.setRandomData("period_2_segment_3", 3); .setRandomData("period_2_segment_3", 3);
DashDownloader dashDownloader = getDashDownloader(fakeDataSet); DashDownloader dashDownloader = getDashDownloader(fakeDataSet);
dashDownloader.download(); dashDownloader.download(progressListener);
assertCachedData(cache, fakeDataSet); assertCachedData(cache, fakeDataSet);
} }
...@@ -186,7 +188,7 @@ public class DashDownloaderTest { ...@@ -186,7 +188,7 @@ public class DashDownloaderTest {
DashDownloader dashDownloader = DashDownloader dashDownloader =
getDashDownloader(factory, new StreamKey(0, 0, 0), new StreamKey(0, 1, 0)); getDashDownloader(factory, new StreamKey(0, 0, 0), new StreamKey(0, 1, 0));
dashDownloader.download(); dashDownloader.download(progressListener);
DataSpec[] openedDataSpecs = fakeDataSource.getAndClearOpenedDataSpecs(); DataSpec[] openedDataSpecs = fakeDataSource.getAndClearOpenedDataSpecs();
assertThat(openedDataSpecs.length).isEqualTo(8); assertThat(openedDataSpecs.length).isEqualTo(8);
...@@ -218,7 +220,7 @@ public class DashDownloaderTest { ...@@ -218,7 +220,7 @@ public class DashDownloaderTest {
DashDownloader dashDownloader = DashDownloader dashDownloader =
getDashDownloader(factory, new StreamKey(0, 0, 0), new StreamKey(1, 0, 0)); getDashDownloader(factory, new StreamKey(0, 0, 0), new StreamKey(1, 0, 0));
dashDownloader.download(); dashDownloader.download(progressListener);
DataSpec[] openedDataSpecs = fakeDataSource.getAndClearOpenedDataSpecs(); DataSpec[] openedDataSpecs = fakeDataSource.getAndClearOpenedDataSpecs();
assertThat(openedDataSpecs.length).isEqualTo(8); assertThat(openedDataSpecs.length).isEqualTo(8);
...@@ -248,12 +250,12 @@ public class DashDownloaderTest { ...@@ -248,12 +250,12 @@ public class DashDownloaderTest {
DashDownloader dashDownloader = getDashDownloader(fakeDataSet, new StreamKey(0, 0, 0)); DashDownloader dashDownloader = getDashDownloader(fakeDataSet, new StreamKey(0, 0, 0));
try { try {
dashDownloader.download(); dashDownloader.download(progressListener);
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
// Expected. // Expected.
} }
dashDownloader.download(); dashDownloader.download(progressListener);
assertCachedData(cache, fakeDataSet); assertCachedData(cache, fakeDataSet);
} }
...@@ -272,18 +274,17 @@ public class DashDownloaderTest { ...@@ -272,18 +274,17 @@ public class DashDownloaderTest {
.setRandomData("audio_segment_3", 6); .setRandomData("audio_segment_3", 6);
DashDownloader dashDownloader = getDashDownloader(fakeDataSet, new StreamKey(0, 0, 0)); DashDownloader dashDownloader = getDashDownloader(fakeDataSet, new StreamKey(0, 0, 0));
assertThat(dashDownloader.getDownloadedBytes()).isEqualTo(0);
try { try {
dashDownloader.download(); dashDownloader.download(progressListener);
fail(); fail();
} catch (IOException e) { } catch (IOException e) {
// Failure expected after downloading init data, segment 1 and 2 bytes in segment 2. // Failure expected after downloading init data, segment 1 and 2 bytes in segment 2.
} }
assertThat(dashDownloader.getDownloadedBytes()).isEqualTo(10 + 4 + 2); progressListener.assertBytesDownloaded(10 + 4 + 2);
dashDownloader.download(); dashDownloader.download(progressListener);
assertThat(dashDownloader.getDownloadedBytes()).isEqualTo(10 + 4 + 5 + 6); progressListener.assertBytesDownloaded(10 + 4 + 5 + 6);
} }
@Test @Test
...@@ -301,7 +302,7 @@ public class DashDownloaderTest { ...@@ -301,7 +302,7 @@ public class DashDownloaderTest {
DashDownloader dashDownloader = DashDownloader dashDownloader =
getDashDownloader(fakeDataSet, new StreamKey(0, 0, 0), new StreamKey(0, 1, 0)); getDashDownloader(fakeDataSet, new StreamKey(0, 0, 0), new StreamKey(0, 1, 0));
dashDownloader.download(); dashDownloader.download(progressListener);
dashDownloader.remove(); dashDownloader.remove();
assertCacheEmpty(cache); assertCacheEmpty(cache);
} }
...@@ -315,7 +316,7 @@ public class DashDownloaderTest { ...@@ -315,7 +316,7 @@ public class DashDownloaderTest {
DashDownloader dashDownloader = getDashDownloader(fakeDataSet, new StreamKey(0, 0, 0)); DashDownloader dashDownloader = getDashDownloader(fakeDataSet, new StreamKey(0, 0, 0));
try { try {
dashDownloader.download(); dashDownloader.download(progressListener);
fail(); fail();
} catch (DownloadException e) { } catch (DownloadException e) {
// Expected. // Expected.
...@@ -339,4 +340,17 @@ public class DashDownloaderTest { ...@@ -339,4 +340,17 @@ public class DashDownloaderTest {
return keysList; return keysList;
} }
private static final class ProgressListener implements Downloader.ProgressListener {
private long bytesDownloaded;
@Override
public void onProgress(long contentLength, long bytesDownloaded, float percentDownloaded) {
this.bytesDownloaded = bytesDownloaded;
}
public void assertBytesDownloaded(long bytesDownloaded) {
assertThat(this.bytesDownloaded).isEqualTo(bytesDownloaded);
}
}
} }
...@@ -39,7 +39,7 @@ import java.util.List; ...@@ -39,7 +39,7 @@ import java.util.List;
* <p>Example usage: * <p>Example usage:
* *
* <pre>{@code * <pre>{@code
* SimpleCache cache = new SimpleCache(downloadFolder, new NoOpCacheEvictor()); * SimpleCache cache = new SimpleCache(downloadFolder, new NoOpCacheEvictor(), databaseProvider);
* DefaultHttpDataSourceFactory factory = new DefaultHttpDataSourceFactory("ExoPlayer", null); * DefaultHttpDataSourceFactory factory = new DefaultHttpDataSourceFactory("ExoPlayer", null);
* DownloaderConstructorHelper constructorHelper = * DownloaderConstructorHelper constructorHelper =
* new DownloaderConstructorHelper(cache, factory); * new DownloaderConstructorHelper(cache, factory);
...@@ -50,7 +50,7 @@ import java.util.List; ...@@ -50,7 +50,7 @@ import java.util.List;
* Collections.singletonList(new StreamKey(HlsMasterPlaylist.GROUP_INDEX_VARIANT, 0)), * Collections.singletonList(new StreamKey(HlsMasterPlaylist.GROUP_INDEX_VARIANT, 0)),
* constructorHelper); * constructorHelper);
* // Perform the download. * // Perform the download.
* hlsDownloader.download(); * hlsDownloader.download(progressListener);
* // Access downloaded data using CacheDataSource * // Access downloaded data using CacheDataSource
* CacheDataSource cacheDataSource = * CacheDataSource cacheDataSource =
* new CacheDataSource(cache, factory.createDataSource(), CacheDataSource.FLAG_BLOCK_ON_CACHE); * new CacheDataSource(cache, factory.createDataSource(), CacheDataSource.FLAG_BLOCK_ON_CACHE);
......
...@@ -67,6 +67,7 @@ public class HlsDownloaderTest { ...@@ -67,6 +67,7 @@ public class HlsDownloaderTest {
private SimpleCache cache; private SimpleCache cache;
private File tempFolder; private File tempFolder;
private ProgressListener progressListener;
private FakeDataSet fakeDataSet; private FakeDataSet fakeDataSet;
@Before @Before
...@@ -74,7 +75,7 @@ public class HlsDownloaderTest { ...@@ -74,7 +75,7 @@ public class HlsDownloaderTest {
tempFolder = tempFolder =
Util.createTempDirectory(ApplicationProvider.getApplicationContext(), "ExoPlayerTest"); Util.createTempDirectory(ApplicationProvider.getApplicationContext(), "ExoPlayerTest");
cache = new SimpleCache(tempFolder, new NoOpCacheEvictor()); cache = new SimpleCache(tempFolder, new NoOpCacheEvictor());
progressListener = new ProgressListener();
fakeDataSet = fakeDataSet =
new FakeDataSet() new FakeDataSet()
.setData(MASTER_PLAYLIST_URI, MASTER_PLAYLIST_DATA) .setData(MASTER_PLAYLIST_URI, MASTER_PLAYLIST_DATA)
...@@ -94,7 +95,7 @@ public class HlsDownloaderTest { ...@@ -94,7 +95,7 @@ public class HlsDownloaderTest {
} }
@Test @Test
public void testCreateWithDefaultDownloaderFactory() throws Exception { public void testCreateWithDefaultDownloaderFactory() {
DownloaderConstructorHelper constructorHelper = DownloaderConstructorHelper constructorHelper =
new DownloaderConstructorHelper(Mockito.mock(Cache.class), DummyDataSource.FACTORY); new DownloaderConstructorHelper(Mockito.mock(Cache.class), DummyDataSource.FACTORY);
DownloaderFactory factory = new DefaultDownloaderFactory(constructorHelper); DownloaderFactory factory = new DefaultDownloaderFactory(constructorHelper);
...@@ -115,17 +116,16 @@ public class HlsDownloaderTest { ...@@ -115,17 +116,16 @@ public class HlsDownloaderTest {
public void testCounterMethods() throws Exception { public void testCounterMethods() throws Exception {
HlsDownloader downloader = HlsDownloader downloader =
getHlsDownloader(MASTER_PLAYLIST_URI, getKeys(MASTER_MEDIA_PLAYLIST_1_INDEX)); getHlsDownloader(MASTER_PLAYLIST_URI, getKeys(MASTER_MEDIA_PLAYLIST_1_INDEX));
downloader.download(); downloader.download(progressListener);
assertThat(downloader.getDownloadedBytes()) progressListener.assertBytesDownloaded(MEDIA_PLAYLIST_DATA.length + 10 + 11 + 12);
.isEqualTo(MEDIA_PLAYLIST_DATA.length + 10 + 11 + 12);
} }
@Test @Test
public void testDownloadRepresentation() throws Exception { public void testDownloadRepresentation() throws Exception {
HlsDownloader downloader = HlsDownloader downloader =
getHlsDownloader(MASTER_PLAYLIST_URI, getKeys(MASTER_MEDIA_PLAYLIST_1_INDEX)); getHlsDownloader(MASTER_PLAYLIST_URI, getKeys(MASTER_MEDIA_PLAYLIST_1_INDEX));
downloader.download(); downloader.download(progressListener);
assertCachedData( assertCachedData(
cache, cache,
...@@ -143,7 +143,7 @@ public class HlsDownloaderTest { ...@@ -143,7 +143,7 @@ public class HlsDownloaderTest {
getHlsDownloader( getHlsDownloader(
MASTER_PLAYLIST_URI, MASTER_PLAYLIST_URI,
getKeys(MASTER_MEDIA_PLAYLIST_1_INDEX, MASTER_MEDIA_PLAYLIST_2_INDEX)); getKeys(MASTER_MEDIA_PLAYLIST_1_INDEX, MASTER_MEDIA_PLAYLIST_2_INDEX));
downloader.download(); downloader.download(progressListener);
assertCachedData(cache, fakeDataSet); assertCachedData(cache, fakeDataSet);
} }
...@@ -162,7 +162,7 @@ public class HlsDownloaderTest { ...@@ -162,7 +162,7 @@ public class HlsDownloaderTest {
.setRandomData(MEDIA_PLAYLIST_3_DIR + "fileSequence2.ts", 15); .setRandomData(MEDIA_PLAYLIST_3_DIR + "fileSequence2.ts", 15);
HlsDownloader downloader = getHlsDownloader(MASTER_PLAYLIST_URI, getKeys()); HlsDownloader downloader = getHlsDownloader(MASTER_PLAYLIST_URI, getKeys());
downloader.download(); downloader.download(progressListener);
assertCachedData(cache, fakeDataSet); assertCachedData(cache, fakeDataSet);
} }
...@@ -173,7 +173,7 @@ public class HlsDownloaderTest { ...@@ -173,7 +173,7 @@ public class HlsDownloaderTest {
getHlsDownloader( getHlsDownloader(
MASTER_PLAYLIST_URI, MASTER_PLAYLIST_URI,
getKeys(MASTER_MEDIA_PLAYLIST_1_INDEX, MASTER_MEDIA_PLAYLIST_2_INDEX)); getKeys(MASTER_MEDIA_PLAYLIST_1_INDEX, MASTER_MEDIA_PLAYLIST_2_INDEX));
downloader.download(); downloader.download(progressListener);
downloader.remove(); downloader.remove();
assertCacheEmpty(cache); assertCacheEmpty(cache);
...@@ -182,7 +182,7 @@ public class HlsDownloaderTest { ...@@ -182,7 +182,7 @@ public class HlsDownloaderTest {
@Test @Test
public void testDownloadMediaPlaylist() throws Exception { public void testDownloadMediaPlaylist() throws Exception {
HlsDownloader downloader = getHlsDownloader(MEDIA_PLAYLIST_1_URI, getKeys()); HlsDownloader downloader = getHlsDownloader(MEDIA_PLAYLIST_1_URI, getKeys());
downloader.download(); downloader.download(progressListener);
assertCachedData( assertCachedData(
cache, cache,
...@@ -205,7 +205,7 @@ public class HlsDownloaderTest { ...@@ -205,7 +205,7 @@ public class HlsDownloaderTest {
.setRandomData("fileSequence2.ts", 12); .setRandomData("fileSequence2.ts", 12);
HlsDownloader downloader = getHlsDownloader(ENC_MEDIA_PLAYLIST_URI, getKeys()); HlsDownloader downloader = getHlsDownloader(ENC_MEDIA_PLAYLIST_URI, getKeys());
downloader.download(); downloader.download(progressListener);
assertCachedData(cache, fakeDataSet); assertCachedData(cache, fakeDataSet);
} }
...@@ -222,4 +222,18 @@ public class HlsDownloaderTest { ...@@ -222,4 +222,18 @@ public class HlsDownloaderTest {
} }
return streamKeys; return streamKeys;
} }
private static final class ProgressListener implements Downloader.ProgressListener {
private long bytesDownloaded;
@Override
public void onProgress(long contentLength, long bytesDownloaded, float percentDownloaded) {
this.bytesDownloaded = bytesDownloaded;
}
public void assertBytesDownloaded(long bytesDownloaded) {
assertThat(this.bytesDownloaded).isEqualTo(bytesDownloaded);
}
}
} }
...@@ -37,7 +37,7 @@ import java.util.List; ...@@ -37,7 +37,7 @@ import java.util.List;
* <p>Example usage: * <p>Example usage:
* *
* <pre>{@code * <pre>{@code
* SimpleCache cache = new SimpleCache(downloadFolder, new NoOpCacheEvictor()); * SimpleCache cache = new SimpleCache(downloadFolder, new NoOpCacheEvictor(), databaseProvider);
* DefaultHttpDataSourceFactory factory = new DefaultHttpDataSourceFactory("ExoPlayer", null); * DefaultHttpDataSourceFactory factory = new DefaultHttpDataSourceFactory("ExoPlayer", null);
* DownloaderConstructorHelper constructorHelper = * DownloaderConstructorHelper constructorHelper =
* new DownloaderConstructorHelper(cache, factory); * new DownloaderConstructorHelper(cache, factory);
...@@ -48,7 +48,7 @@ import java.util.List; ...@@ -48,7 +48,7 @@ import java.util.List;
* Collections.singletonList(new StreamKey(0, 0)), * Collections.singletonList(new StreamKey(0, 0)),
* constructorHelper); * constructorHelper);
* // Perform the download. * // Perform the download.
* ssDownloader.download(); * ssDownloader.download(progressListener);
* // Access downloaded data using CacheDataSource * // Access downloaded data using CacheDataSource
* CacheDataSource cacheDataSource = * CacheDataSource cacheDataSource =
* new CacheDataSource(cache, factory.createDataSource(), CacheDataSource.FLAG_BLOCK_ON_CACHE); * new CacheDataSource(cache, factory.createDataSource(), CacheDataSource.FLAG_BLOCK_ON_CACHE);
......
...@@ -75,12 +75,12 @@ public final class DownloadNotificationHelper { ...@@ -75,12 +75,12 @@ public final class DownloadNotificationHelper {
continue; continue;
} }
haveDownloadTasks = true; haveDownloadTasks = true;
float downloadPercentage = download.getDownloadPercentage(); float downloadPercentage = download.getPercentDownloaded();
if (downloadPercentage != C.PERCENTAGE_UNSET) { if (downloadPercentage != C.PERCENTAGE_UNSET) {
allDownloadPercentagesUnknown = false; allDownloadPercentagesUnknown = false;
totalPercentage += downloadPercentage; totalPercentage += downloadPercentage;
} }
haveDownloadedBytes |= download.getDownloadedBytes() > 0; haveDownloadedBytes |= download.getBytesDownloaded() > 0;
downloadTaskCount++; downloadTaskCount++;
} }
......
...@@ -89,7 +89,7 @@ public final class DashDownloadTest { ...@@ -89,7 +89,7 @@ public final class DashDownloadTest {
@Test @Test
public void testDownload() throws Exception { public void testDownload() throws Exception {
DashDownloader dashDownloader = downloadContent(); DashDownloader dashDownloader = downloadContent();
dashDownloader.download(); dashDownloader.download(/* progressListener= */ null);
testRunner testRunner
.setStreamName("test_h264_fixed_download") .setStreamName("test_h264_fixed_download")
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment