Skip to content

Commit 780f0d2

Browse files
committed
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.
1 parent 2dd25d2 commit 780f0d2

9 files changed

Lines changed: 408 additions & 124 deletions

File tree

‎docs/guide/media/media-files.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -176,9 +176,11 @@ source.setListener(new MediaPlayerListener() {
176176
```
177177

178178
::: warning
179-
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.
179+
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.
180180

181-
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.
181+
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.
182+
183+
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.
182184
:::
183185

184186
## Feeding Your Own Media Sources

‎webrtc-media/src/main/cpp/include/media/JavaPlayerObserver.h‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,11 @@ namespace ffmpeg
2626
// Passes a player's reports on to its Java MediaPlayer, which turns them
2727
// into calls on whatever listener the application set.
2828
//
29-
// The calls arrive on the player's own thread, which the JVM knows nothing
30-
// about, so each one attaches that thread, makes the call and detaches
31-
// again. Attaching is not free, but these are state changes and errors,
32-
// not frames: they happen a handful of times over a whole playback.
29+
// The calls arrive on the player's event thread, which the JVM knows
30+
// nothing about. That thread is attached when it starts and detached when
31+
// it stops, so that every call of a player is made on one and the same
32+
// Java thread, "MediaPlayer-events". A call on any other thread, such as
33+
// the release of the global reference, attaches for itself.
3334
class JavaPlayerObserver : public MediaPlayerObserver
3435
{
3536
public:
@@ -41,6 +42,8 @@ namespace ffmpeg
4142
JavaPlayerObserver(const JavaPlayerObserver &) = delete;
4243
JavaPlayerObserver & operator=(const JavaPlayerObserver &) = delete;
4344

45+
void OnThreadStart() override;
46+
void OnThreadStop() override;
4447
void OnStateChanged(int state) override;
4548
void OnEndOfStream() override;
4649
void OnError(const std::string & message) override;
@@ -63,6 +66,10 @@ namespace ffmpeg
6366
jmethodID on_state_changed_ = nullptr;
6467
jmethodID on_end_of_stream_ = nullptr;
6568
jmethodID on_error_ = nullptr;
69+
70+
// Whether OnThreadStart attached the event thread, which only
71+
// that thread reads or changes.
72+
bool thread_attached_ = false;
6673
};
6774
}
6875

‎webrtc-media/src/main/cpp/include/media/MediaPlayer.h‎

Lines changed: 48 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
#include <atomic>
2828
#include <condition_variable>
2929
#include <cstdint>
30+
#include <deque>
3031
#include <memory>
3132
#include <mutex>
3233
#include <string>
@@ -55,6 +56,12 @@ namespace ffmpeg
5556
// Decoding runs ahead of playback only as far as the pacer's queues allow.
5657
// Once those are full the decode thread blocks, which is what keeps a
5758
// whole file from being decoded into memory at once.
59+
//
60+
// What the observer is told goes through a thread of its own. Each report
61+
// is queued under the lock, in the same step as the change it reports,
62+
// and that thread makes the calls one after the other, in that order.
63+
// Neither a command nor the decode thread calls the observer itself, so
64+
// the calls never overlap, and a slow observer holds up no decoding.
5865
class MediaPlayer
5966
{
6067
public:
@@ -69,9 +76,9 @@ namespace ffmpeg
6976
MediaPlayer & operator=(const MediaPlayer &) = delete;
7077

7178
// Takes over the observer, which then lives as long as the
72-
// player does. Call this before Initialize: the observer is read
73-
// without the lock while it is being called, on the assumption
74-
// that it does not change once the thread is running.
79+
// player does. Call this before Initialize: the observer is
80+
// called without the lock, on the assumption that it does not
81+
// change once the threads are running.
7582
void SetObserver(std::unique_ptr<MediaPlayerObserver> observer);
7683

7784
// Asks for video to be decoded in hardware where the platform can.
@@ -98,8 +105,9 @@ namespace ffmpeg
98105
void SetLooping(bool looping);
99106
bool IsLooping() const;
100107

101-
// Stops playback and releases the thread. The player cannot be
102-
// used afterwards.
108+
// Stops playback and releases the threads. What was reported
109+
// before, and the closed state after it, has reached the observer
110+
// once this returns. The player cannot be used afterwards.
103111
void Close();
104112

105113
// Where playback has got to within the current pass, in
@@ -116,8 +124,32 @@ namespace ffmpeg
116124
bool IsOwnThread() const;
117125

118126
private:
127+
// A report waiting for the event thread.
128+
struct Event
129+
{
130+
enum Kind
131+
{
132+
kState,
133+
kEndOfStream,
134+
kError
135+
};
136+
137+
Kind kind = kState;
138+
int state = kIdle;
139+
std::string message;
140+
};
141+
119142
void Run();
120143

144+
// The event thread: hands what is queued to the observer, one
145+
// report after the other, until the player closes.
146+
void DeliverEvents();
147+
static void Deliver(MediaPlayerObserver & observer, const Event & event);
148+
149+
// Queues a report, with the lock held. Allocates, and so may
150+
// throw, in which case nothing has been queued.
151+
void PostLocked(Event::Kind kind, int state, std::string message);
152+
121153
// Reads and decodes until the source is exhausted. Returns false
122154
// if playback should stop, either on error or on close.
123155
bool PumpOnce(AVPacket * packet, bool * end_of_stream);
@@ -146,13 +178,10 @@ namespace ffmpeg
146178
// further back to try once the reader would land where it did
147179
// already, or the distance has grown past kMaxSeekBackUs.
148180
bool SeekFurtherBack();
149-
void SetState(int state);
150181

151-
// Records the state, with the lock held. Returns whether it
152-
// changed, in which case the caller reports it with NotifyState
153-
// once the lock is released.
182+
// Records the state, with the lock held, and queues the report of
183+
// it if it changed. Returns whether it did.
154184
bool UpdateStateLocked(int state);
155-
void NotifyState(int state);
156185

157186
// Stops playback where it is, as a pause does, and reports the
158187
// error. The thread stays, so that playback can be resumed.
@@ -169,10 +198,19 @@ namespace ffmpeg
169198
bool has_audio_ = false;
170199

171200
std::thread thread_;
201+
std::thread event_thread_;
172202

173203
mutable std::mutex mutex_;
174204
std::condition_variable command_;
175205

206+
// The reports for the event thread, and what wakes it, all under
207+
// the lock. The closed state is not queued, as queueing could
208+
// fail: it is what stopping the thread delivers, after the rest.
209+
std::deque<Event> events_;
210+
std::condition_variable event_posted_;
211+
bool events_stopping_ = false;
212+
bool closed_pending_ = false;
213+
176214
std::unique_ptr<MediaPlayerObserver> observer_;
177215
bool running_ = false;
178216
bool playing_ = false;

‎webrtc-media/src/main/cpp/include/media/MediaPlayerObserver.h‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,21 @@ namespace ffmpeg
2323
{
2424
// What a player reports while it runs.
2525
//
26-
// Every call arrives on the player's own thread, never on the thread that
27-
// asked for playback, so an implementation must not block: the thread it
28-
// holds up is the one decoding the media.
26+
// Every call arrives on the player's event thread, never on the thread
27+
// that asked for playback, one at a time and in the order the player went
28+
// through what it reports. An implementation should still return
29+
// promptly: the reports behind it wait, and so does a close.
2930
class MediaPlayerObserver
3031
{
3132
public:
3233
virtual ~MediaPlayerObserver() = default;
3334

35+
// Called on the event thread before the first report and after
36+
// the last, so that what the thread needs set up, such as being
37+
// known to the JVM, is set up once rather than for every call.
38+
virtual void OnThreadStart() {}
39+
virtual void OnThreadStop() {}
40+
3441
// The player moved to another state, as a MediaPlayerState value.
3542
virtual void OnStateChanged(int state) = 0;
3643

‎webrtc-media/src/main/cpp/src/media/JavaPlayerObserver.cpp‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,39 @@ namespace ffmpeg
6464
Detach(attached);
6565
}
6666

67+
void JavaPlayerObserver::OnThreadStart()
68+
{
69+
if (vm_ == nullptr) {
70+
return;
71+
}
72+
73+
JNIEnv * env = nullptr;
74+
75+
if (vm_->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_EDETACHED) {
76+
return;
77+
}
78+
79+
// A daemon, so that a player left open does not keep the JVM from
80+
// exiting. Every call made on this thread from here on finds it
81+
// attached, and leaves it so.
82+
JavaVMAttachArgs args;
83+
args.version = JNI_VERSION_1_6;
84+
args.name = const_cast<char *>("MediaPlayer-events");
85+
args.group = nullptr;
86+
87+
thread_attached_ = vm_->AttachCurrentThreadAsDaemon(
88+
reinterpret_cast<void **>(&env), &args) == JNI_OK;
89+
}
90+
91+
void JavaPlayerObserver::OnThreadStop()
92+
{
93+
if (thread_attached_) {
94+
thread_attached_ = false;
95+
96+
vm_->DetachCurrentThread();
97+
}
98+
}
99+
67100
void JavaPlayerObserver::OnStateChanged(int state)
68101
{
69102
if (on_state_changed_ == nullptr) {

0 commit comments

Comments
 (0)