From 14f5c1f50c32bf2388cdb01aef8aa96153a2f021 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Sat, 7 Nov 2026 18:34:01 +0100 Subject: [PATCH 1/2] fix: preserve decoder packets and propagate drain errors --- .../src/main/cpp/include/JNI_DecoderFault.h | 60 ++++++++++ .../src/main/cpp/include/JNI_PlaybackProbe.h | 8 ++ .../src/main/cpp/include/media/DecoderFault.h | 42 +++++++ .../src/main/cpp/include/media/MediaPlayer.h | 8 +- .../main/cpp/include/media/PlaybackProbe.h | 8 +- .../src/main/cpp/src/JNI_DecoderFault.cpp | 87 ++++++++++++++ .../src/main/cpp/src/JNI_PlaybackProbe.cpp | 6 + .../src/main/cpp/src/media/DecoderFault.cpp | 106 ++++++++++++++++++ .../src/main/cpp/src/media/MediaPlayer.cpp | 93 +++++++++------ .../src/main/cpp/src/media/PlaybackProbe.cpp | 16 +++ .../webrtc/media/player/DecoderFault.java | 32 ++++++ .../webrtc/media/player/MediaPlayerTest.java | 74 ++++++++++++ .../webrtc/media/player/PlaybackProbe.java | 2 + 13 files changed, 505 insertions(+), 37 deletions(-) create mode 100644 webrtc-media/src/main/cpp/include/JNI_DecoderFault.h create mode 100644 webrtc-media/src/main/cpp/include/media/DecoderFault.h create mode 100644 webrtc-media/src/main/cpp/src/JNI_DecoderFault.cpp create mode 100644 webrtc-media/src/main/cpp/src/media/DecoderFault.cpp create mode 100644 webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/DecoderFault.java diff --git a/webrtc-media/src/main/cpp/include/JNI_DecoderFault.h b/webrtc-media/src/main/cpp/include/JNI_DecoderFault.h new file mode 100644 index 00000000..0dd2bec0 --- /dev/null +++ b/webrtc-media/src/main/cpp/include/JNI_DecoderFault.h @@ -0,0 +1,60 @@ +/* + * Copyright 2026 Alex Andres + * + * 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. + */ + +#include +/* Header for class dev_onvoid_webrtc_media_player_DecoderFault */ + +#ifndef _Included_dev_onvoid_webrtc_media_player_DecoderFault +#define _Included_dev_onvoid_webrtc_media_player_DecoderFault +#ifdef __cplusplus +extern "C" { +#endif + /* + * Class: dev_onvoid_webrtc_media_player_DecoderFault + * Method: arm + * Signature: (ZI)V + */ + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_DecoderFault_arm + (JNIEnv *, jclass, jboolean, jint); + + /* + * Class: dev_onvoid_webrtc_media_player_DecoderFault + * Method: disarm + * Signature: ()V + */ + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_DecoderFault_disarm + (JNIEnv *, jclass); + + /* + * Class: dev_onvoid_webrtc_media_player_DecoderFault + * Method: retries + * Signature: ()I + */ + JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_player_DecoderFault_retries + (JNIEnv *, jclass); + + /* + * Class: dev_onvoid_webrtc_media_player_DecoderFault + * Method: observerLifecycle + * Signature: (Ljava/lang/String;J)Z + */ + JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_media_player_DecoderFault_observerLifecycle + (JNIEnv *, jclass, jstring, jlong); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/webrtc-media/src/main/cpp/include/JNI_PlaybackProbe.h b/webrtc-media/src/main/cpp/include/JNI_PlaybackProbe.h index f3e2bf78..a0dabc68 100644 --- a/webrtc-media/src/main/cpp/include/JNI_PlaybackProbe.h +++ b/webrtc-media/src/main/cpp/include/JNI_PlaybackProbe.h @@ -38,6 +38,14 @@ extern "C" { JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_player_PlaybackProbe_waitingPushes (JNIEnv *, jclass); + /* + * Class: dev_onvoid_webrtc_media_player_PlaybackProbe + * Method: waitingPlayers + * Signature: ()I + */ + JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_player_PlaybackProbe_waitingPlayers + (JNIEnv *, jclass); + #ifdef __cplusplus } #endif diff --git a/webrtc-media/src/main/cpp/include/media/DecoderFault.h b/webrtc-media/src/main/cpp/include/media/DecoderFault.h new file mode 100644 index 00000000..95eaa0bb --- /dev/null +++ b/webrtc-media/src/main/cpp/include/media/DecoderFault.h @@ -0,0 +1,42 @@ +/* + * Copyright 2026 Alex Andres + * + * 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. + */ + +#ifndef WEBRTC_JAVA_MEDIA_DECODER_FAULT_H_ +#define WEBRTC_JAVA_MEDIA_DECODER_FAULT_H_ + +extern "C" { +#include +} + +namespace ffmpeg +{ + // Test-only JNI callers arm one fault for one stream at a time. Disarm + // only after the player has closed. Normal playback pays an atomic load. + class DecoderFault + { + public: + // 1: reject a packet once with EAGAIN; 2: fail drain send; + // 3: fail receiving buffered output after the drain request; + // 4: reject the drain request once with EAGAIN. + static void Arm(bool video, int mode); + static void Disarm(); + static int SendError(bool video, const AVPacket * packet); + static int ReceiveError(bool video); + static int Retries(); + }; +} + +#endif diff --git a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h index 50aac174..002bebb7 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h +++ b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h @@ -168,8 +168,12 @@ namespace ffmpeg bool PumpOnce(AVPacket * packet, bool * end_of_stream); // Pushes everything the decoders still hold, which is what the end - // of a stream and a loop both need. - void DrainDecoders(); + // of a stream and a loop both need. Returns false on a reported error. + bool DrainDecoders(); + + // Keeps an unaccepted packet alive while output is received, then + // retries it. A null packet drains the selected decoder. + bool SendToDecoder(bool video, const AVPacket * packet, bool at_end); // Takes the decoded video and hands it to the pacer. At the end // of the stream a seek that landed too late is not retried: the diff --git a/webrtc-media/src/main/cpp/include/media/PlaybackProbe.h b/webrtc-media/src/main/cpp/include/media/PlaybackProbe.h index 13fd5eb1..7d93f62e 100644 --- a/webrtc-media/src/main/cpp/include/media/PlaybackProbe.h +++ b/webrtc-media/src/main/cpp/include/media/PlaybackProbe.h @@ -26,7 +26,7 @@ namespace ffmpeg // once, and a thread held up by a full queue looks like one that is done. // // Only the tests read it, through JNI_PlaybackProbe, and it costs a player - // a single atomic update per seek and per wait for room in a queue. The + // an atomic update per seek, command wait and wait for room in a queue. The // counts are those of all players, which tests one at a time can tell // apart. class PlaybackProbe @@ -52,6 +52,12 @@ namespace ffmpeg // How many pushes are waiting for room in a queue right now. static int WaitingPushes(); + + // Counts decode threads waiting for a playback command, rather + // than stuck in decoding or waiting for the pacer at EOF. + static void BeginCommandWait(); + static void EndCommandWait(); + static int WaitingPlayers(); }; } diff --git a/webrtc-media/src/main/cpp/src/JNI_DecoderFault.cpp b/webrtc-media/src/main/cpp/src/JNI_DecoderFault.cpp new file mode 100644 index 00000000..17024ea8 --- /dev/null +++ b/webrtc-media/src/main/cpp/src/JNI_DecoderFault.cpp @@ -0,0 +1,87 @@ +/* + * Copyright 2026 Alex Andres + * + * 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. + */ + +#include "JNI_DecoderFault.h" +#include "media/DecoderFault.h" +#include "media/JniBoundary.h" +#include "media/MediaPlayer.h" + +namespace +{ + class CountingObserver : public ffmpeg::MediaPlayerObserver + { + public: + void OnThreadStart() override { ++starts; } + void OnThreadStop() override { ++stops; } + void OnStateChanged(int state) override + { + ordered = ordered && starts == 1 && stops == 0; + last_state = state; + } + void OnEndOfStream() override {} + void OnError(const std::string &) override {} + int starts = 0; + int stops = 0; + int last_state = ffmpeg::kIdle; + bool ordered = true; + }; +} + +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_DecoderFault_arm +(JNIEnv *, jclass, jboolean video, jint mode) +{ + ffmpeg::DecoderFault::Arm(video == JNI_TRUE, mode); +} + +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_DecoderFault_disarm +(JNIEnv *, jclass) +{ + ffmpeg::DecoderFault::Disarm(); +} + +JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_player_DecoderFault_retries +(JNIEnv *, jclass) +{ + return ffmpeg::DecoderFault::Retries(); +} + +JNIEXPORT jboolean JNICALL Java_dev_onvoid_webrtc_media_player_DecoderFault_observerLifecycle +(JNIEnv * env, jclass, jstring source, jlong api) +{ + return ffmpeg::CallFromJava(env, JNI_FALSE, [&]() -> jboolean { + ffmpeg::JavaStringChars chars(env, source); + if (chars.get() == nullptr) { + return JNI_FALSE; + } + auto reader = std::make_unique(); + if (reader->Open(chars.utf8()) < 0) { + return JNI_FALSE; + } + // Native observers have no JVM detach flag to hide a double stop. + ffmpeg::MediaPlayer player(std::move(reader), + reinterpret_cast(api), nullptr, nullptr); + auto observer = std::make_unique(); + auto * counts = observer.get(); + player.SetObserver(std::move(observer)); + if (player.Initialize() < 0) { + return JNI_FALSE; + } + player.Close(); + player.Close(); + return counts->starts == 1 && counts->stops == 1 && counts->ordered + && counts->last_state == ffmpeg::kClosed ? JNI_TRUE : JNI_FALSE; + }); +} diff --git a/webrtc-media/src/main/cpp/src/JNI_PlaybackProbe.cpp b/webrtc-media/src/main/cpp/src/JNI_PlaybackProbe.cpp index c38dce4f..b9c35b43 100644 --- a/webrtc-media/src/main/cpp/src/JNI_PlaybackProbe.cpp +++ b/webrtc-media/src/main/cpp/src/JNI_PlaybackProbe.cpp @@ -31,3 +31,9 @@ JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_player_PlaybackProbe_waiting { return static_cast(ffmpeg::PlaybackProbe::WaitingPushes()); } + +JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_player_PlaybackProbe_waitingPlayers +(JNIEnv * env, jclass caller) +{ + return static_cast(ffmpeg::PlaybackProbe::WaitingPlayers()); +} diff --git a/webrtc-media/src/main/cpp/src/media/DecoderFault.cpp b/webrtc-media/src/main/cpp/src/media/DecoderFault.cpp new file mode 100644 index 00000000..8c44fef9 --- /dev/null +++ b/webrtc-media/src/main/cpp/src/media/DecoderFault.cpp @@ -0,0 +1,106 @@ +/* + * Copyright 2026 Alex Andres + * + * 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. + */ + +#include "media/DecoderFault.h" + +#include +#include +#include + +extern "C" { +#include +} + +namespace +{ + std::atomic mode{ 0 }; + bool target_video = true; + std::vector rejected; + int64_t rejected_pts = 0; + std::atomic retries{ 0 }; +} + +namespace ffmpeg +{ + void DecoderFault::Arm(bool video, int fault) + { + target_video = video; + rejected.clear(); + retries.store(0); + mode.store(fault); + } + + void DecoderFault::Disarm() + { + mode.store(0); + rejected.clear(); + } + + int DecoderFault::SendError(bool video, const AVPacket * packet) + { + int fault = mode.load(); + if (fault == 0 || video != target_video) { + return 0; + } + if (fault == 1 && packet != nullptr) { + rejected.assign(packet->data, packet->data + packet->size); + rejected_pts = packet->pts; + mode.store(5); + return AVERROR(EAGAIN); + } + if (fault == 5) { + mode.store(0); + if (packet == nullptr || packet->pts != rejected_pts + || packet->size != static_cast(rejected.size()) + || !std::equal(rejected.begin(), rejected.end(), packet->data)) { + return AVERROR_INVALIDDATA; + } + retries.fetch_add(1); + } + if (packet == nullptr) { + if (fault == 2) { + mode.store(0); + return AVERROR_INVALIDDATA; + } + if (fault == 3) { + mode.store(6); + } + if (fault == 4) { + mode.store(7); + return AVERROR(EAGAIN); + } + if (fault == 7) { + mode.store(0); + retries.fetch_add(1); + } + } + return 0; + } + + int DecoderFault::ReceiveError(bool video) + { + if (mode.load() == 6 && video == target_video) { + mode.store(0); + return AVERROR_INVALIDDATA; + } + return 0; + } + + int DecoderFault::Retries() + { + return retries.load(); + } +} diff --git a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp index d930a4df..40c8aff4 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp @@ -16,6 +16,7 @@ #include "media/MediaPlayer.h" #include "media/AllocationFault.h" +#include "media/DecoderFault.h" #include "media/ErrorText.h" #include "media/PlaybackProbe.h" @@ -305,10 +306,14 @@ namespace ffmpeg { std::unique_lock lock(mutex_); + PlaybackProbe::BeginCommandWait(); + command_.wait(lock, [this] { return closing_ || seek_pending_ || (playing_ && !ended_); }); + PlaybackProbe::EndCommandWait(); + if (closing_) { break; } @@ -346,7 +351,9 @@ namespace ffmpeg // Whatever the decoders still hold belongs to this pass, so it // goes out before anything is rewound. - DrainDecoders(); + if (!DrainDecoders()) { + continue; + } // A source that cannot be rewound, such as a live stream that has // ended, cannot start over either, and ends as if not looping. @@ -427,45 +434,59 @@ namespace ffmpeg bool video = has_video_ && index == reader_->GetVideoStreamIndex(); bool audio = has_audio_ && index == reader_->GetAudioStreamIndex(); - if (video) { - result = video_decoder_.SendPacket(packet); - } - else if (audio) { - result = audio_decoder_.SendPacket(packet); - } - else { - // A stream this player does not play, such as a subtitle track. - result = 0; + bool decoded = true; + + if (video || audio) { + decoded = SendToDecoder(video, packet, false); } + // The decoder either accepted it or playback failed; EAGAIN alone + // never releases the packet. av_packet_unref(packet); - if (result < 0 && result != AVERROR(EAGAIN)) { - ReportError("Decoding failed", result); + return decoded; + } - return false; - } + bool MediaPlayer::SendToDecoder(bool video, const AVPacket * packet, bool at_end) + { + for (;;) { + int result = DecoderFault::SendError(video, packet); - if (video) { - return DecodeVideo(false) >= 0; - } - if (audio) { - return DecodeAudio() >= 0; - } + if (result == 0) { + result = video ? video_decoder_.SendPacket(packet) : audio_decoder_.SendPacket(packet); + } - return true; + // EOF means this decoder already accepted a drain request. + if (result < 0 && result != AVERROR(EAGAIN) + && !(at_end && result == AVERROR_EOF)) { + ReportError("Decoding failed", result); + + return false; + } + + // Do not seek backwards while making room for an unaccepted + // packet: that would flush the decoder before its retry. + int decoded = video ? DecodeVideo(at_end || result == AVERROR(EAGAIN)) : DecodeAudio(); + + if (decoded < 0) { + return false; + } + if (result != AVERROR(EAGAIN)) { + return true; + } + } } - void MediaPlayer::DrainDecoders() + bool MediaPlayer::DrainDecoders() { - if (has_video_) { - video_decoder_.SendPacket(nullptr); - DecodeVideo(true); + if (has_video_ && !SendToDecoder(true, nullptr, true)) { + return false; } - if (has_audio_) { - audio_decoder_.SendPacket(nullptr); - DecodeAudio(); + if (has_audio_ && !SendToDecoder(false, nullptr, true)) { + return false; } + + return true; } int MediaPlayer::DecodeVideo(bool at_end) @@ -474,7 +495,11 @@ namespace ffmpeg AVFrame * frame = nullptr; int64_t timestamp_us = 0; - int result = video_decoder_.ReceiveFrame(&frame, ×tamp_us); + int result = DecoderFault::ReceiveError(true); + + if (result == 0) { + result = video_decoder_.ReceiveFrame(&frame, ×tamp_us); + } if (result == AVERROR(EAGAIN) || result == AVERROR_EOF) { return 0; @@ -511,7 +536,11 @@ namespace ffmpeg std::vector chunk; int64_t timestamp_us = 0; - int result = audio_decoder_.ReceiveChunk(chunk, ×tamp_us); + int result = DecoderFault::ReceiveError(false); + + if (result == 0) { + result = audio_decoder_.ReceiveChunk(chunk, ×tamp_us); + } if (result == AVERROR(EAGAIN) || result == AVERROR_EOF) { return 0; @@ -673,10 +702,6 @@ namespace ffmpeg observer->OnThreadStop(); } - - if (observer != nullptr) { - observer->OnThreadStop(); - } } void MediaPlayer::Deliver(MediaPlayerObserver & observer, const Event & event) diff --git a/webrtc-media/src/main/cpp/src/media/PlaybackProbe.cpp b/webrtc-media/src/main/cpp/src/media/PlaybackProbe.cpp index 5510f405..c3b620d4 100644 --- a/webrtc-media/src/main/cpp/src/media/PlaybackProbe.cpp +++ b/webrtc-media/src/main/cpp/src/media/PlaybackProbe.cpp @@ -22,10 +22,26 @@ namespace { std::atomic seeks{ 0 }; std::atomic waiting_pushes{ 0 }; + std::atomic waiting_players{ 0 }; } namespace ffmpeg { + void PlaybackProbe::BeginCommandWait() + { + waiting_players.fetch_add(1); + } + + void PlaybackProbe::EndCommandWait() + { + waiting_players.fetch_sub(1); + } + + int PlaybackProbe::WaitingPlayers() + { + return waiting_players.load(); + } + void PlaybackProbe::NoteSeek() { seeks.fetch_add(1); diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/DecoderFault.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/DecoderFault.java new file mode 100644 index 00000000..13a8db78 --- /dev/null +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/DecoderFault.java @@ -0,0 +1,32 @@ +/* + * Copyright 2026 Alex Andres + * + * 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 dev.onvoid.webrtc.media.player; + +/** Deterministic faults at the player's decoder boundary. */ +final class DecoderFault { + + static { + FFmpeg.load(); + } + + private DecoderFault() {} + + static native void arm(boolean video, int mode); + static native void disarm(); + static native int retries(); + static native boolean observerLifecycle(String source, long api); +} diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaPlayerTest.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaPlayerTest.java index 8c36cf79..3433539a 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaPlayerTest.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaPlayerTest.java @@ -128,6 +128,80 @@ void disposeFactory() { audioModule.dispose(); } + @Test + void retriesUnacceptedPacketsAndDrainRequests() throws Exception { + for (boolean video : new boolean[] { true, false }) { + for (int mode : new int[] { 1, 4 }) { + DecoderFault.arm(video, mode); + try (Playback playback = new Playback()) { + playback.player.play(); + assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream"); + assertEquals(MediaPlayerState.ENDED, playback.player.getState()); + assertEquals(1, DecoderFault.retries(), "unaccepted input was lost"); + assertTrue(Math.abs(playback.frames.get() - EXPECTED_FRAMES) <= 1); + assertTrue(Math.abs(playback.chunks.get() - EXPECTED_CHUNKS) <= 2); + } + finally { + DecoderFault.disarm(); + } + } + } + } + + @Test + void drainFailuresPauseWithoutEndingOrLooping() throws Exception { + for (boolean video : new boolean[] { true, false }) { + for (int mode : new int[] { 2, 3 }) { + for (boolean looping : new boolean[] { false, true }) { + DecoderFault.arm(video, mode); + try (Playback playback = new Playback()) { + CountDownLatch failed = new CountDownLatch(1); + AtomicInteger ends = new AtomicInteger(); + AtomicInteger errors = new AtomicInteger(); + playback.player.setListener(new MediaPlayerListener() { + @Override + public void onError(String message) { + errors.incrementAndGet(); + failed.countDown(); + } + + @Override + public void onEndOfStream() { + ends.incrementAndGet(); + } + }); + playback.player.setLooping(looping); + playback.player.play(); + assertTrue(failed.await(15, TimeUnit.SECONDS), "no drain error"); + assertEquals(MediaPlayerState.PAUSED, playback.player.getState()); + assertTrue(waitFor(() -> PlaybackProbe.waitingPlayers() == 1, 5000), + "decode thread stuck waiting for the paused pacer at EOF"); + assertEquals(0, ends.get()); + // Resuming after a drain error must finish this pass, without + // having rewound and decoded a second one while paused. + playback.player.setLooping(false); + playback.player.play(); + assertTrue(waitFor(() -> ends.get() == 1, 10000), "no end after resume"); + assertTrue(playback.frames.get() <= EXPECTED_FRAMES); + assertEquals(1, errors.get()); + playback.player.close(); + assertEquals(1, errors.get()); + assertEquals(1, ends.get()); + } + finally { + DecoderFault.disarm(); + } + } + } + } + } + + @Test + void nativeObserverStartsAndStopsExactlyOnce() throws Exception { + assertTrue(DecoderFault.observerLifecycle(asset().toString(), + dev.onvoid.webrtc.internal.NativeApi.tableAddress())); + } + @Test void playsToEnd() throws Exception { try (Playback playback = new Playback()) { diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/PlaybackProbe.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/PlaybackProbe.java index c9e224d8..5167948e 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/PlaybackProbe.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/PlaybackProbe.java @@ -47,4 +47,6 @@ private PlaybackProbe() { */ static native int waitingPushes(); + static native int waitingPlayers(); + } From 558212bb6247178bc4580ded9f06f0e400ee9998 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Sat, 7 Nov 2026 19:05:49 +0100 Subject: [PATCH 2/2] fix: retain player output sources before taking the reader --- docs/guide/media/media-files.md | 2 +- .../src/main/cpp/include/JNI_NativeApi.h | 32 +++++++++ .../src/main/cpp/include/webrtc_java_api.h | 5 +- webrtc-jni/src/main/cpp/src/JNI_NativeApi.cpp | 54 +++++++++++++++ .../webrtc/media/player/MediaPlayer.java | 38 +++++++---- .../webrtc/media/player/MediaPlayerTest.java | 68 +++++++++++++++++++ .../dev/onvoid/webrtc/internal/NativeApi.java | 56 +++++++++++++-- .../webrtc/internal/NativeApiTests.java | 32 +++++++++ 8 files changed, 264 insertions(+), 23 deletions(-) diff --git a/docs/guide/media/media-files.md b/docs/guide/media/media-files.md index 11aebc64..cebb737d 100644 --- a/docs/guide/media/media-files.md +++ b/docs/guide/media/media-files.md @@ -221,7 +221,7 @@ player.play(); ::: info The player takes over the reader it is given. That reader must not be used or closed afterwards; closing the player releases it. -It also keeps the native side of the media sources it feeds alive until it is closed, so disposing of a source or its track while the player runs is safe. +It also keeps the native side of the media sources it feeds alive until it is closed, so disposing of a source or its track while the player runs is safe. A source that was already disposed is rejected with `IllegalStateException` before the reader is taken over; the caller can still use or close that reader. Source acquisition is protected against concurrent disposal: the constructor either acquires its own reference or rejects the disposed source. ::: ## Decoding in Hardware diff --git a/webrtc-jni/src/main/cpp/include/JNI_NativeApi.h b/webrtc-jni/src/main/cpp/include/JNI_NativeApi.h index 664d7713..4721642f 100644 --- a/webrtc-jni/src/main/cpp/include/JNI_NativeApi.h +++ b/webrtc-jni/src/main/cpp/include/JNI_NativeApi.h @@ -62,6 +62,38 @@ extern "C" { JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_releaseFrames (JNIEnv *, jclass, jlong); + /* + * Class: dev_onvoid_webrtc_internal_NativeApi + * Method: retainVideoSource + * Signature: (Ldev/onvoid/webrtc/media/video/CustomVideoSource;)J + */ + JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_retainVideoSource + (JNIEnv *, jclass, jobject); + + /* + * Class: dev_onvoid_webrtc_internal_NativeApi + * Method: releaseVideoSource + * Signature: (J)V + */ + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_releaseVideoSource + (JNIEnv *, jclass, jlong); + + /* + * Class: dev_onvoid_webrtc_internal_NativeApi + * Method: retainAudioSource + * Signature: (Ldev/onvoid/webrtc/media/audio/CustomAudioSource;)J + */ + JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_retainAudioSource + (JNIEnv *, jclass, jobject); + + /* + * Class: dev_onvoid_webrtc_internal_NativeApi + * Method: releaseAudioSource + * Signature: (J)V + */ + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_releaseAudioSource + (JNIEnv *, jclass, jlong); + #ifdef __cplusplus } #endif diff --git a/webrtc-jni/src/main/cpp/include/webrtc_java_api.h b/webrtc-jni/src/main/cpp/include/webrtc_java_api.h index 9becd952..e1f5c036 100644 --- a/webrtc-jni/src/main/cpp/include/webrtc_java_api.h +++ b/webrtc-jni/src/main/cpp/include/webrtc_java_api.h @@ -31,8 +31,9 @@ * * 1. Java side: dev.onvoid.webrtc.internal.NativeApi.tableAddress() returns * the address of a "struct webrtc_java_api" owned by this library, and - * NativeApi.handleOf(source) returns the native handle of a - * CustomVideoSource or CustomAudioSource. + * NativeApi.retainVideoSource(source) or retainAudioSource(source) + * returns a retained handle of a CustomVideoSource or CustomAudioSource. + * Release that reference with the matching source_release() when done. * 2. The extension receives both as jlong values and casts them back. * * There is no link-time dependency between the two native libraries, so the diff --git a/webrtc-jni/src/main/cpp/src/JNI_NativeApi.cpp b/webrtc-jni/src/main/cpp/src/JNI_NativeApi.cpp index 1b11e467..2fe37361 100644 --- a/webrtc-jni/src/main/cpp/src/JNI_NativeApi.cpp +++ b/webrtc-jni/src/main/cpp/src/JNI_NativeApi.cpp @@ -16,6 +16,9 @@ #include "JNI_NativeApi.h" #include "JavaBoundary.h" +#include "NativeHandle.h" +#include "media/audio/CustomAudioSource.h" +#include "media/video/CustomVideoSource.h" #include "api/ExtensionApi.h" #include "api/EncodedFrameTransformer.h" @@ -38,6 +41,57 @@ JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_tableAddress }); } +JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_retainVideoSource +(JNIEnv * env, jclass caller, jobject javaSource) +{ + return jni::CallFromJava(env, [&]() -> jlong { + if (javaSource == nullptr) { + return 0; + } + + jni::NativeLease source(env, javaSource); + CHECK_HANDLEV(source, 0); + + // AddRef while the lease still defers any concurrent dispose. + source->AddRef(); + + return reinterpret_cast(source.get()); + }); +} + +JNIEXPORT jlong JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_retainAudioSource +(JNIEnv * env, jclass caller, jobject javaSource) +{ + return jni::CallFromJava(env, [&]() -> jlong { + if (javaSource == nullptr) { + return 0; + } + + jni::NativeLease source(env, javaSource); + CHECK_HANDLEV(source, 0); + + source->AddRef(); + + return reinterpret_cast(source.get()); + }); +} + +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_releaseVideoSource +(JNIEnv * env, jclass caller, jlong source) +{ + jni::CallFromJava(env, [&]() { + jni::GetExtensionApi()->video_source_release(reinterpret_cast(source)); + }); +} + +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_releaseAudioSource +(JNIEnv * env, jclass caller, jlong source) +{ + jni::CallFromJava(env, [&]() { + jni::GetExtensionApi()->audio_source_release(reinterpret_cast(source)); + }); +} + JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_internal_NativeApi_version (JNIEnv * env, jclass caller) { diff --git a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java index 5790e0e8..449a54df 100644 --- a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java +++ b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java @@ -93,6 +93,7 @@ public class MediaPlayer implements AutoCloseable { * * @throws IOException if the source cannot be decoded. * @throws IllegalArgumentException if both sources are {@code null}. + * @throws IllegalStateException if a supplied source has been disposed. */ public MediaPlayer(MediaReader reader, CustomVideoSource videoSource, CustomAudioSource audioSource) throws IOException { @@ -130,6 +131,7 @@ public MediaPlayer(MediaReader reader, CustomVideoSource videoSource, * including HEVC on a machine without a * hardware decoder for it. * @throws IllegalArgumentException if both sources are {@code null}. + * @throws IllegalStateException if a supplied source has been disposed. */ public MediaPlayer(MediaReader reader, CustomVideoSource videoSource, CustomAudioSource audioSource, boolean hardwareDecoding) throws IOException { @@ -139,24 +141,32 @@ public MediaPlayer(MediaReader reader, CustomVideoSource videoSource, throw new IllegalArgumentException("A player needs at least one media source"); } - // Before the reader is taken over: should these fail, such as when the - // library of the sources cannot be loaded, the caller still has the - // reader to close. long tableAddress = NativeApi.tableAddress(); - long videoSourceHandle = videoSource != null ? NativeApi.handleOf(videoSource) : 0; - long audioSourceHandle = audioSource != null ? NativeApi.handleOf(audioSource) : 0; + long videoSourceHandle = NativeApi.retainVideoSource(videoSource); - // Taking the reader over rather than sharing it: the native player - // owns it from here, and a Java reader that still held the same - // pointer would release it a second time. - long readerHandle = reader.detach(); + try { + long audioSourceHandle = NativeApi.retainAudioSource(audioSource); - if (readerHandle == 0) { - throw new IOException("The reader is closed"); - } + try { + // Both sources are validated and retained before the reader is + // taken over. Their Java wrappers may now be disposed without + // freeing the handles passed to the native pacer. + long readerHandle = reader.detach(); - handle = create(readerHandle, tableAddress, videoSourceHandle, audioSourceHandle, - hardwareDecoding); + if (readerHandle == 0) { + throw new IOException("The reader is closed"); + } + + handle = create(readerHandle, tableAddress, videoSourceHandle, audioSourceHandle, + hardwareDecoding); + } + finally { + NativeApi.releaseAudioSource(audioSourceHandle); + } + } + finally { + NativeApi.releaseVideoSource(videoSourceHandle); + } } /** diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaPlayerTest.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaPlayerTest.java index 3433539a..5ed62a4f 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaPlayerTest.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaPlayerTest.java @@ -33,6 +33,7 @@ import java.util.Collections; import java.util.List; import java.util.Set; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -959,6 +960,73 @@ void needsAtLeastOneSource() throws Exception { reader.close(); } + @Test + void rejectsDisposedSources() throws Exception { + for (boolean disposedVideo : new boolean[] { true, false }) { + for (boolean otherSource : new boolean[] { true, false }) { + try (Sources sources = new Sources(); MediaReader reader = new MediaReader(asset())) { + if (disposedVideo) { + sources.video.dispose(); + } + else { + sources.audio.dispose(); + } + CustomVideoSource video = disposedVideo || otherSource ? sources.video : null; + CustomAudioSource audio = !disposedVideo || otherSource ? sources.audio : null; + assertThrows(IllegalStateException.class, () -> new MediaPlayer(reader, video, audio)); + // Rejection must leave the reader with its caller, ready to use. + assertNotNull(reader.getInfo()); + try (MediaPlayer player = new MediaPlayer(reader, + disposedVideo ? null : sources.video, disposedVideo ? sources.audio : null)) { + assertEquals(MediaPlayerState.IDLE, player.getState()); + } + } + } + } + } + + @Test + void sourcesSurviveConstructorHandoff() throws Exception { + try (Sources sources = new Sources()) { + // The transfer of the reader is between source acquisition in Java + // and the pacer's AddRef. Force disposal on another thread in that gap. + try (MediaReader reader = new MediaReader(asset()) { + @Override + synchronized long detach() { + try { + CompletableFuture.runAsync(() -> { + sources.video.dispose(); + sources.audio.dispose(); + }).get(5, TimeUnit.SECONDS); + } + catch (Exception e) { + throw new AssertionError("Disposal during source handoff failed", e); + } + return super.detach(); + } + }; MediaPlayer player = new MediaPlayer(reader, sources.video, sources.audio)) { + CountDownLatch finished = new CountDownLatch(1); + AtomicReference error = new AtomicReference<>(); + player.setListener(new MediaPlayerListener() { + @Override + public void onEndOfStream() { + finished.countDown(); + } + + @Override + public void onError(String message) { + error.set(message); + finished.countDown(); + } + }); + player.play(); + assertTrue(finished.await(15, TimeUnit.SECONDS), "no end of stream"); + assertEquals(null, error.get()); + assertEquals(MediaPlayerState.ENDED, player.getState()); + } + } + } + @Test void closesTwice() throws Exception { Playback playback = new Playback(); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/internal/NativeApi.java b/webrtc/src/main/java/dev/onvoid/webrtc/internal/NativeApi.java index d6a5089f..f554445d 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/internal/NativeApi.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/internal/NativeApi.java @@ -20,6 +20,8 @@ import dev.onvoid.webrtc.RTCRtpReceiver; import dev.onvoid.webrtc.RTCRtpSender; +import dev.onvoid.webrtc.media.audio.CustomAudioSource; +import dev.onvoid.webrtc.media.video.CustomVideoSource; /** * The entry point a native extension library uses to reach this library's @@ -28,17 +30,18 @@ * An extension gets two addresses from here and passes both to its own native * code: {@link #tableAddress()}, which is a {@code struct webrtc_java_api} of * function pointers declared in {@code webrtc_java_api.h}, and - * {@link #handleOf(NativeObject)}, which is the native object behind a - * {@code CustomVideoSource} or {@code CustomAudioSource}. The extension then - * pushes decoded media straight into that source. + * {@link #retainVideoSource(CustomVideoSource)} or + * {@link #retainAudioSource(CustomAudioSource)}, which keeps the native source + * alive even if its Java wrapper is disposed. The extension then pushes decoded + * media straight into that source and releases the reference when done. *

* Neither native library links against the other, which is what makes this * work at all: {@link NativeLoader} extracts the library to a temporary file * with a generated name, so there is nothing an extension could link to. *

* This is not API for applications. It has no use outside a native extension, - * and an address used after the source it belongs to was disposed crashes the - * process. + * and using a raw, unretained address after its source was disposed can crash + * the process. * * @author Alex Andres */ @@ -67,6 +70,44 @@ private NativeApi() { */ public static native long tableAddress(); + /** + * Acquires a reference to a video source while protecting its native + * handle against concurrent disposal. The reference remains valid after + * disposal of the Java source and must be released with + * {@link #releaseVideoSource(long)} or the table's video_source_release(). + * + * @param source The source, or {@code null} for none. + * @return A retained native handle, or {@code 0} for {@code null}. + * @throws IllegalStateException If the source has been disposed. + */ + public static native long retainVideoSource(CustomVideoSource source); + + /** + * Acquires a reference to an audio source while protecting its native + * handle against concurrent disposal. The reference remains valid after + * disposal of the Java source and must be released with + * {@link #releaseAudioSource(long)} or the table's audio_source_release(). + * + * @param source The source, or {@code null} for none. + * @return A retained native handle, or {@code 0} for {@code null}. + * @throws IllegalStateException If the source has been disposed. + */ + public static native long retainAudioSource(CustomAudioSource source); + + /** + * Releases a reference acquired with {@link #retainVideoSource(CustomVideoSource)}. + * + * @param source The retained handle, or {@code 0}, which is ignored. + */ + public static native void releaseVideoSource(long source); + + /** + * Releases a reference acquired with {@link #retainAudioSource(CustomAudioSource)}. + * + * @param source The retained handle, or {@code 0}, which is ignored. + */ + public static native void releaseAudioSource(long source); + /** * Returns the interface version of the function table. An extension built * against a different version must not use the table. @@ -77,7 +118,10 @@ private NativeApi() { /** * Returns the address of the native object bound to the given Java object, - * so that a native extension can act on it directly. + * so that a native extension can act on it directly. This does not retain + * the object or protect it from concurrent disposal. Use + * {@link #retainVideoSource(CustomVideoSource)} or + * {@link #retainAudioSource(CustomAudioSource)} to hand a source to an extension. * * @param object The object whose native counterpart is wanted. * diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/internal/NativeApiTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/internal/NativeApiTests.java index dfec20d4..70efb6a0 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/internal/NativeApiTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/internal/NativeApiTests.java @@ -90,6 +90,38 @@ void handleOfNull() { assertThrows(NullPointerException.class, () -> NativeApi.handleOf(null)); } + @Test + void retainedSourcesOutliveWrappers() { + CustomVideoSource video = new CustomVideoSource(); + CustomAudioSource audio = new CustomAudioSource(); + long videoHandle = NativeApi.retainVideoSource(video); + long audioHandle = NativeApi.retainAudioSource(audio); + + try { + assertNotEquals(0L, videoHandle); + assertNotEquals(0L, audioHandle); + video.dispose(); + audio.dispose(); + assertThrows(IllegalStateException.class, () -> NativeApi.retainVideoSource(video)); + assertThrows(IllegalStateException.class, () -> NativeApi.retainAudioSource(audio)); + } + finally { + video.dispose(); + audio.dispose(); + // These references must still be valid after the wrappers released theirs. + NativeApi.releaseVideoSource(videoHandle); + NativeApi.releaseAudioSource(audioHandle); + } + } + + @Test + void absentSourcesNeedNoReference() { + assertEquals(0L, NativeApi.retainVideoSource(null)); + assertEquals(0L, NativeApi.retainAudioSource(null)); + NativeApi.releaseVideoSource(0); + NativeApi.releaseAudioSource(0); + } + @Test void failedObserverAddAttachesNothing() { AudioTrackSource source = factory.createAudioSource(new AudioOptions());