Search in sources :

Example 1 with Downloader

use of com.google.android.exoplayer2.offline.Downloader in project ExoPlayer by google.

the class DashDownloaderTest method createWithDefaultDownloaderFactory.

@Test
public void createWithDefaultDownloaderFactory() {
    CacheDataSource.Factory cacheDataSourceFactory = new CacheDataSource.Factory().setCache(Mockito.mock(Cache.class)).setUpstreamDataSourceFactory(DummyDataSource.FACTORY);
    DownloaderFactory factory = new DefaultDownloaderFactory(cacheDataSourceFactory, /* executor= */
    Runnable::run);
    Downloader downloader = factory.createDownloader(new DownloadRequest.Builder(/* id= */
    "id", Uri.parse("https://www.test.com/download")).setMimeType(MimeTypes.APPLICATION_MPD).setStreamKeys(Collections.singletonList(new StreamKey(/* groupIndex= */
    0, /* trackIndex= */
    0))).build());
    assertThat(downloader).isInstanceOf(DashDownloader.class);
}
Also used : CacheDataSource(com.google.android.exoplayer2.upstream.cache.CacheDataSource) DefaultDownloaderFactory(com.google.android.exoplayer2.offline.DefaultDownloaderFactory) DefaultDownloaderFactory(com.google.android.exoplayer2.offline.DefaultDownloaderFactory) DownloaderFactory(com.google.android.exoplayer2.offline.DownloaderFactory) Downloader(com.google.android.exoplayer2.offline.Downloader) DefaultDownloaderFactory(com.google.android.exoplayer2.offline.DefaultDownloaderFactory) DownloaderFactory(com.google.android.exoplayer2.offline.DownloaderFactory) StreamKey(com.google.android.exoplayer2.offline.StreamKey) Test(org.junit.Test)

Example 2 with Downloader

use of com.google.android.exoplayer2.offline.Downloader in project ExoPlayer by google.

the class HlsDownloaderTest method createWithDefaultDownloaderFactory.

@Test
public void createWithDefaultDownloaderFactory() {
    CacheDataSource.Factory cacheDataSourceFactory = new CacheDataSource.Factory().setCache(Mockito.mock(Cache.class)).setUpstreamDataSourceFactory(DummyDataSource.FACTORY);
    DownloaderFactory factory = new DefaultDownloaderFactory(cacheDataSourceFactory, /* executor= */
    Runnable::run);
    Downloader downloader = factory.createDownloader(new DownloadRequest.Builder(/* id= */
    "id", Uri.parse("https://www.test.com/download")).setMimeType(MimeTypes.APPLICATION_M3U8).setStreamKeys(Collections.singletonList(new StreamKey(/* groupIndex= */
    0, /* trackIndex= */
    0))).build());
    assertThat(downloader).isInstanceOf(HlsDownloader.class);
}
Also used : CacheDataSource(com.google.android.exoplayer2.upstream.cache.CacheDataSource) DefaultDownloaderFactory(com.google.android.exoplayer2.offline.DefaultDownloaderFactory) DefaultDownloaderFactory(com.google.android.exoplayer2.offline.DefaultDownloaderFactory) DownloaderFactory(com.google.android.exoplayer2.offline.DownloaderFactory) Downloader(com.google.android.exoplayer2.offline.Downloader) DefaultDownloaderFactory(com.google.android.exoplayer2.offline.DefaultDownloaderFactory) DownloaderFactory(com.google.android.exoplayer2.offline.DownloaderFactory) StreamKey(com.google.android.exoplayer2.offline.StreamKey) Test(org.junit.Test)

Example 3 with Downloader

use of com.google.android.exoplayer2.offline.Downloader in project Slide by ccrama.

the class GifUtils method cacheSaveGif.

/**
 * Temporarily cache or permanently save a GIF
 *
 * @param uri       URL of the GIF
 * @param a
 * @param subreddit Subreddit for saving in sub-specific folders
 * @param save      Whether to permanently save the GIF of just temporarily cache it
 */
public static void cacheSaveGif(Uri uri, Activity a, String subreddit, String submissionTitle, boolean save) {
    if (save) {
        try {
            Toast.makeText(a, a.getString(R.string.mediaview_notif_title), Toast.LENGTH_SHORT).show();
        } catch (Exception ignored) {
        }
    }
    if (Reddit.appRestart.getString("imagelocation", "").isEmpty()) {
        showFirstDialog(a);
    } else if (!new File(Reddit.appRestart.getString("imagelocation", "")).exists()) {
        showErrorDialog(a);
    } else {
        new AsyncTask<Void, Integer, Boolean>() {

            File outFile;

            NotificationManager notifMgr = ContextCompat.getSystemService(a, NotificationManager.class);

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                if (save) {
                    Notification notif = new NotificationCompat.Builder(a, Reddit.CHANNEL_IMG).setContentTitle(a.getString(R.string.mediaview_saving, uri.toString().replace("/DASHPlaylist.mpd", ""))).setSmallIcon(R.drawable.ic_download).setProgress(0, 0, true).setOngoing(true).build();
                    notifMgr.notify(1, notif);
                }
            }

            @Override
            protected Boolean doInBackground(Void... voids) {
                String folderPath = Reddit.appRestart.getString("imagelocation", "");
                String subFolderPath = "";
                if (SettingValues.imageSubfolders && !subreddit.isEmpty()) {
                    subFolderPath = File.separator + subreddit;
                }
                String extension = ".mp4";
                outFile = FileUtil.getValidFile(folderPath, subFolderPath, submissionTitle, "", extension);
                OutputStream out = null;
                InputStream in = null;
                try {
                    DataSource.Factory downloader = new OkHttpDataSource.Factory(Reddit.client).setUserAgent(a.getString(R.string.app_name));
                    DataSource.Factory cacheDataSourceFactory = new CacheDataSource.Factory().setCache(Reddit.videoCache).setUpstreamDataSourceFactory(downloader);
                    if (uri.getLastPathSegment().endsWith("DASHPlaylist.mpd")) {
                        InputStream dashManifestStream = new DataSourceInputStream(cacheDataSourceFactory.createDataSource(), new DataSpec(uri));
                        DashManifest dashManifest = new DashManifestParser().parse(uri, dashManifestStream);
                        dashManifestStream.close();
                        Uri audioUri = null;
                        Uri videoUri = null;
                        for (int i = 0; i < dashManifest.getPeriodCount(); i++) {
                            for (AdaptationSet as : dashManifest.getPeriod(i).adaptationSets) {
                                boolean isAudio = false;
                                int bitrate = 0;
                                String hqUri = null;
                                for (Representation r : as.representations) {
                                    if (r.format.bitrate > bitrate) {
                                        bitrate = r.format.bitrate;
                                        hqUri = r.baseUrl;
                                    }
                                    if (MimeTypes.isAudio(r.format.sampleMimeType)) {
                                        isAudio = true;
                                    }
                                }
                                if (isAudio) {
                                    audioUri = Uri.parse(hqUri);
                                } else {
                                    videoUri = Uri.parse(hqUri);
                                }
                            }
                        }
                        if (audioUri != null) {
                            LogUtil.v("Downloading DASH audio from: " + audioUri);
                            DataSourceInputStream audioInputStream = new DataSourceInputStream(cacheDataSourceFactory.createDataSource(), new DataSpec(audioUri));
                            if (save) {
                                FileUtils.copyInputStreamToFile(audioInputStream, new File(a.getCacheDir().getAbsolutePath(), "audio.mp4"));
                            } else {
                                IOUtils.copy(audioInputStream, NullOutputStream.NULL_OUTPUT_STREAM);
                            }
                            audioInputStream.close();
                        }
                        if (videoUri != null) {
                            LogUtil.v("Downloading DASH video from: " + videoUri);
                            DataSourceInputStream videoInputStream = new DataSourceInputStream(cacheDataSourceFactory.createDataSource(), new DataSpec(videoUri));
                            if (save) {
                                FileUtils.copyInputStreamToFile(videoInputStream, new File(a.getCacheDir().getAbsolutePath(), "video.mp4"));
                            } else {
                                IOUtils.copy(videoInputStream, NullOutputStream.NULL_OUTPUT_STREAM);
                            }
                            videoInputStream.close();
                        }
                        if (!save) {
                            return true;
                        } else if (audioUri != null && videoUri != null) {
                            if (mux(new File(a.getCacheDir().getAbsolutePath(), "video.mp4").getAbsolutePath(), new File(a.getCacheDir().getAbsolutePath(), "audio.mp4").getAbsolutePath(), new File(a.getCacheDir().getAbsolutePath(), "muxed.mp4").getAbsolutePath())) {
                                in = new FileInputStream(new File(a.getCacheDir().getAbsolutePath(), "muxed.mp4"));
                            } else {
                                throw new IOException("Muxing failed!");
                            }
                        } else {
                            in = new FileInputStream(new File(a.getCacheDir().getAbsolutePath(), "video.mp4"));
                        }
                    } else {
                        in = new DataSourceInputStream(cacheDataSourceFactory.createDataSource(), new DataSpec(uri));
                    }
                    out = save ? new FileOutputStream(outFile) : NullOutputStream.NULL_OUTPUT_STREAM;
                    IOUtils.copy(in, out);
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtil.e("Error saving GIF called with: " + "from = [" + uri + "], in = [" + in + "]");
                    return false;
                } finally {
                    try {
                        if (out != null) {
                            out.close();
                        }
                        if (in != null) {
                            in.close();
                        }
                    } catch (IOException e) {
                        LogUtil.e("Error closing GIF called with: " + "from = [" + uri + "], out = [" + out + "]");
                        return false;
                    }
                }
                return true;
            }

            @Override
            protected void onPostExecute(Boolean success) {
                super.onPostExecute(success);
                if (save) {
                    notifMgr.cancel(1);
                    if (success) {
                        doNotifGif(outFile, a);
                    } else {
                        showErrorDialog(a);
                    }
                }
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
}
Also used : OkHttpDataSource(com.google.android.exoplayer2.ext.okhttp.OkHttpDataSource) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) NullOutputStream(org.apache.commons.io.output.NullOutputStream) DashManifest(com.google.android.exoplayer2.source.dash.manifest.DashManifest) Uri(android.net.Uri) Notification(android.app.Notification) DashManifestParser(com.google.android.exoplayer2.source.dash.manifest.DashManifestParser) NotificationCompat(androidx.core.app.NotificationCompat) DataSpec(com.google.android.exoplayer2.upstream.DataSpec) DataSourceInputStream(com.google.android.exoplayer2.upstream.DataSourceInputStream) NotificationManager(android.app.NotificationManager) DataSourceInputStream(com.google.android.exoplayer2.upstream.DataSourceInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) AsyncTask(android.os.AsyncTask) Representation(com.google.android.exoplayer2.source.dash.manifest.Representation) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) BufferOverflowException(java.nio.BufferOverflowException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) DataSource(com.google.android.exoplayer2.upstream.DataSource) CacheDataSource(com.google.android.exoplayer2.upstream.cache.CacheDataSource) OkHttpDataSource(com.google.android.exoplayer2.ext.okhttp.OkHttpDataSource) FileOutputStream(java.io.FileOutputStream) AdaptationSet(com.google.android.exoplayer2.source.dash.manifest.AdaptationSet) File(java.io.File)

Example 4 with Downloader

use of com.google.android.exoplayer2.offline.Downloader in project ExoPlayer by google.

the class ProgressiveDownloaderTest method download_afterWriteFailureOnClose_succeeds.

@Test
public void download_afterWriteFailureOnClose_succeeds() throws Exception {
    Uri uri = Uri.parse("test:///test.mp4");
    FakeDataSet data = new FakeDataSet();
    data.newData(uri).appendReadData(1024);
    DataSource.Factory upstreamDataSource = new FakeDataSource.Factory().setFakeDataSet(data);
    AtomicBoolean failOnClose = new AtomicBoolean(/* initialValue= */
    true);
    FailOnCloseDataSink.Factory dataSinkFactory = new FailOnCloseDataSink.Factory(downloadCache, failOnClose);
    MediaItem mediaItem = MediaItem.fromUri(uri);
    CacheDataSource.Factory cacheDataSourceFactory = new CacheDataSource.Factory().setCache(downloadCache).setCacheWriteDataSinkFactory(dataSinkFactory).setUpstreamDataSourceFactory(upstreamDataSource);
    ProgressiveDownloader downloader = new ProgressiveDownloader(mediaItem, cacheDataSourceFactory);
    TestProgressListener progressListener = new TestProgressListener();
    // Failure expected after 1024 bytes.
    assertThrows(IOException.class, () -> downloader.download(progressListener));
    assertThat(progressListener.bytesDownloaded).isEqualTo(1024);
    failOnClose.set(false);
    // Retry should succeed.
    downloader.download(progressListener);
    assertThat(progressListener.bytesDownloaded).isEqualTo(1024);
}
Also used : FakeDataSet(com.google.android.exoplayer2.testutil.FakeDataSet) Uri(android.net.Uri) FailOnCloseDataSink(com.google.android.exoplayer2.testutil.FailOnCloseDataSink) CacheDataSource(com.google.android.exoplayer2.upstream.cache.CacheDataSource) DataSource(com.google.android.exoplayer2.upstream.DataSource) FakeDataSource(com.google.android.exoplayer2.testutil.FakeDataSource) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FakeDataSource(com.google.android.exoplayer2.testutil.FakeDataSource) MediaItem(com.google.android.exoplayer2.MediaItem) CacheDataSource(com.google.android.exoplayer2.upstream.cache.CacheDataSource) Test(org.junit.Test)

Example 5 with Downloader

use of com.google.android.exoplayer2.offline.Downloader in project ExoPlayer by google.

the class ProgressiveDownloaderTest method download_afterReadFailure_succeeds.

@Test
public void download_afterReadFailure_succeeds() throws Exception {
    Uri uri = Uri.parse("test:///test.mp4");
    // Fake data has a built in failure after 10 bytes.
    FakeDataSet data = new FakeDataSet();
    data.newData(uri).appendReadData(10).appendReadError(new IOException()).appendReadData(20);
    DataSource.Factory upstreamDataSource = new FakeDataSource.Factory().setFakeDataSet(data);
    MediaItem mediaItem = MediaItem.fromUri(uri);
    CacheDataSource.Factory cacheDataSourceFactory = new CacheDataSource.Factory().setCache(downloadCache).setUpstreamDataSourceFactory(upstreamDataSource);
    ProgressiveDownloader downloader = new ProgressiveDownloader(mediaItem, cacheDataSourceFactory);
    TestProgressListener progressListener = new TestProgressListener();
    // Failure expected after 10 bytes.
    assertThrows(IOException.class, () -> downloader.download(progressListener));
    assertThat(progressListener.bytesDownloaded).isEqualTo(10);
    // Retry should succeed.
    downloader.download(progressListener);
    assertThat(progressListener.bytesDownloaded).isEqualTo(30);
}
Also used : FakeDataSet(com.google.android.exoplayer2.testutil.FakeDataSet) IOException(java.io.IOException) Uri(android.net.Uri) CacheDataSource(com.google.android.exoplayer2.upstream.cache.CacheDataSource) DataSource(com.google.android.exoplayer2.upstream.DataSource) FakeDataSource(com.google.android.exoplayer2.testutil.FakeDataSource) FakeDataSource(com.google.android.exoplayer2.testutil.FakeDataSource) MediaItem(com.google.android.exoplayer2.MediaItem) CacheDataSource(com.google.android.exoplayer2.upstream.cache.CacheDataSource) Test(org.junit.Test)

Aggregations

CacheDataSource (com.google.android.exoplayer2.upstream.cache.CacheDataSource)7 Test (org.junit.Test)6 DataSource (com.google.android.exoplayer2.upstream.DataSource)4 Uri (android.net.Uri)3 MediaItem (com.google.android.exoplayer2.MediaItem)3 DefaultDownloaderFactory (com.google.android.exoplayer2.offline.DefaultDownloaderFactory)3 Downloader (com.google.android.exoplayer2.offline.Downloader)3 DownloaderFactory (com.google.android.exoplayer2.offline.DownloaderFactory)3 StreamKey (com.google.android.exoplayer2.offline.StreamKey)3 FakeDataSet (com.google.android.exoplayer2.testutil.FakeDataSet)3 OkHttpDataSource (com.google.android.exoplayer2.ext.okhttp.OkHttpDataSource)2 FakeDataSource (com.google.android.exoplayer2.testutil.FakeDataSource)2 IOException (java.io.IOException)2 Notification (android.app.Notification)1 NotificationManager (android.app.NotificationManager)1 AsyncTask (android.os.AsyncTask)1 Nullable (androidx.annotation.Nullable)1 NotificationCompat (androidx.core.app.NotificationCompat)1 MediaSource (com.google.android.exoplayer2.source.MediaSource)1 ProgressiveMediaSource (com.google.android.exoplayer2.source.ProgressiveMediaSource)1