From 780f0d201cf48d9ff92e60108c8af64be717cfb0 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Sun, 1 Nov 2026 09:50:32 +0100 Subject: [PATCH] fix: deliver player listener calls in order on one event thread PLAYING and PAUSED were reported on the calling thread, ENDED and errors on the decode thread, so a listener could be called concurrently. Every report is now queued with its state change and delivered by a per-player event thread. --- docs/guide/media/media-files.md | 6 +- .../cpp/include/media/JavaPlayerObserver.h | 15 +- .../src/main/cpp/include/media/MediaPlayer.h | 58 ++++- .../cpp/include/media/MediaPlayerObserver.h | 13 +- .../main/cpp/src/media/JavaPlayerObserver.cpp | 33 +++ .../src/main/cpp/src/media/MediaPlayer.cpp | 246 +++++++++++------- .../webrtc/media/player/MediaPlayer.java | 12 +- .../media/player/MediaPlayerListener.java | 16 +- .../webrtc/media/player/MediaPlayerTest.java | 133 +++++++++- 9 files changed, 408 insertions(+), 124 deletions(-) diff --git a/docs/guide/media/media-files.md b/docs/guide/media/media-files.md index 48e127348..9a2bca5f9 100644 --- a/docs/guide/media/media-files.md +++ b/docs/guide/media/media-files.md @@ -176,9 +176,11 @@ source.setListener(new MediaPlayerListener() { ``` ::: warning -Every call arrives on the player's own thread, and that thread is the one decoding the media. A listener must return promptly, and must not wait on the player. +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. -Closing the player, or the `MediaFileSource`, from a listener is fine: it takes effect at once, and the native player is released on another thread once the listener has returned. The same holds for a sink of a track made from the player's sources, which the player calls on its own thread as well. +A listener must still return promptly: the calls behind it wait, and so does a `close()` from another thread. It must not wait on the player. + +Closing the player, or the `MediaFileSource`, from a listener is fine: it takes effect at once, and the native player is released on another thread once the listener has returned. The same holds for a sink of a track made from the player's sources, which the player calls on threads of its own as well. ::: ## Feeding Your Own Media Sources diff --git a/webrtc-media/src/main/cpp/include/media/JavaPlayerObserver.h b/webrtc-media/src/main/cpp/include/media/JavaPlayerObserver.h index ef924f6d5..189d938ab 100644 --- a/webrtc-media/src/main/cpp/include/media/JavaPlayerObserver.h +++ b/webrtc-media/src/main/cpp/include/media/JavaPlayerObserver.h @@ -26,10 +26,11 @@ namespace ffmpeg // Passes a player's reports on to its Java MediaPlayer, which turns them // into calls on whatever listener the application set. // - // The calls arrive on the player's own thread, which the JVM knows nothing - // about, so each one attaches that thread, makes the call and detaches - // again. Attaching is not free, but these are state changes and errors, - // not frames: they happen a handful of times over a whole playback. + // The calls arrive on the player's event thread, which the JVM knows + // nothing about. That thread is attached when it starts and detached when + // it stops, so that every call of a player is made on one and the same + // Java thread, "MediaPlayer-events". A call on any other thread, such as + // the release of the global reference, attaches for itself. class JavaPlayerObserver : public MediaPlayerObserver { public: @@ -41,6 +42,8 @@ namespace ffmpeg JavaPlayerObserver(const JavaPlayerObserver &) = delete; JavaPlayerObserver & operator=(const JavaPlayerObserver &) = delete; + void OnThreadStart() override; + void OnThreadStop() override; void OnStateChanged(int state) override; void OnEndOfStream() override; void OnError(const std::string & message) override; @@ -63,6 +66,10 @@ namespace ffmpeg jmethodID on_state_changed_ = nullptr; jmethodID on_end_of_stream_ = nullptr; jmethodID on_error_ = nullptr; + + // Whether OnThreadStart attached the event thread, which only + // that thread reads or changes. + bool thread_attached_ = false; }; } diff --git a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h index a06a4fd94..96d82ab84 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaPlayer.h +++ b/webrtc-media/src/main/cpp/include/media/MediaPlayer.h @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -55,6 +56,12 @@ namespace ffmpeg // Decoding runs ahead of playback only as far as the pacer's queues allow. // Once those are full the decode thread blocks, which is what keeps a // whole file from being decoded into memory at once. + // + // What the observer is told goes through a thread of its own. Each report + // is queued under the lock, in the same step as the change it reports, + // and that thread makes the calls one after the other, in that order. + // Neither a command nor the decode thread calls the observer itself, so + // the calls never overlap, and a slow observer holds up no decoding. class MediaPlayer { public: @@ -69,9 +76,9 @@ namespace ffmpeg MediaPlayer & operator=(const MediaPlayer &) = delete; // Takes over the observer, which then lives as long as the - // player does. Call this before Initialize: the observer is read - // without the lock while it is being called, on the assumption - // that it does not change once the thread is running. + // player does. Call this before Initialize: the observer is + // called without the lock, on the assumption that it does not + // change once the threads are running. void SetObserver(std::unique_ptr observer); // Asks for video to be decoded in hardware where the platform can. @@ -98,8 +105,9 @@ namespace ffmpeg void SetLooping(bool looping); bool IsLooping() const; - // Stops playback and releases the thread. The player cannot be - // used afterwards. + // Stops playback and releases the threads. What was reported + // before, and the closed state after it, has reached the observer + // once this returns. The player cannot be used afterwards. void Close(); // Where playback has got to within the current pass, in @@ -116,8 +124,32 @@ namespace ffmpeg bool IsOwnThread() const; private: + // A report waiting for the event thread. + struct Event + { + enum Kind + { + kState, + kEndOfStream, + kError + }; + + Kind kind = kState; + int state = kIdle; + std::string message; + }; + void Run(); + // The event thread: hands what is queued to the observer, one + // report after the other, until the player closes. + void DeliverEvents(); + static void Deliver(MediaPlayerObserver & observer, const Event & event); + + // Queues a report, with the lock held. Allocates, and so may + // throw, in which case nothing has been queued. + void PostLocked(Event::Kind kind, int state, std::string message); + // Reads and decodes until the source is exhausted. Returns false // if playback should stop, either on error or on close. bool PumpOnce(AVPacket * packet, bool * end_of_stream); @@ -146,13 +178,10 @@ namespace ffmpeg // further back to try once the reader would land where it did // already, or the distance has grown past kMaxSeekBackUs. bool SeekFurtherBack(); - void SetState(int state); - // Records the state, with the lock held. Returns whether it - // changed, in which case the caller reports it with NotifyState - // once the lock is released. + // Records the state, with the lock held, and queues the report of + // it if it changed. Returns whether it did. bool UpdateStateLocked(int state); - void NotifyState(int state); // Stops playback where it is, as a pause does, and reports the // error. The thread stays, so that playback can be resumed. @@ -169,10 +198,19 @@ namespace ffmpeg bool has_audio_ = false; std::thread thread_; + std::thread event_thread_; mutable std::mutex mutex_; std::condition_variable command_; + // The reports for the event thread, and what wakes it, all under + // the lock. The closed state is not queued, as queueing could + // fail: it is what stopping the thread delivers, after the rest. + std::deque events_; + std::condition_variable event_posted_; + bool events_stopping_ = false; + bool closed_pending_ = false; + std::unique_ptr observer_; bool running_ = false; bool playing_ = false; diff --git a/webrtc-media/src/main/cpp/include/media/MediaPlayerObserver.h b/webrtc-media/src/main/cpp/include/media/MediaPlayerObserver.h index 5c9c29846..f0c3fde26 100644 --- a/webrtc-media/src/main/cpp/include/media/MediaPlayerObserver.h +++ b/webrtc-media/src/main/cpp/include/media/MediaPlayerObserver.h @@ -23,14 +23,21 @@ namespace ffmpeg { // What a player reports while it runs. // - // Every call arrives on the player's own thread, never on the thread that - // asked for playback, so an implementation must not block: the thread it - // holds up is the one decoding the media. + // Every call arrives on the player's event thread, never on the thread + // that asked for playback, one at a time and in the order the player went + // through what it reports. An implementation should still return + // promptly: the reports behind it wait, and so does a close. class MediaPlayerObserver { public: virtual ~MediaPlayerObserver() = default; + // Called on the event thread before the first report and after + // the last, so that what the thread needs set up, such as being + // known to the JVM, is set up once rather than for every call. + virtual void OnThreadStart() {} + virtual void OnThreadStop() {} + // The player moved to another state, as a MediaPlayerState value. virtual void OnStateChanged(int state) = 0; diff --git a/webrtc-media/src/main/cpp/src/media/JavaPlayerObserver.cpp b/webrtc-media/src/main/cpp/src/media/JavaPlayerObserver.cpp index a8756da3c..3873ff5f3 100644 --- a/webrtc-media/src/main/cpp/src/media/JavaPlayerObserver.cpp +++ b/webrtc-media/src/main/cpp/src/media/JavaPlayerObserver.cpp @@ -64,6 +64,39 @@ namespace ffmpeg Detach(attached); } + void JavaPlayerObserver::OnThreadStart() + { + if (vm_ == nullptr) { + return; + } + + JNIEnv * env = nullptr; + + if (vm_->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_EDETACHED) { + return; + } + + // A daemon, so that a player left open does not keep the JVM from + // exiting. Every call made on this thread from here on finds it + // attached, and leaves it so. + JavaVMAttachArgs args; + args.version = JNI_VERSION_1_6; + args.name = const_cast("MediaPlayer-events"); + args.group = nullptr; + + thread_attached_ = vm_->AttachCurrentThreadAsDaemon( + reinterpret_cast(&env), &args) == JNI_OK; + } + + void JavaPlayerObserver::OnThreadStop() + { + if (thread_attached_) { + thread_attached_ = false; + + vm_->DetachCurrentThread(); + } + } + void JavaPlayerObserver::OnStateChanged(int state) { if (on_state_changed_ == nullptr) { diff --git a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp index bc5d3eab1..c91fbf9ef 100644 --- a/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp +++ b/webrtc-media/src/main/cpp/src/media/MediaPlayer.cpp @@ -97,6 +97,11 @@ namespace ffmpeg running_ = true; thread_ = std::thread(&MediaPlayer::Run, this); + + // Started last: once it runs, it calls the observer, which a + // player that failed to start would take away from under it. + // Until then, what the decode thread reports waits in the queue. + event_thread_ = std::thread(&MediaPlayer::DeliverEvents, this); } return 0; @@ -104,59 +109,47 @@ namespace ffmpeg void MediaPlayer::Play() { - bool changed = false; - - { - std::lock_guard lock(mutex_); - - if (closing_ || playing_) { - return; - } + std::lock_guard lock(mutex_); - playing_ = true; + if (closing_ || playing_) { + return; + } - if (ended_) { - // Playing again after the source ran out starts it over, - // which is what a listener would expect of a play button. - ended_ = false; - seek_pending_ = true; - seek_position_us_ = 0; - seek_precise_ = true; - } + // First, as it is the one step that can fail, which then leaves the + // player as it was. + UpdateStateLocked(kPlaying); - // Under the lock, together with the flag: the decode thread stops - // playback on an error, and the two must not interleave. - pacer_->Resume(); - changed = UpdateStateLocked(kPlaying); + playing_ = true; - command_.notify_all(); + if (ended_) { + // Playing again after the source ran out starts it over, which is + // what a listener would expect of a play button. + ended_ = false; + seek_pending_ = true; + seek_position_us_ = 0; + seek_precise_ = true; } - if (changed) { - NotifyState(kPlaying); - } + // Under the lock, together with the flag: the decode thread stops + // playback on an error, and the two must not interleave. + pacer_->Resume(); + + command_.notify_all(); } void MediaPlayer::Pause() { - bool changed = false; - - { - std::lock_guard lock(mutex_); + std::lock_guard lock(mutex_); - if (closing_ || !playing_) { - return; - } + if (closing_ || !playing_) { + return; + } - playing_ = false; + UpdateStateLocked(kPaused); - pacer_->Pause(); - changed = UpdateStateLocked(kPaused); - } + playing_ = false; - if (changed) { - NotifyState(kPaused); - } + pacer_->Pause(); } void MediaPlayer::Seek(int64_t position_us, bool precise) @@ -233,7 +226,25 @@ namespace ffmpeg reader_->Close(); } - SetState(kClosed); + { + std::lock_guard lock(mutex_); + + // Delivered by the event thread once it has delivered the rest, + // since nothing else is reported after it. + if (state_ != kClosed) { + state_ = kClosed; + closed_pending_ = true; + } + + events_stopping_ = true; + event_posted_.notify_all(); + } + + // A player without an event thread, one that never started, has no + // observer to tell: the closed state is not reported then. + if (event_thread_.joinable()) { + event_thread_.join(); + } } int64_t MediaPlayer::GetPositionUs() const @@ -255,7 +266,9 @@ namespace ffmpeg { std::lock_guard lock(mutex_); - if (thread_.get_id() == std::this_thread::get_id()) { + const std::thread::id current = std::this_thread::get_id(); + + if (thread_.get_id() == current || event_thread_.get_id() == current) { return true; } } @@ -367,22 +380,14 @@ namespace ffmpeg continue; } + // In one step with the flags: a play coming in now has to + // find the player ended, and be reported after it. + UpdateStateLocked(kEnded); + PostLocked(Event::kEndOfStream, kEnded, std::string()); + ended_ = true; playing_ = false; } - - SetState(kEnded); - - MediaPlayerObserver * observer = nullptr; - { - std::lock_guard lock(mutex_); - - observer = observer_.get(); - } - - if (observer != nullptr) { - observer->OnEndOfStream(); - } } av_packet_free(&packet); @@ -584,72 +589,123 @@ namespace ffmpeg return 0; } - void MediaPlayer::SetState(int state) - { - bool changed = false; - - { - std::lock_guard lock(mutex_); - - changed = UpdateStateLocked(state); - } - - if (changed) { - NotifyState(state); - } - } - bool MediaPlayer::UpdateStateLocked(int state) { if (state_ == state) { return false; } + PostLocked(Event::kState, state, std::string()); + state_ = state; return true; } - void MediaPlayer::NotifyState(int state) + void MediaPlayer::PostLocked(Event::Kind kind, int state, std::string message) { - // Called with the lock released: an observer runs Java code, which - // must never happen underneath a lock of ours. The observer does not - // change once the thread runs, so it is read without the lock. - if (observer_ != nullptr) { - observer_->OnStateChanged(state); - } + events_.push_back(Event{ kind, state, std::move(message) }); + + event_posted_.notify_one(); } - void MediaPlayer::ReportError(const std::string & message, int error) + void MediaPlayer::DeliverEvents() { - bool changed = false; + // The observer does not change once the threads run, so it is read + // without the lock, and called without it: an observer runs Java + // code, which must never happen underneath a lock of ours. + MediaPlayerObserver * observer = observer_.get(); - { - std::lock_guard lock(mutex_); + if (observer != nullptr) { + observer->OnThreadStart(); + } - // 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_) { - return; + bool closed = false; + + for (;;) { + Event event; + + { + std::unique_lock lock(mutex_); + + event_posted_.wait(lock, [this] { + return !events_.empty() || events_stopping_; + }); + + if (events_.empty()) { + // Stopping, with everything queued before delivered. + closed = closed_pending_; + closed_pending_ = false; + + break; + } + + event = std::move(events_.front()); + events_.pop_front(); } - // Playback stops where it failed, as if paused: what is queued - // stays queued, and playing again carries on from here. - if (playing_) { - playing_ = false; + if (observer != nullptr) { + Deliver(*observer, event); + } + } - pacer_->Pause(); - changed = UpdateStateLocked(kPaused); + if (observer != nullptr) { + if (closed) { + Deliver(*observer, Event{ Event::kState, kClosed, std::string() }); } + + observer->OnThreadStop(); + } + + if (observer != nullptr) { + observer->OnThreadStop(); + } + } + + void MediaPlayer::Deliver(MediaPlayerObserver & observer, const Event & event) + { + // Nothing may leave this thread, and an observer that could not take + // one report still gets the ones after it. + try { + switch (event.kind) { + case Event::kState: + observer.OnStateChanged(event.state); + break; + case Event::kEndOfStream: + observer.OnEndOfStream(); + break; + case Event::kError: + observer.OnError(event.message); + break; + } + } + catch (...) { } + } + + void MediaPlayer::ReportError(const std::string & message, int error) + { + std::string text = message + ": " + ErrorText(error); - if (changed) { - NotifyState(kPaused); + std::lock_guard lock(mutex_); + + // 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_) { + return; } - if (observer_ != nullptr) { - observer_->OnError(message + ": " + ErrorText(error)); + // Playback stops where it failed, as if paused: what is queued stays + // queued, and playing again carries on from here. + if (playing_) { + UpdateStateLocked(kPaused); + + playing_ = false; + + pacer_->Pause(); } + + PostLocked(Event::kError, kIdle, std::move(text)); } } 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 375aa6e97..e10f143ff 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 @@ -71,7 +71,7 @@ public class MediaPlayer implements AutoCloseable { /** The native player, or 0 once this player has been closed. */ private long handle; - /** Read on the native player's thread, so never a stale value. */ + /** Read on the native player's event thread, so never a stale value. */ private volatile MediaPlayerListener listener; /** @@ -270,7 +270,9 @@ public MediaPlayerState getState() { /** * Stops playback, releases the native player and the reader it took over, - * and waits for the player's thread to finish. Closing a player that is + * and waits for the player's threads to finish. By the time this returns, + * the listener has been told of everything that happened before, and of + * the {@link MediaPlayerState#CLOSED} state last. Closing a player that is * already closed does nothing. *

* Closing from within a {@link MediaPlayerListener} call, or from a sink @@ -322,7 +324,7 @@ public void close() { releaser.start(); } - /** Called by native code on the player's thread. */ + /** Called by native code on the player's event thread. */ private void onNativeStateChanged(int state) { MediaPlayerListener current = listener; @@ -331,7 +333,7 @@ private void onNativeStateChanged(int state) { } } - /** Called by native code on the player's thread. */ + /** Called by native code on the player's event thread. */ private void onNativeEndOfStream() { MediaPlayerListener current = listener; @@ -340,7 +342,7 @@ private void onNativeEndOfStream() { } } - /** Called by native code on the player's thread. */ + /** Called by native code on the player's event thread. */ private void onNativeError(String message) { MediaPlayerListener current = listener; 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 2a017e3aa..e4c0d94e2 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 @@ -19,10 +19,18 @@ /** * What a {@link MediaPlayer} reports while it runs. *

- * Calls arrive on the player's own thread, not on the thread that asked for - * playback, and that thread is the one decoding the media. An implementation - * must therefore return promptly and must not call back into the player in a - * way that waits for it. + * Calls arrive on the player's own event thread, never on the thread that + * asked for playback, nor on the one decoding the media. They come one at a + * time, never overlapping, in the order the player went through what they + * report, and all calls of one player arrive on the same thread. A command + * such as {@link MediaPlayer#play()} returns without waiting for its state + * change to be reported, so {@link MediaPlayer#getState()} may already read a + * later state than the call in progress reports. + *

+ * The reports behind a call wait for it to return, and so does closing the + * player from another thread. An implementation must therefore return + * promptly and must not call back into the player in a way that waits for + * it. *

* Closing the player from here, or the {@link MediaFileSource} it belongs to, * is fine: the native player is then released once this call has returned, 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 db4ba08c4..5a458c6e8 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 @@ -31,8 +31,11 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; @@ -599,27 +602,67 @@ public void onEndOfStream() { } } + @Test + void reportsInOrderOnOneThreadWithoutOverlap() throws Exception { + try (Sources sources = new Sources()) { + MediaPlayer player = new MediaPlayer(new MediaReader(asset()), + sources.video, sources.audio); + RecordingListener listener = new RecordingListener(player); + + player.setListener(listener); + player.seek(2_500_000); + + // Three changes from this thread, the end from the decode thread. + // The listener holds on to the second PLAYING until the decode + // thread has ended the source, which it does whatever the + // listener does, so a report of the end that did not wait for + // that call would overlap it. + player.play(); + player.pause(); + player.play(); + + assertTrue(listener.ended.await(10, TimeUnit.SECONDS), "no end of stream"); + + player.close(); + + // Everything has been reported once close() returns. + assertEquals(Arrays.asList("PLAYING", "PAUSED", "PLAYING", "ENDED", + "end of stream", "CLOSED"), listener.reports); + assertTrue(listener.endedWhileHeld.get(), "the source did not end while the listener was held"); + assertEquals(0, listener.overlaps.get(), "listener calls overlapped"); + assertEquals(1, listener.threads.size(), "listener called on: " + listener.threads); + assertFalse(listener.threads.contains(Thread.currentThread()), + "listener called on the thread giving the commands"); + } + } + @Test void closesFromStateChangeOfCommand() throws Exception { try (Sources sources = new Sources()) { MediaPlayer player = new MediaPlayer(new MediaReader(asset()), sources.video, sources.audio); AtomicInteger closes = new AtomicInteger(); + CountDownLatch closed = new CountDownLatch(1); player.setListener(new MediaPlayerListener() { @Override public void onStateChanged(MediaPlayerState state) { - // Called from within play(), on the calling thread. + // On the player's event thread, which the close cannot + // wait for, and after play() may already have returned. if (state == MediaPlayerState.PLAYING) { player.close(); closes.incrementAndGet(); } + else if (state == MediaPlayerState.CLOSED) { + closed.countDown(); + } } }); player.play(); + assertTrue(closed.await(10, TimeUnit.SECONDS), "not closed"); assertEquals(1, closes.get()); assertEquals(MediaPlayerState.CLOSED, player.getState()); @@ -939,6 +982,94 @@ private static Path asset() throws Exception { return Paths.get(url.toURI()); } + /** + * Records what a player reports, which thread it reports it on, and + * whether a report came in while another was still being handled. + */ + private static final class RecordingListener implements MediaPlayerListener { + + final List reports = Collections.synchronizedList(new ArrayList<>()); + final Set threads = ConcurrentHashMap.newKeySet(); + final AtomicInteger overlaps = new AtomicInteger(); + final AtomicBoolean endedWhileHeld = new AtomicBoolean(); + final CountDownLatch ended = new CountDownLatch(1); + + private final MediaPlayer player; + private final AtomicBoolean inCall = new AtomicBoolean(); + private int playing; + + + RecordingListener(MediaPlayer player) { + this.player = player; + } + + @Override + public void onStateChanged(MediaPlayerState state) { + enter(state.name()); + + try { + if (state == MediaPlayerState.PLAYING && ++playing == 2) { + endedWhileHeld.set(awaitEnded()); + } + } + finally { + leave(); + } + } + + @Override + public void onEndOfStream() { + enter("end of stream"); + leave(); + + ended.countDown(); + } + + @Override + public void onError(String message) { + enter("error: " + message); + leave(); + } + + private void enter(String report) { + if (!inCall.compareAndSet(false, true)) { + overlaps.incrementAndGet(); + } + + threads.add(Thread.currentThread()); + reports.add(report); + } + + private void leave() { + inCall.set(false); + } + + /** + * Waits for the player to read as ended, which the decode thread sets + * without waiting for this call to return. + */ + private boolean awaitEnded() { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + + while (player.getState() != MediaPlayerState.ENDED) { + if (System.nanoTime() > deadline) { + return false; + } + + try { + Thread.sleep(5); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + + return false; + } + } + + return true; + } + } + /** * A pair of sources with no tracks, for tests that only need somewhere to * deliver to.