Skip to content

Commit b1de27c

Browse files
authored
fix: close a media player from a sink of a track it feeds (#435)
A sink runs on the player's pacing thread, so close() from there joined that thread and aborted the JVM. The native release now detects the player's own threads and destroys the player on another one. MediaFileSource.close() no longer holds a lock while waiting for the player, which deadlocked against a close from a listener or sink.
1 parent 073a61e commit b1de27c

10 files changed

Lines changed: 177 additions & 13 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ source.setListener(new MediaPlayerListener() {
175175
::: warning
176176
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.
177177

178-
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.
178+
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.
179179
:::
180180

181181
## Feeding Your Own Media Sources

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,10 @@ namespace ffmpeg
116116
// playback has got to.
117117
int64_t GetPositionUs() const;
118118

119+
// True on the pacing thread, which is the one that calls the sinks
120+
// of the tracks fed by the sources.
121+
bool IsOwnThread() const;
122+
119123
private:
120124
struct VideoItem
121125
{

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,13 @@ namespace ffmpeg
106106

107107
int GetState() const;
108108

109+
// True on any thread of the player, which are the ones its
110+
// observer and the sinks of the tracks it feeds are called on.
111+
// Such a thread cannot destroy the player: that waits for the
112+
// thread, and what is below the call on its stack still uses
113+
// the player.
114+
bool IsOwnThread() const;
115+
109116
private:
110117
void Run();
111118

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

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424

2525
#include <memory>
2626
#include <string>
27+
#include <thread>
2728

2829
extern "C" {
2930
#include <libavutil/error.h>
@@ -155,7 +156,22 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_player_MediaPlayer_dispose
155156
{
156157
// Closing twice is allowed, so a handle that is already zero is simply
157158
// nothing to do.
158-
if (handle != 0) {
159-
delete PlayerOf(handle);
159+
if (handle == 0) {
160+
return;
161+
}
162+
163+
ffmpeg::MediaPlayer * player = PlayerOf(handle);
164+
165+
if (player->IsOwnThread()) {
166+
// Called from something the player is calling, such as a sink of a
167+
// track it feeds. Destroying it here would wait for this very thread,
168+
// and the delivery that made the call still uses the player once the
169+
// call returns. Another thread destroys it, and its wait ends as soon
170+
// as this thread is out of the player.
171+
std::thread([player] { delete player; }).detach();
172+
173+
return;
160174
}
175+
176+
delete player;
161177
}

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,13 @@ namespace ffmpeg
252252
return position_us_;
253253
}
254254

255+
bool MediaPacer::IsOwnThread() const
256+
{
257+
std::lock_guard<std::mutex> lock(mutex_);
258+
259+
return thread_.get_id() == std::this_thread::get_id();
260+
}
261+
255262
void MediaPacer::Run()
256263
{
257264
std::unique_lock<std::mutex> lock(mutex_);

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,19 @@ namespace ffmpeg
244244
return state_;
245245
}
246246

247+
bool MediaPlayer::IsOwnThread() const
248+
{
249+
{
250+
std::lock_guard<std::mutex> lock(mutex_);
251+
252+
if (thread_.get_id() == std::this_thread::get_id()) {
253+
return true;
254+
}
255+
}
256+
257+
return pacer_->IsOwnThread();
258+
}
259+
247260
void MediaPlayer::Run()
248261
{
249262
AVPacket * packet = av_packet_alloc();

‎webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaFileSource.java‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import java.io.IOException;
2020
import java.nio.file.Path;
2121
import java.time.Duration;
22+
import java.util.concurrent.atomic.AtomicBoolean;
2223

2324
import dev.onvoid.webrtc.media.audio.CustomAudioSource;
2425
import dev.onvoid.webrtc.media.video.CustomVideoSource;
@@ -66,7 +67,12 @@ public class MediaFileSource implements AutoCloseable {
6667

6768
private final MediaPlayer player;
6869

69-
private boolean closed;
70+
/**
71+
* Not guarded by a lock: a close holding one while it waits for the
72+
* player's threads would never end if one of them, in a listener or a
73+
* sink, closed this source as well.
74+
*/
75+
private final AtomicBoolean closed = new AtomicBoolean();
7076

7177

7278
/**
@@ -275,13 +281,11 @@ public MediaPlayerState getState() {
275281
* a source that is already closed does nothing.
276282
*/
277283
@Override
278-
public synchronized void close() {
279-
if (closed) {
284+
public void close() {
285+
if (!closed.compareAndSet(false, true)) {
280286
return;
281287
}
282288

283-
closed = true;
284-
285289
player.close();
286290

287291
disposeSources();

‎webrtc-media/src/main/java/dev/onvoid/webrtc/media/player/MediaPlayer.java‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -252,11 +252,12 @@ public MediaPlayerState getState() {
252252
* and waits for the player's thread to finish. Closing a player that is
253253
* already closed does nothing.
254254
* <p>
255-
* Closing from within a {@link MediaPlayerListener} call is allowed, but
256-
* cannot wait: the player's thread is the one making that call. The player
257-
* is closed at once, in that every later command does nothing and its
258-
* state reads as closed, and it is released on another thread as soon as
259-
* the listener call has returned.
255+
* Closing from within a {@link MediaPlayerListener} call, or from a sink
256+
* of a track made from one of the sources this player feeds, is allowed,
257+
* but cannot wait: the player's thread is the one making that call. The
258+
* player is closed at once, in that every later command does nothing and
259+
* its state reads as closed, and it is released on another thread as soon
260+
* as that call has returned.
260261
*/
261262
@Override
262263
public void close() {
@@ -274,6 +275,9 @@ public void close() {
274275
return;
275276
}
276277

278+
// A sink of a track this player feeds is called on one of its threads
279+
// too, but not through the listener. The native side tells those
280+
// apart itself, and hands the release to another thread.
277281
if (callbackDepth.get()[0] == 0) {
278282
dispose(closing);
279283

‎webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaFileSourceTest.java‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,14 @@
1919
import static org.junit.jupiter.api.Assertions.assertEquals;
2020
import static org.junit.jupiter.api.Assertions.assertNotNull;
2121
import static org.junit.jupiter.api.Assertions.assertThrows;
22+
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
2223
import static org.junit.jupiter.api.Assertions.assertTrue;
2324

2425
import java.io.IOException;
2526
import java.net.URL;
2627
import java.nio.file.Path;
2728
import java.nio.file.Paths;
29+
import java.time.Duration;
2830
import java.util.concurrent.CountDownLatch;
2931
import java.util.concurrent.TimeUnit;
3032
import java.util.concurrent.atomic.AtomicInteger;
@@ -162,6 +164,54 @@ public void onEndOfStream() {
162164
assertEquals(MediaPlayerState.CLOSED, source.getState());
163165
}
164166

167+
@Test
168+
void closesFromSinkWhileClosing() throws Exception {
169+
MediaFileSource source = new MediaFileSource(asset());
170+
VideoTrack track = factory.createVideoTrack("video", source.getVideoSource());
171+
CountDownLatch delivering = new CountDownLatch(1);
172+
AtomicInteger sinkCloses = new AtomicInteger();
173+
174+
VideoTrackSink sink = frame -> {
175+
try {
176+
if (delivering.getCount() == 0) {
177+
return;
178+
}
179+
180+
delivering.countDown();
181+
182+
// Once the player reads as closed, the close on the test
183+
// thread is waiting for this very thread to return.
184+
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
185+
186+
while (source.getState() != MediaPlayerState.CLOSED
187+
&& System.nanoTime() < deadline) {
188+
Thread.yield();
189+
}
190+
191+
// Must not wait for the close already under way.
192+
source.close();
193+
sinkCloses.incrementAndGet();
194+
}
195+
finally {
196+
frame.release();
197+
}
198+
};
199+
200+
track.addSink(sink);
201+
source.play();
202+
203+
assertTrue(delivering.await(10, TimeUnit.SECONDS), "nothing delivered");
204+
205+
// Would never return if the two closes waited for each other.
206+
assertTimeoutPreemptively(Duration.ofSeconds(10), source::close);
207+
208+
assertEquals(1, sinkCloses.get());
209+
assertEquals(MediaPlayerState.CLOSED, source.getState());
210+
211+
track.removeSink(sink);
212+
track.dispose();
213+
}
214+
165215
private static Path asset() throws Exception {
166216
URL url = MediaFileSourceTest.class.getResource(ASSET);
167217

‎webrtc-media/src/test/java/dev/onvoid/webrtc/media/player/MediaPlayerTest.java‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,65 @@ public void onStateChanged(MediaPlayerState state) {
431431
}
432432
}
433433

434+
@Test
435+
void closesFromVideoSink() throws Exception {
436+
try (Sources sources = new Sources()) {
437+
VideoTrack track = factory.createVideoTrack("video", sources.video);
438+
MediaPlayer player = new MediaPlayer(new MediaReader(asset()),
439+
sources.video, sources.audio);
440+
CountDownLatch closed = new CountDownLatch(1);
441+
442+
// Called on the player's pacing thread, which is the one closing
443+
// it has to wait for, and not through the listener.
444+
VideoTrackSink sink = frame -> {
445+
try {
446+
player.close();
447+
closed.countDown();
448+
}
449+
finally {
450+
frame.release();
451+
}
452+
};
453+
454+
track.addSink(sink);
455+
player.play();
456+
457+
assertTrue(closed.await(10, TimeUnit.SECONDS), "not closed");
458+
assertEquals(MediaPlayerState.CLOSED, player.getState());
459+
460+
player.close();
461+
462+
track.removeSink(sink);
463+
track.dispose();
464+
}
465+
}
466+
467+
@Test
468+
void closesFromAudioSink() throws Exception {
469+
try (Sources sources = new Sources()) {
470+
AudioTrack track = factory.createAudioTrack("audio", sources.audio);
471+
MediaPlayer player = new MediaPlayer(new MediaReader(asset()),
472+
sources.video, sources.audio);
473+
CountDownLatch closed = new CountDownLatch(1);
474+
475+
AudioTrackSink sink = (data, bits, rate, ch, count) -> {
476+
player.close();
477+
closed.countDown();
478+
};
479+
480+
track.addSink(sink);
481+
player.play();
482+
483+
assertTrue(closed.await(10, TimeUnit.SECONDS), "not closed");
484+
assertEquals(MediaPlayerState.CLOSED, player.getState());
485+
486+
player.close();
487+
488+
track.removeSink(sink);
489+
track.dispose();
490+
}
491+
}
492+
434493
@Test
435494
void outlivesDisposedSources() throws Exception {
436495
CustomVideoSource videoSource = new CustomVideoSource();

0 commit comments

Comments
 (0)