Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions docs/guide/media/media-files.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 11 additions & 4 deletions webrtc-media/src/main/cpp/include/media/JavaPlayerObserver.h
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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;
Expand All @@ -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;
};
}

Expand Down
58 changes: 48 additions & 10 deletions webrtc-media/src/main/cpp/include/media/MediaPlayer.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
#include <atomic>
#include <condition_variable>
#include <cstdint>
#include <deque>
#include <memory>
#include <mutex>
#include <string>
Expand Down Expand Up @@ -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:
Expand All @@ -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<MediaPlayerObserver> observer);

// Asks for video to be decoded in hardware where the platform can.
Expand All @@ -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
Expand All @@ -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);
Expand Down Expand Up @@ -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.
Expand All @@ -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<Event> events_;
std::condition_variable event_posted_;
bool events_stopping_ = false;
bool closed_pending_ = false;

std::unique_ptr<MediaPlayerObserver> observer_;
bool running_ = false;
bool playing_ = false;
Expand Down
13 changes: 10 additions & 3 deletions webrtc-media/src/main/cpp/include/media/MediaPlayerObserver.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
33 changes: 33 additions & 0 deletions webrtc-media/src/main/cpp/src/media/JavaPlayerObserver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,39 @@ namespace ffmpeg
Detach(attached);
}

void JavaPlayerObserver::OnThreadStart()
{
if (vm_ == nullptr) {
return;
}

JNIEnv * env = nullptr;

if (vm_->GetEnv(reinterpret_cast<void **>(&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<char *>("MediaPlayer-events");
args.group = nullptr;

thread_attached_ = vm_->AttachCurrentThreadAsDaemon(
reinterpret_cast<void **>(&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) {
Expand Down
Loading
Loading