|
19 | 19 | import static org.junit.jupiter.api.Assertions.assertEquals; |
20 | 20 | import static org.junit.jupiter.api.Assertions.assertNotNull; |
21 | 21 | import static org.junit.jupiter.api.Assertions.assertThrows; |
| 22 | +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; |
22 | 23 | import static org.junit.jupiter.api.Assertions.assertTrue; |
23 | 24 |
|
24 | 25 | import java.io.IOException; |
25 | 26 | import java.net.URL; |
26 | 27 | import java.nio.file.Path; |
27 | 28 | import java.nio.file.Paths; |
| 29 | +import java.time.Duration; |
28 | 30 | import java.util.concurrent.CountDownLatch; |
29 | 31 | import java.util.concurrent.TimeUnit; |
30 | 32 | import java.util.concurrent.atomic.AtomicInteger; |
@@ -162,6 +164,54 @@ public void onEndOfStream() { |
162 | 164 | assertEquals(MediaPlayerState.CLOSED, source.getState()); |
163 | 165 | } |
164 | 166 |
|
| 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 | + |
165 | 215 | private static Path asset() throws Exception { |
166 | 216 | URL url = MediaFileSourceTest.class.getResource(ASSET); |
167 | 217 |
|
|
0 commit comments