Search in sources :

Example 71 with DataSpec

use of com.google.android.exoplayer2.upstream.DataSpec in project ExoPlayer by google.

the class CacheAsserts method assertReadData.

/**
 * Asserts that the read data from {@code dataSource} specified by {@code dataSpec} is equal to
 * {@code expected} or not.
 *
 * @throws IOException If an error occurred reading from the Cache.
 */
public static void assertReadData(DataSource dataSource, DataSpec dataSpec, byte[] expected) throws IOException {
    try (DataSourceInputStream inputStream = new DataSourceInputStream(dataSource, dataSpec)) {
        byte[] bytes = Util.toByteArray(inputStream);
        assertThat(bytes).isEqualTo(expected);
    }
}
Also used : DataSourceInputStream(com.google.android.exoplayer2.upstream.DataSourceInputStream)

Example 72 with DataSpec

use of com.google.android.exoplayer2.upstream.DataSpec in project ExoPlayer by google.

the class FakeDataSourceTest method testRunnable.

@Test
public void testRunnable() throws IOException {
    TestRunnable[] runnables = new TestRunnable[3];
    for (int i = 0; i < 3; i++) {
        runnables[i] = new TestRunnable();
    }
    FakeDataSource dataSource = new FakeDataSource(new FakeDataSet().newData(uri.toString()).appendReadData(TEST_DATA).appendReadAction(runnables[0]).appendReadData(TEST_DATA).appendReadAction(runnables[1]).appendReadAction(runnables[2]).appendReadData(TEST_DATA).endData());
    assertThat(dataSource.open(new DataSpec(uri))).isEqualTo(45);
    assertThat(dataSource.read(BUFFER, 0, BUFFER.length)).isEqualTo(15);
    assertBuffer(TEST_DATA);
    for (int i = 0; i < 3; i++) {
        assertThat(runnables[i].ran).isFalse();
    }
    assertThat(dataSource.read(BUFFER, 0, BUFFER.length)).isEqualTo(15);
    assertBuffer(TEST_DATA);
    assertThat(runnables[0].ran).isTrue();
    assertThat(runnables[1].ran).isFalse();
    assertThat(runnables[2].ran).isFalse();
    assertThat(dataSource.read(BUFFER, 0, BUFFER.length)).isEqualTo(15);
    assertBuffer(TEST_DATA);
    for (int i = 0; i < 3; i++) {
        assertThat(runnables[i].ran).isTrue();
    }
    assertThat(dataSource.read(BUFFER, 0, BUFFER.length)).isEqualTo(C.RESULT_END_OF_INPUT);
    dataSource.close();
}
Also used : DataSpec(com.google.android.exoplayer2.upstream.DataSpec) Test(org.junit.Test)

Example 73 with DataSpec

use of com.google.android.exoplayer2.upstream.DataSpec in project ExoPlayer by google.

the class FakeDataSourceTest method testException.

@Test
public void testException() throws IOException {
    String errorMessage = "error, error, error";
    IOException exception = new IOException(errorMessage);
    FakeDataSource dataSource = new FakeDataSource(new FakeDataSet().newData(uri.toString()).appendReadData(TEST_DATA).appendReadError(exception).appendReadData(TEST_DATA).endData());
    assertThat(dataSource.open(new DataSpec(uri))).isEqualTo(30);
    assertThat(dataSource.read(BUFFER, 0, BUFFER.length)).isEqualTo(15);
    assertBuffer(TEST_DATA);
    try {
        dataSource.read(BUFFER, 0, BUFFER.length);
        fail("IOException expected.");
    } catch (IOException e) {
        assertThat(e).hasMessageThat().isEqualTo(errorMessage);
    }
    try {
        dataSource.read(BUFFER, 0, BUFFER.length);
        fail("IOException expected.");
    } catch (IOException e) {
        assertThat(e).hasMessageThat().isEqualTo(errorMessage);
    }
    dataSource.close();
    assertThat(dataSource.open(new DataSpec(uri, 15, 15))).isEqualTo(15);
    assertThat(dataSource.read(BUFFER, 0, BUFFER.length)).isEqualTo(15);
    assertBuffer(TEST_DATA);
    assertThat(dataSource.read(BUFFER, 0, BUFFER.length)).isEqualTo(C.RESULT_END_OF_INPUT);
    dataSource.close();
}
Also used : DataSpec(com.google.android.exoplayer2.upstream.DataSpec) IOException(java.io.IOException) Test(org.junit.Test)

Example 74 with DataSpec

use of com.google.android.exoplayer2.upstream.DataSpec in project ExoPlayer by google.

the class FakeDataSourceTest method testOpenSourceFailures.

@Test
public void testOpenSourceFailures() {
    // Empty data.
    FakeDataSource dataSource = new FakeDataSource(new FakeDataSet().newData(uri.toString()).endData());
    try {
        dataSource.open(new DataSpec(uri));
        fail("IOException expected.");
    } catch (IOException e) {
    // Expected.
    } finally {
        dataSource.close();
    }
    // Non-existent data
    dataSource = new FakeDataSource(new FakeDataSet());
    try {
        dataSource.open(new DataSpec(uri));
        fail("IOException expected.");
    } catch (IOException e) {
    // Expected.
    } finally {
        dataSource.close();
    }
}
Also used : DataSpec(com.google.android.exoplayer2.upstream.DataSpec) IOException(java.io.IOException) Test(org.junit.Test)

Example 75 with DataSpec

use of com.google.android.exoplayer2.upstream.DataSpec 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)

Aggregations

DataSpec (com.google.android.exoplayer2.upstream.DataSpec)118 Test (org.junit.Test)79 FakeDataSource (com.google.android.exoplayer2.testutil.FakeDataSource)28 DataSource (com.google.android.exoplayer2.upstream.DataSource)22 Uri (android.net.Uri)17 Nullable (androidx.annotation.Nullable)17 IOException (java.io.IOException)17 DefaultExtractorInput (com.google.android.exoplayer2.extractor.DefaultExtractorInput)9 FakeDataSet (com.google.android.exoplayer2.testutil.FakeDataSet)9 HlsMediaPlaylist (com.google.android.exoplayer2.source.hls.playlist.HlsMediaPlaylist)8 ArrayList (java.util.ArrayList)7 ExtractorInput (com.google.android.exoplayer2.extractor.ExtractorInput)6 InterruptedIOException (java.io.InterruptedIOException)5 List (java.util.List)5 ContainerMediaChunk (com.google.android.exoplayer2.source.chunk.ContainerMediaChunk)4 Representation (com.google.android.exoplayer2.source.dash.manifest.Representation)4 DataSourceException (com.google.android.exoplayer2.upstream.DataSourceException)4 DataSourceInputStream (com.google.android.exoplayer2.upstream.DataSourceInputStream)4 HttpDataSource (com.google.android.exoplayer2.upstream.HttpDataSource)4 ByteBuffer (java.nio.ByteBuffer)4