Search in sources :

Example 1 with ConditionVariable

use of androidx.media3.common.util.ConditionVariable in project media by androidx.

the class CronetDataSourceTest method connectTimeout.

@Test
public void connectTimeout() throws InterruptedException {
    long startTimeMs = SystemClock.elapsedRealtime();
    final ConditionVariable startCondition = buildUrlRequestStartedCondition();
    final CountDownLatch timedOutLatch = new CountDownLatch(1);
    new Thread() {

        @Override
        public void run() {
            try {
                dataSourceUnderTest.open(testDataSpec);
                fail();
            } catch (HttpDataSourceException e) {
                // Expected.
                assertThat(e).isInstanceOf(CronetDataSource.OpenException.class);
                assertThat(e).hasCauseThat().isInstanceOf(SocketTimeoutException.class);
                assertThat(((CronetDataSource.OpenException) e).cronetConnectionStatus).isEqualTo(TEST_CONNECTION_STATUS);
                timedOutLatch.countDown();
            }
        }
    }.start();
    startCondition.block();
    // We should still be trying to open.
    assertNotCountedDown(timedOutLatch);
    // We should still be trying to open as we approach the timeout.
    setSystemClockInMsAndTriggerPendingMessages(/* nowMs= */
    startTimeMs + TEST_CONNECT_TIMEOUT_MS - 1);
    assertNotCountedDown(timedOutLatch);
    // Now we timeout.
    setSystemClockInMsAndTriggerPendingMessages(/* nowMs= */
    startTimeMs + TEST_CONNECT_TIMEOUT_MS + 10);
    timedOutLatch.await();
    verify(mockTransferListener, never()).onTransferStart(dataSourceUnderTest, testDataSpec, /* isNetwork= */
    true);
}
Also used : ConditionVariable(android.os.ConditionVariable) HttpDataSourceException(androidx.media3.datasource.HttpDataSource.HttpDataSourceException) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 2 with ConditionVariable

use of androidx.media3.common.util.ConditionVariable in project media by androidx.

the class DrmPlaybackTest method clearkeyPlayback.

@Test
public void clearkeyPlayback() throws Exception {
    MockWebServer mockWebServer = new MockWebServer();
    mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(CLEARKEY_RESPONSE));
    mockWebServer.start();
    MediaItem mediaItem = new MediaItem.Builder().setUri("asset:///media/drm/sample_fragmented_clearkey.mp4").setDrmConfiguration(new MediaItem.DrmConfiguration.Builder(C.CLEARKEY_UUID).setLicenseUri(mockWebServer.url("license").toString()).build()).build();
    AtomicReference<ExoPlayer> player = new AtomicReference<>();
    ConditionVariable playbackComplete = new ConditionVariable();
    AtomicReference<PlaybackException> playbackException = new AtomicReference<>();
    getInstrumentation().runOnMainSync(() -> {
        player.set(new ExoPlayer.Builder(getInstrumentation().getContext()).build());
        player.get().addListener(new Player.Listener() {

            @Override
            public void onPlaybackStateChanged(@Player.State int playbackState) {
                if (playbackState == Player.STATE_ENDED) {
                    playbackComplete.open();
                }
            }

            @Override
            public void onPlayerError(PlaybackException error) {
                playbackException.set(error);
                playbackComplete.open();
            }
        });
        player.get().setMediaItem(mediaItem);
        player.get().prepare();
        player.get().play();
    });
    playbackComplete.block();
    getInstrumentation().runOnMainSync(() -> player.get().release());
    getInstrumentation().waitForIdleSync();
    assertThat(playbackException.get()).isNull();
}
Also used : PlaybackException(androidx.media3.common.PlaybackException) MockResponse(okhttp3.mockwebserver.MockResponse) Player(androidx.media3.common.Player) ExoPlayer(androidx.media3.exoplayer.ExoPlayer) AtomicReference(java.util.concurrent.atomic.AtomicReference) ExoPlayer(androidx.media3.exoplayer.ExoPlayer) ConditionVariable(androidx.media3.common.util.ConditionVariable) MediaItem(androidx.media3.common.MediaItem) MockWebServer(okhttp3.mockwebserver.MockWebServer) Test(org.junit.Test)

Example 3 with ConditionVariable

use of androidx.media3.common.util.ConditionVariable in project media by androidx.

the class MediaSessionServiceLegacyStub method onGetRoot.

@Override
@Nullable
public BrowserRoot onGetRoot(String clientPackageName, int clientUid, @Nullable Bundle rootHints) {
    RemoteUserInfo info = getCurrentBrowserInfo();
    MediaSession.ControllerInfo controller = createControllerInfo(info);
    AtomicReference<MediaSession.ConnectionResult> resultReference = new AtomicReference<>();
    ConditionVariable haveResult = new ConditionVariable();
    postOrRun(sessionImpl.getApplicationHandler(), () -> {
        resultReference.set(sessionImpl.onConnectOnHandler(controller));
        haveResult.open();
    });
    try {
        haveResult.block();
    } catch (InterruptedException e) {
        Log.e(TAG, "Couldn't get a result from onConnect", e);
        return null;
    }
    MediaSession.ConnectionResult result = resultReference.get();
    if (!result.isAccepted) {
        return null;
    }
    connectedControllersManager.addController(info, controller, result.availableSessionCommands, result.availablePlayerCommands);
    // No library root, but keep browser compat connected to allow getting session.
    return MediaUtils.defaultBrowserRoot;
}
Also used : ConditionVariable(androidx.media3.common.util.ConditionVariable) AtomicReference(java.util.concurrent.atomic.AtomicReference) RemoteUserInfo(androidx.media.MediaSessionManager.RemoteUserInfo) ControllerInfo(androidx.media3.session.MediaSession.ControllerInfo) Nullable(androidx.annotation.Nullable)

Example 4 with ConditionVariable

use of androidx.media3.common.util.ConditionVariable in project media by androidx.

the class TestDownloadManagerListener method blockUntilIdle.

/**
 * Blocks until the manager is idle.
 */
public void blockUntilIdle() throws InterruptedException {
    idleCondition.close();
    // If the manager is already idle the condition will be opened by the code immediately below.
    // Else it will be opened by onIdle().
    ConditionVariable checkedOnMainThread = createRobolectricConditionVariable();
    new Handler(downloadManager.getApplicationLooper()).post(() -> {
        if (downloadManager.isIdle()) {
            idleCondition.open();
        }
        checkedOnMainThread.open();
    });
    assertThat(checkedOnMainThread.block(TIMEOUT_MS)).isTrue();
    assertThat(idleCondition.block(TIMEOUT_MS)).isTrue();
}
Also used : ConditionVariable(androidx.media3.common.util.ConditionVariable) RobolectricUtil.createRobolectricConditionVariable(androidx.media3.test.utils.robolectric.RobolectricUtil.createRobolectricConditionVariable) Handler(android.os.Handler)

Example 5 with ConditionVariable

use of androidx.media3.common.util.ConditionVariable in project media by androidx.

the class TestPlayerRunHelper method playUntilPosition.

/**
 * Calls {@link Player#play()}, runs tasks of the main {@link Looper} until the {@code player}
 * reaches the specified position or a playback error occurs, and then pauses the {@code player}.
 *
 * <p>If a playback error occurs it will be thrown wrapped in an {@link IllegalStateException}.
 *
 * @param player The {@link Player}.
 * @param mediaItemIndex The index of the media item.
 * @param positionMs The position within the media item, in milliseconds.
 * @throws TimeoutException If the {@link RobolectricUtil#DEFAULT_TIMEOUT_MS default timeout} is
 *     exceeded.
 */
public static void playUntilPosition(ExoPlayer player, int mediaItemIndex, long positionMs) throws TimeoutException {
    verifyMainTestThread(player);
    Looper applicationLooper = Util.getCurrentOrMainLooper();
    AtomicBoolean messageHandled = new AtomicBoolean(false);
    player.createMessage((messageType, payload) -> {
        // Block playback thread until pause command has been sent from test thread.
        ConditionVariable blockPlaybackThreadCondition = new ConditionVariable();
        player.getClock().createHandler(applicationLooper, /* callback= */
        null).post(() -> {
            player.pause();
            messageHandled.set(true);
            blockPlaybackThreadCondition.open();
        });
        try {
            player.getClock().onThreadBlocked();
            blockPlaybackThreadCondition.block();
        } catch (InterruptedException e) {
        // Ignore.
        }
    }).setPosition(mediaItemIndex, positionMs).send();
    player.play();
    runMainLooperUntil(() -> messageHandled.get() || player.getPlayerError() != null);
    if (player.getPlayerError() != null) {
        throw new IllegalStateException(player.getPlayerError());
    }
}
Also used : ConditionVariable(androidx.media3.common.util.ConditionVariable) Looper(android.os.Looper) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Aggregations

Test (org.junit.Test)12 ConditionVariable (androidx.media3.common.util.ConditionVariable)10 ConditionVariable (android.os.ConditionVariable)9 CountDownLatch (java.util.concurrent.CountDownLatch)7 HttpDataSourceException (androidx.media3.datasource.HttpDataSource.HttpDataSourceException)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 InterruptedIOException (java.io.InterruptedIOException)4 HandlerThread (android.os.HandlerThread)2 Nullable (androidx.annotation.Nullable)2 MediaItem (androidx.media3.common.MediaItem)2 HandlerWrapper (androidx.media3.common.util.HandlerWrapper)2 MediaPeriod (androidx.media3.exoplayer.source.MediaPeriod)2 ControllerInfo (androidx.media3.session.MediaSession.ControllerInfo)2 ArrayList (java.util.ArrayList)2 Handler (android.os.Handler)1 Looper (android.os.Looper)1 RemoteUserInfo (androidx.media.MediaSessionManager.RemoteUserInfo)1 PlaybackException (androidx.media3.common.PlaybackException)1 Player (androidx.media3.common.Player)1 TrackGroupArray (androidx.media3.common.TrackGroupArray)1