From e18b56682f3342ae342fc939a9fc2bf02fa9b797 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Sat, 7 Nov 2026 18:37:41 +0100 Subject: [PATCH 1/2] fix: contain player thread failures and report rejected output --- docs/guide/media/media-files.md | 4 +- .../webrtc/examples/MediaFileExample.java | 7 +- .../examples/MediaFilePlayerExample.java | 7 +- .../main/cpp/include/JNI_AllocationFault.h | 6 + .../main/cpp/include/media/AllocationFault.h | 5 + .../src/main/cpp/include/media/MediaPacer.h | 20 +- .../src/main/cpp/include/media/MediaPlayer.h | 8 +- .../src/main/cpp/src/JNI_AllocationFault.cpp | 12 ++ .../main/cpp/src/media/AllocationFault.cpp | 36 +++- .../src/main/cpp/src/media/MediaPacer.cpp | 86 +++++++-- .../src/main/cpp/src/media/MediaPlayer.cpp | 100 ++++++++-- .../media/player/MediaPlayerListener.java | 12 +- .../webrtc/media/player/AllocationFault.java | 6 + .../webrtc/media/player/MediaPlayerTest.java | 12 +- .../media/player/PlayerFailureTest.java | 171 ++++++++++++++++++ 15 files changed, 446 insertions(+), 46 deletions(-) create mode 100644 webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/PlayerFailureTest.java diff --git a/docs/guide/media/media-files.md b/docs/guide/media/media-files.md index cebb737d6..dfea4e7cb 100644 --- a/docs/guide/media/media-files.md +++ b/docs/guide/media/media-files.md @@ -174,11 +174,13 @@ source.setListener(new MediaPlayerListener() { @Override public void onError(String message) { - System.out.println("Playback failed: " + message); + System.out.println("Playback error: " + message); } }); ``` +Output failures are reported through `onError`. A single rejected video frame or audio chunk is dropped without advancing the position for that item; playback continues. These reports are limited to one per second for video and one for audio. Ten consecutive failed deliveries of either kind stop playback in `PAUSED` and produce a final error report. An unexpected C++ exception on the decoder thread also stops playback in `PAUSED`. After either terminal failure, `play()` and `seek()` have no effect: close the player and create a new one to retry. + ::: warning Every call arrives on the player's own event thread, never on the thread that called `play()`, `pause()` or `close()`, and never on the one decoding the media. The calls come one at a time, in the order the player went through what they report, so a listener needs no locking of its own against itself. A command returns without waiting for its state change to be reported, so `getState()` can already read a later state than the call in progress reports. `close()` returns once the listener has been told of everything, `CLOSED` last. diff --git a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/MediaFileExample.java b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/MediaFileExample.java index b92a8216d..e0cfa52c4 100644 --- a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/MediaFileExample.java +++ b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/MediaFileExample.java @@ -150,8 +150,11 @@ public void onEndOfStream() { @Override public void onError(String message) { - System.out.println("Playback failed: " + message); - finished.countDown(); + System.out.println("Playback error: " + message); + // A rejected output item is reported while playback continues. + if (source.getState() == MediaPlayerState.PAUSED) { + finished.countDown(); + } } }); diff --git a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/MediaFilePlayerExample.java b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/MediaFilePlayerExample.java index e0072205b..adf1939b1 100644 --- a/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/MediaFilePlayerExample.java +++ b/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/MediaFilePlayerExample.java @@ -588,8 +588,11 @@ public void onEndOfStream() { @Override public void onError(String message) { - LOG.warning("Playback failed: " + message); - stopIfCurrent(); + LOG.warning("Playback error: " + message); + // A rejected output item does not stop playback. + if (source.getState() == MediaPlayerState.PAUSED) { + stopIfCurrent(); + } } }); diff --git a/webrtc-media/src/main/cpp/include/JNI_AllocationFault.h b/webrtc-media/src/main/cpp/include/JNI_AllocationFault.h index ff20d998e..f7f616ff8 100644 --- a/webrtc-media/src/main/cpp/include/JNI_AllocationFault.h +++ b/webrtc-media/src/main/cpp/include/JNI_AllocationFault.h @@ -110,6 +110,12 @@ extern "C" { JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_player_AllocationFault_heldStrings (JNIEnv *, jclass); +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_AllocationFault_failDecoderAllocation + (JNIEnv *, jclass); + + JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_AllocationFault_failOutput + (JNIEnv *, jclass, jboolean, jint); + #ifdef __cplusplus } #endif diff --git a/webrtc-media/src/main/cpp/include/media/AllocationFault.h b/webrtc-media/src/main/cpp/include/media/AllocationFault.h index 5c9c31050..3d0f0bb30 100644 --- a/webrtc-media/src/main/cpp/include/media/AllocationFault.h +++ b/webrtc-media/src/main/cpp/include/media/AllocationFault.h @@ -47,6 +47,11 @@ namespace ffmpeg static void FailNextQueueRoom(); // Forgets a fault that has not fired. static void Disarm(); + static void FailDecoderAllocation(); + static void CheckDecoderAllocation(); + // Rejects the next count output items; negative means indefinitely. + static void FailOutput(bool video, int count); + static bool CheckOutputFailure(bool video); // Whether a fault is armed that has not fired. static bool IsArmed(); // Throws std::bad_alloc if a fault is armed, and disarms it. diff --git a/webrtc-media/src/main/cpp/include/media/MediaPacer.h b/webrtc-media/src/main/cpp/include/media/MediaPacer.h index a30230894..9ffeb0d7c 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaPacer.h +++ b/webrtc-media/src/main/cpp/include/media/MediaPacer.h @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -99,7 +100,11 @@ namespace ffmpeg MediaPacer(const MediaPacer &) = delete; MediaPacer & operator=(const MediaPacer &) = delete; + // Set before Start; called without the pacer lock. + void SetErrorHandler(std::function handler); void Start(); + // Stops accepting and delivering items, without joining this thread. + void Cancel(); // Stops the thread and drops whatever is still queued. Safe to // call more than once. @@ -225,8 +230,19 @@ namespace ffmpeg // lock of ours. The time on the WebRTC clock is worked out by the // caller while it still holds the lock and passed in, so that // neither of these reads the mapping unguarded. - void DeliverVideo(VideoItem item, int64_t mapped_us); - void DeliverAudio(const AudioItem & item, int64_t mapped_us); + int DeliverVideo(VideoItem item, int64_t mapped_us); + int DeliverAudio(const AudioItem & item, int64_t mapped_us); + + struct OutputStatus + { + int consecutive_failures = 0; + bool reported = false; + int64_t last_report_us = 0; + }; + void CheckOutput(OutputStatus & status, const char * media, int result); + OutputStatus video_output_; + OutputStatus audio_output_; + std::function error_handler_; const webrtc_java_api * api_; void * video_source_; diff --git a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h index 002bebb7a..e4cda4d47 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h +++ b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h @@ -152,7 +152,10 @@ namespace ffmpeg std::string message; }; - void Run(); + void Run() noexcept; + void Decode(); + void Abort(const char * message) noexcept; + void OutputError(const char * media, int error, bool fatal) noexcept; // The event thread: hands what is queued to the observer, one // report after the other, until the player closes. @@ -230,6 +233,9 @@ namespace ffmpeg std::unique_ptr observer_; bool running_ = false; + bool failed_ = false; + // Allocation-free fallback, delivered after already queued events. + const char * failure_pending_ = nullptr; bool playing_ = false; bool closing_ = false; int state_ = kIdle; diff --git a/webrtc-media/src/main/cpp/src/JNI_AllocationFault.cpp b/webrtc-media/src/main/cpp/src/JNI_AllocationFault.cpp index 993ac1177..6acfe5fc5 100644 --- a/webrtc-media/src/main/cpp/src/JNI_AllocationFault.cpp +++ b/webrtc-media/src/main/cpp/src/JNI_AllocationFault.cpp @@ -110,3 +110,15 @@ JNIEXPORT jint JNICALL Java_dev_onvoid_webrtc_media_player_AllocationFault_heldS { return ffmpeg::JavaStringChars::Held(); } + +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_AllocationFault_failDecoderAllocation +(JNIEnv *, jclass) +{ + ffmpeg::AllocationFault::FailDecoderAllocation(); +} + +JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_AllocationFault_failOutput +(JNIEnv *, jclass, jboolean video, jint count) +{ + ffmpeg::AllocationFault::FailOutput(video == JNI_TRUE, count); +} diff --git a/webrtc-media/src/main/cpp/src/media/AllocationFault.cpp b/webrtc-media/src/main/cpp/src/media/AllocationFault.cpp index 48af3562a..7a4dfc6c7 100644 --- a/webrtc-media/src/main/cpp/src/media/AllocationFault.cpp +++ b/webrtc-media/src/main/cpp/src/media/AllocationFault.cpp @@ -27,6 +27,9 @@ extern "C" { namespace { + std::atomic fail_decoder_allocation{ false }; + std::atomic video_failures{ 0 }; + std::atomic audio_failures{ 0 }; std::atomic fail_string_copy{ false }; std::atomic fail_allocation{ false }; std::atomic fail_thread_start{ false }; @@ -77,8 +80,38 @@ namespace ffmpeg fail_queue_room.store(true); } + void AllocationFault::FailDecoderAllocation() + { + fail_decoder_allocation.store(true); + } + + void AllocationFault::CheckDecoderAllocation() + { + if (fail_decoder_allocation.exchange(false)) { + throw std::bad_alloc(); + } + } + + void AllocationFault::FailOutput(bool video, int count) + { + (video ? video_failures : audio_failures).store(count); + } + + bool AllocationFault::CheckOutputFailure(bool video) + { + auto & remaining = video ? video_failures : audio_failures; + const int count = remaining.load(); + if (count > 0) { + remaining.fetch_sub(1); + } + return count != 0; + } + void AllocationFault::Disarm() { + fail_decoder_allocation.store(false); + video_failures.store(0); + audio_failures.store(0); fail_string_copy.store(false); fail_allocation.store(false); fail_thread_start.store(false); @@ -90,7 +123,8 @@ namespace ffmpeg bool AllocationFault::IsArmed() { - return fail_string_copy.load() || fail_allocation.load() || fail_thread_start.load() + return fail_decoder_allocation.load() || video_failures.load() != 0 + || audio_failures.load() != 0 || fail_string_copy.load() || fail_allocation.load() || fail_thread_start.load() || fail_writer_allocation.load() || fail_option.load() || fail_observer_add.load() || fail_queue_room.load(); } diff --git a/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp b/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp index df60d833d..2410fc86b 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaPacer.cpp @@ -16,6 +16,7 @@ #include "media/MediaPacer.h" #include "media/AudioDecoder.h" +#include "media/AllocationFault.h" #include "media/PlaybackProbe.h" #include "media/VideoGeometry.h" @@ -118,6 +119,23 @@ namespace ffmpeg } } + void MediaPacer::SetErrorHandler(std::function handler) + { + error_handler_ = std::move(handler); + } + + void MediaPacer::Cancel() + { + std::lock_guard lock(mutex_); + running_ = false; + video_queue_.clear(); + audio_queue_.clear(); + video_bytes_ = 0; + work_.notify_all(); + video_space_.notify_all(); + audio_space_.notify_all(); + } + void MediaPacer::Start() { std::lock_guard lock(mutex_); @@ -162,7 +180,8 @@ namespace ffmpeg bool MediaPacer::PushVideo(AVFrame * frame, int64_t timestamp_us, int64_t loop_offset_us, uint64_t generation) { - const size_t bytes = FrameBytes(frame); + VideoItem owned(frame, timestamp_us + loop_offset_us, loop_offset_us, FrameBytes(frame)); + const size_t bytes = owned.bytes; std::unique_lock lock(mutex_); @@ -178,12 +197,10 @@ namespace ffmpeg if (!running_ || generation != generation_) { // The frame became ours on the way in, so it is ours to drop. - av_frame_free(&frame); - return false; } - video_queue_.emplace_back(frame, timestamp_us + loop_offset_us, loop_offset_us, bytes); + video_queue_.push_back(std::move(owned)); video_bytes_ += bytes; peak_video_bytes_ = std::max(peak_video_bytes_, video_bytes_); @@ -417,7 +434,6 @@ namespace ffmpeg video_queue_.pop_front(); video_bytes_ -= item.bytes; - AdvancePosition(item.timestamp_us, item.loop_offset_us); video_space_.notify_one(); // A shorter video queue may be what lets audio past its @@ -425,9 +441,16 @@ namespace ffmpeg audio_space_.notify_one(); ++delivering_; + const auto delivery_generation = generation_; lock.unlock(); - DeliverVideo(std::move(item), due); + const auto timestamp = item.timestamp_us; + const auto offset = item.loop_offset_us; + const int result = DeliverVideo(std::move(item), due); + CheckOutput(video_output_, "Video", result); lock.lock(); + if (running_ && result >= 0 && delivery_generation == generation_) { + AdvancePosition(timestamp, offset); + } --delivering_; delivered = true; @@ -437,21 +460,25 @@ namespace ffmpeg } } - if (!audio_queue_.empty()) { + if (running_ && !paused_ && !audio_queue_.empty()) { const int64_t due = audio_queue_.front().timestamp_us + base_us_; if (due <= now) { AudioItem item = std::move(audio_queue_.front()); audio_queue_.pop_front(); - AdvancePosition(item.timestamp_us, item.loop_offset_us); audio_space_.notify_one(); ++delivering_; + const auto delivery_generation = generation_; lock.unlock(); - DeliverAudio(item, due); + const int result = DeliverAudio(item, due); + CheckOutput(audio_output_, "Audio", result); lock.lock(); + if (running_ && result >= 0 && delivery_generation == generation_) { + AdvancePosition(item.timestamp_us, item.loop_offset_us); + } --delivering_; delivered = true; @@ -476,14 +503,33 @@ namespace ffmpeg } } - void MediaPacer::DeliverVideo(VideoItem item, int64_t mapped_us) + void MediaPacer::CheckOutput(OutputStatus & status, const char * media, int result) + { + if (result >= 0) { + status.consecutive_failures = 0; + return; + } + const bool fatal = ++status.consecutive_failures >= 10; + const int64_t now = api_->now_us(); + // At most one dropped-item report per second and media kind. The + // terminal report is always delivered, even within that interval. + if (fatal || !status.reported || now - status.last_report_us >= 1000000) { + status.reported = true; + status.last_report_us = now; + if (error_handler_) { + error_handler_(media, result, fatal); + } + } + } + + int MediaPacer::DeliverVideo(VideoItem item, int64_t mapped_us) { AVFrame * frame = item.frame; if (video_source_ == nullptr || frame == nullptr) { // Nothing to deliver to; the item frees the frame as it goes out // of scope. - return; + return 0; } wj_i420_frame pushed = {}; @@ -512,13 +558,19 @@ namespace ffmpeg static_cast(frame->color_range) }; - api_->video_source_push_color(video_source_, &pushed, &color); + // Tests reject a frame through the real API, including its release + // callback on failure, rather than bypassing ownership transfer. + if (AllocationFault::CheckOutputFailure(true)) { + pushed.width = 0; + } + + return api_->video_source_push_color(video_source_, &pushed, &color); } - void MediaPacer::DeliverAudio(const AudioItem & item, int64_t mapped_us) + int MediaPacer::DeliverAudio(const AudioItem & item, int64_t mapped_us) { if (audio_source_ == nullptr || item.samples.empty()) { - return; + return 0; } wj_audio_chunk chunk = {}; @@ -531,6 +583,10 @@ namespace ffmpeg // The samples are copied during the call, so the item may go away as // soon as this returns. - api_->audio_source_push(audio_source_, &chunk); + if (AllocationFault::CheckOutputFailure(false)) { + chunk.channels = 0; + } + + return api_->audio_source_push(audio_source_, &chunk); } } diff --git a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp index 40c8aff44..cb42d1eef 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp @@ -36,6 +36,9 @@ namespace ffmpeg api_(api) { pacer_ = std::make_unique(api, video_source, audio_source); + pacer_->SetErrorHandler([this](const char * media, int error, bool fatal) { + OutputError(media, error, fatal); + }); } MediaPlayer::~MediaPlayer() @@ -114,7 +117,7 @@ namespace ffmpeg { std::lock_guard lock(mutex_); - if (closing_ || playing_) { + if (closing_ || failed_ || playing_) { return; } @@ -159,7 +162,7 @@ namespace ffmpeg { std::lock_guard lock(mutex_); - if (closing_) { + if (closing_ || failed_) { return; } @@ -288,12 +291,23 @@ namespace ffmpeg return pacer_->IsOwnThread(); } - void MediaPlayer::Run() + void MediaPlayer::Run() noexcept { - AVPacket * packet = av_packet_alloc(); + try { + Decode(); + } + catch (...) { + Abort("Decoder thread failed"); + } + } + + void MediaPlayer::Decode() + { + auto release = [](AVPacket * packet) { av_packet_free(&packet); }; + std::unique_ptr packet(av_packet_alloc(), release); if (packet == nullptr) { - ReportError("Allocating a packet failed", AVERROR(ENOMEM)); + Abort("Allocating a packet failed"); return; } @@ -309,12 +323,12 @@ namespace ffmpeg PlaybackProbe::BeginCommandWait(); command_.wait(lock, [this] { - return closing_ || seek_pending_ || (playing_ && !ended_); + return closing_ || failed_ || seek_pending_ || (playing_ && !ended_); }); PlaybackProbe::EndCommandWait(); - if (closing_) { + if (closing_ || failed_) { break; } @@ -338,7 +352,7 @@ namespace ffmpeg bool end_of_stream = false; - if (!PumpOnce(packet, &end_of_stream)) { + if (!PumpOnce(packet.get(), &end_of_stream)) { // Playback has stopped and been reported. The thread stays, // so that playing again carries on past what failed, and a // seek can move away from it. @@ -382,7 +396,7 @@ namespace ffmpeg for (;;) { std::unique_lock lock(mutex_); - if (closing_ || seek_pending_ || pacer_->IsDrained()) { + if (closing_ || failed_ || seek_pending_ || pacer_->IsDrained()) { break; } @@ -392,7 +406,7 @@ namespace ffmpeg { std::lock_guard lock(mutex_); - if (closing_) { + if (closing_ || failed_) { break; } @@ -411,8 +425,6 @@ namespace ffmpeg playing_ = false; } } - - av_packet_free(&packet); } bool MediaPlayer::PumpOnce(AVPacket * packet, bool * end_of_stream) @@ -430,6 +442,8 @@ namespace ffmpeg return false; } + AllocationFault::CheckDecoderAllocation(); + const int index = packet->stream_index; bool video = has_video_ && index == reader_->GetVideoStreamIndex(); bool audio = has_audio_ && index == reader_->GetAudioStreamIndex(); @@ -510,10 +524,12 @@ namespace ffmpeg return result; } + auto release = [](AVFrame * value) { av_frame_free(&value); }; + std::unique_ptr owned(frame, release); + if (!at_end && video_decoder_.LandedPastPosition() && SeekFurtherBack()) { // From a later keyframe than the one the seek needs; decoding // starts again from an earlier one. - av_frame_free(&frame); return 0; } @@ -524,7 +540,7 @@ namespace ffmpeg // The frame belongs to the pacer from here on, whether or not it // makes it into the queue. - if (!pacer_->PushVideo(frame, timestamp_us, loop_offset_us_, generation_)) { + if (!pacer_->PushVideo(owned.release(), timestamp_us, loop_offset_us_, generation_)) { return 0; } } @@ -675,9 +691,24 @@ namespace ffmpeg std::unique_lock lock(mutex_); event_posted_.wait(lock, [this] { - return !events_.empty() || events_stopping_; + return !events_.empty() || failure_pending_ != nullptr || events_stopping_; }); + if (events_.empty() && failure_pending_ != nullptr) { + const char * message = failure_pending_; + failure_pending_ = nullptr; + lock.unlock(); + if (observer != nullptr) { + try { + observer->OnStateChanged(kPaused); + observer->OnError(message); + } + catch (...) { + } + } + continue; + } + if (events_.empty()) { // Stopping, with everything queued before delivered. closed = closed_pending_; @@ -725,6 +756,43 @@ namespace ffmpeg } } + void MediaPlayer::Abort(const char * message) noexcept + { + // No string or event allocation: this also handles an exhausted heap. + std::lock_guard lock(mutex_); + if (closing_ || failed_) { + return; + } + failed_ = true; + playing_ = false; + state_ = kPaused; + failure_pending_ = message; + reader_->Interrupt(); + pacer_->Cancel(); + command_.notify_all(); + event_posted_.notify_one(); + } + + void MediaPlayer::OutputError(const char * media, int error, bool fatal) noexcept + { + if (fatal) { + Abort(media[0] == 'V' ? "Persistent video output failure" + : "Persistent audio output failure"); + return; + } + try { + std::lock_guard lock(mutex_); + if (!closing_ && !failed_) { + AllocationFault::CheckAllocation(); + PostLocked(Event::kError, kIdle, std::string(media) + + " output dropped: " + std::to_string(error)); + } + } + catch (...) { + Abort("Reporting output failure failed"); + } + } + void MediaPlayer::ReportError(const std::string & message, int error) { std::string text = message + ": " + ErrorText(error); @@ -734,7 +802,7 @@ namespace ffmpeg // A player being closed fails whatever it was waiting on on purpose, // since closing interrupts the reader. That is not an error of the // source, and nobody should hear of it. - if (closing_) { + if (closing_ || failed_) { return; } diff --git a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayerListener.java b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayerListener.java index e4c0d94e2..d77157f6f 100644 --- a/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayerListener.java +++ b/webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayerListener.java @@ -56,12 +56,20 @@ default void onEndOfStream() { } /** - * Playback stopped because something went wrong. The player is left + * A decoding or output error occurred. A dropped output item is reported + * at most once per second per media kind, while playback continues. Its + * position does not advance for that item. + *

+ * A recoverable decoding error leaves the player * {@link MediaPlayerState#PAUSED} where it failed: playing again carries * on past what failed, and a seek moves away from it, though a source * that cannot be read at all fails again. + *

+ * An unexpected decoder-thread exception or ten consecutive output + * failures of either media kind stops playback permanently in PAUSED. + * Close the player and create a new one to try again. * - * @param message What went wrong, as FFmpeg described it. + * @param message What went wrong. */ default void onError(String message) { } diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/AllocationFault.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/AllocationFault.java index 22e9629e4..957544982 100644 --- a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/AllocationFault.java +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/AllocationFault.java @@ -108,6 +108,12 @@ private AllocationFault() { */ public static native void disarm(); + /** Throws on the decoder thread with a live packet. */ + static native void failDecoderAllocation(); + + /** Rejects count output items; negative means indefinitely. */ + static native void failOutput(boolean video, int count); + /** * Returns how many Java strings the native library holds the characters * of right now, which is 0 whenever no entry point is running. 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 5ed62a4f6..bc298c5e2 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 @@ -519,10 +519,14 @@ void loopAfterASeekWithoutIndexThatLandedLateStartsOver() throws Exception { // The late landing, left over from the seek once the source had // started over, used to send the reader back before 7.8 s, so that // the last pictures played again before the next pass. - assertTrue(positions.get(0) > 7_800_000, "not from the position: " + positions); - assertTrue(positions.get(1) < 1_000_000, "next pass not from the start: " + positions); - - for (int i = 2; i < positions.size(); i++) { + // A sink runs inside the push, before its result is known. The + // position it sees belongs to the last successful delivery: first + // the seek target, then the picture at 8 s, then the next pass. + assertEquals(7_800_000L, positions.get(0)); + assertTrue(positions.get(1) > 7_800_000, "not from the position: " + positions); + assertTrue(positions.get(2) < 1_000_000, "next pass not from the start: " + positions); + + for (int i = 3; i < positions.size(); i++) { assertTrue(positions.get(i) > positions.get(i - 1), "position went back at frame " + i + ": " + positions); } diff --git a/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/PlayerFailureTest.java b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/PlayerFailureTest.java new file mode 100644 index 000000000..54d5fa055 --- /dev/null +++ b/webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/PlayerFailureTest.java @@ -0,0 +1,171 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import dev.onvoid.webrtc.media.audio.CustomAudioSource; +import dev.onvoid.webrtc.media.video.CustomVideoSource; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; + +/** Failures on native threads must be observable without ending the JVM. */ +@Execution(ExecutionMode.SAME_THREAD) +@Timeout(20) +class PlayerFailureTest { + + @AfterEach + void disarm() { + AllocationFault.disarm(); + } + + @Test + void decoderExceptionStopsAndCanBeClosed() throws Exception { + try (Playback playback = new Playback()) { + AllocationFault.failDecoderAllocation(); + playback.player.play(); + assertTrue(playback.failed.await(10, TimeUnit.SECONDS)); + assertEquals(MediaPlayerState.PAUSED, playback.player.getState()); + assertEquals("Decoder thread failed", playback.errors.get(0)); + playback.player.play(); + playback.player.seek(1000); + assertEquals(MediaPlayerState.PAUSED, playback.player.getState()); + } + } + + @Test + void reportingOutputFailureCanRunOutOfMemory() throws Exception { + try (Playback playback = new Playback()) { + AllocationFault.failNextAllocation(); + AllocationFault.failOutput(true, 1); + playback.player.play(); + assertTrue(playback.failed.await(10, TimeUnit.SECONDS)); + assertEquals(MediaPlayerState.PAUSED, playback.player.getState()); + assertEquals("Reporting output failure failed", playback.errors.get(0)); + } + } + + @Test + void oneRejectedVideoFrameDoesNotStopPlayback() throws Exception { + assertTransient(true); + } + + @Test + void oneRejectedAudioChunkDoesNotStopPlayback() throws Exception { + assertTransient(false); + } + + @Test + void persistentVideoFailureStopsPlayback() throws Exception { + assertPersistent(true); + } + + @Test + void persistentAudioFailureStopsPlayback() throws Exception { + assertPersistent(false); + } + + @Test + void failedOutputsDoNotAdvancePosition() throws Exception { + try (Playback playback = new Playback()) { + AllocationFault.failOutput(true, -1); + AllocationFault.failOutput(false, -1); + playback.player.play(); + assertTrue(playback.failed.await(10, TimeUnit.SECONDS)); + assertEquals(0, playback.player.getPositionUs()); + assertEquals(MediaPlayerState.PAUSED, playback.player.getState()); + } + } + + private void assertTransient(boolean video) throws Exception { + try (Playback playback = new Playback()) { + AllocationFault.failOutput(video, 1); + playback.player.play(); + assertTrue(playback.ended.await(10, TimeUnit.SECONDS)); + assertEquals(MediaPlayerState.ENDED, playback.player.getState()); + assertEquals(1, playback.errors.size()); + assertTrue(playback.errors.get(0).startsWith(video ? "Video output dropped:" : "Audio output dropped:")); + assertFalse(AllocationFault.isArmed()); + } + } + + private void assertPersistent(boolean video) throws Exception { + try (Playback playback = new Playback()) { + AllocationFault.failOutput(video, -1); + long started = System.nanoTime(); + playback.player.play(); + assertTrue(playback.failed.await(10, TimeUnit.SECONDS)); + assertEquals(MediaPlayerState.PAUSED, playback.player.getState()); + // One initial drop report, at most one more per second, and a + // terminal report even when the drop reports are rate limited. + long seconds = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - started); + assertTrue(playback.errors.size() >= 2); + assertTrue(playback.errors.size() <= 2 + seconds); + assertEquals(video ? "Persistent video output failure" : "Persistent audio output failure", + playback.errors.get(playback.errors.size() - 1)); + assertEquals(0, playback.player.getQueuedVideoBytes()); + assertEquals(1, playback.ended.getCount()); + playback.player.play(); + assertEquals(MediaPlayerState.PAUSED, playback.player.getState()); + } + } + + private static final class Playback implements AutoCloseable { + final CustomVideoSource video = new CustomVideoSource(); + final CustomAudioSource audio = new CustomAudioSource(); + final MediaPlayer player; + final List errors = new CopyOnWriteArrayList<>(); + final CountDownLatch ended = new CountDownLatch(1); + final CountDownLatch failed = new CountDownLatch(1); + + Playback() throws Exception { + player = new MediaPlayer(new MediaReader(MediaReaderTest.asset("/media-test.webm")), video, audio); + player.setListener(new MediaPlayerListener() { + @Override + public void onError(String message) { + errors.add(message); + if (!message.contains("output dropped:")) { + failed.countDown(); + } + } + + @Override + public void onEndOfStream() { + ended.countDown(); + } + }); + } + + @Override + public void close() { + player.close(); + video.dispose(); + audio.dispose(); + } + } +} From 2fa8718e38a2c257302ed86fc676e591cdf1e6b9 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Sat, 7 Nov 2026 19:38:28 +0100 Subject: [PATCH 2/2] fix: observe playback position after video delivery completes --- .../webrtc/media/player/MediaPlayerTest.java | 34 ++++++++++++++----- 1 file changed, 25 insertions(+), 9 deletions(-) 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 bc298c5e2..c0061db67 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 @@ -682,18 +682,34 @@ void seekBeforeVideoStartsKeepsTheAudio() throws Exception { void positionCountsFromTheFirstFrame() throws Exception { try (Playback playback = new Playback(new MediaReader( TestMedia.shiftedMatroska(tempDir, asset(), 6000, 5000)))) { - playback.player.play(); + AtomicLong firstDeliveredFramePositionUs = new AtomicLong(-1); + AudioTrackSink afterVideo = (data, bits, rate, ch, count) -> { + // Both sinks run on the pacer thread. An audio callback after + // a video callback sees the completed video push, whereas the + // video callback itself still sees the last accepted audio. + if (playback.frames.get() > 0) { + firstDeliveredFramePositionUs.compareAndSet(-1, playback.player.getPositionUs()); + } + }; + playback.audioTrack.addSink(afterVideo); - assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream"); + try { + playback.player.play(); - // Video starts a second after the source does. - long first = playback.firstFramePositionUs.get(); + assertTrue(playback.ended.await(15, TimeUnit.SECONDS), "no end of stream"); - assertTrue(Math.abs(first - 1_000_000) < 20_000, "first frame at " + first + " us"); + // Video starts a second after the source does. Read its + // position only once delivery has returned successfully. + assertEquals(1_000_000, firstDeliveredFramePositionUs.get(), + "position after the first video delivery"); - long end = playback.player.getPositionUs(); + long end = playback.player.getPositionUs(); - assertTrue(end > 3_900_000 && end < 4_100_000, "ended at " + end + " us"); + assertTrue(end > 3_900_000 && end < 4_100_000, "ended at " + end + " us"); + } + finally { + playback.audioTrack.removeSink(afterVideo); + } } } @@ -1706,8 +1722,8 @@ private final class Playback implements AutoCloseable { final List silentChunks = Collections.synchronizedList(new ArrayList<>()); private final VideoTrackSink videoSink = frame -> { - // The pacer delivers on its own thread, having just moved the - // position to the frame's presentation time. + // This callback runs inside the push. The position still belongs + // to the last successful delivery until this push returns. long positionUs = Playback.this.player.getPositionUs(); if (firstFramePositionUs.get() < 0) {