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
4 changes: 3 additions & 1 deletion docs/guide/media/media-files.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
});

Expand Down
6 changes: 6 additions & 0 deletions webrtc-media/src/main/cpp/include/JNI_AllocationFault.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions webrtc-media/src/main/cpp/include/media/AllocationFault.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
20 changes: 18 additions & 2 deletions webrtc-media/src/main/cpp/include/media/MediaPacer.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include <condition_variable>
#include <cstdint>
#include <deque>
#include <functional>
#include <mutex>
#include <thread>
#include <vector>
Expand Down Expand Up @@ -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<void(const char *, int, bool)> 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.
Expand Down Expand Up @@ -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<void(const char *, int, bool)> error_handler_;

const webrtc_java_api * api_;
void * video_source_;
Expand Down
8 changes: 7 additions & 1 deletion webrtc-media/src/main/cpp/include/media/MediaPlayer.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -230,6 +233,9 @@ namespace ffmpeg

std::unique_ptr<MediaPlayerObserver> 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;
Expand Down
12 changes: 12 additions & 0 deletions webrtc-media/src/main/cpp/src/JNI_AllocationFault.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
36 changes: 35 additions & 1 deletion webrtc-media/src/main/cpp/src/media/AllocationFault.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ extern "C" {

namespace
{
std::atomic<bool> fail_decoder_allocation{ false };
std::atomic<int> video_failures{ 0 };
std::atomic<int> audio_failures{ 0 };
std::atomic<bool> fail_string_copy{ false };
std::atomic<bool> fail_allocation{ false };
std::atomic<bool> fail_thread_start{ false };
Expand Down Expand Up @@ -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);
Expand All @@ -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();
}
Expand Down
86 changes: 71 additions & 15 deletions webrtc-media/src/main/cpp/src/media/MediaPacer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

#include "media/MediaPacer.h"
#include "media/AudioDecoder.h"
#include "media/AllocationFault.h"
#include "media/PlaybackProbe.h"
#include "media/VideoGeometry.h"

Expand Down Expand Up @@ -118,6 +119,23 @@ namespace ffmpeg
}
}

void MediaPacer::SetErrorHandler(std::function<void(const char *, int, bool)> handler)
{
error_handler_ = std::move(handler);
}

void MediaPacer::Cancel()
{
std::lock_guard<std::mutex> 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<std::mutex> lock(mutex_);
Expand Down Expand Up @@ -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<std::mutex> lock(mutex_);

Expand All @@ -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_);

Expand Down Expand Up @@ -417,17 +434,23 @@ 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
// capacity.
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;
Expand All @@ -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;
Expand All @@ -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 = {};
Expand Down Expand Up @@ -512,13 +558,19 @@ namespace ffmpeg
static_cast<uint8_t>(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 = {};
Expand All @@ -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);
}
}
Loading
Loading