Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: A FileInputStream that blocks in read() while other thread downloads remainder of file?

I have an FFmpeg-based video-playing app which is able to play content from any arbitrary InputStream.

It is important that the app is able to play a video file which is in the process of being downloaded. What I seem to need for this is a special kind of FileInputStream that will (a) share file access with the downloading thread, and (b) if it reaches the end of the downloaded portion, will quietly block until more content becomes available.

(a) seems easy enough thanks to RandomAccessFile, but I'm a bit puzzled about (b). I can probably hack something up that will work, but I am wondering if there's a standard approach to implementing this. Thinking about it in detail gives me a feeling that I may be missing something obvious.

Any thoughts? How would you guys do this?

like image 534
Reuben Scratton Avatar asked Nov 04 '22 09:11

Reuben Scratton


1 Answers

If you can push the data not in the file but into a OutputStream (or maybe write simulataneously to both FileOutputStream and other shared PipedOutputStream), this would be the easiest solution:

Use PipedOutputStream and PipedInputStream. This will allow you to implement both A and B, however you will need to somehow implement video buffering on the viewer side.

Basically your downloader thread will write every bit of data it gets to the PipedOutputStream. The write() method is not blocking, as the data is pushed to the internal buffer of the pipe.

Your viewer thread will simply read() from the pipedInputStream, as here is what the API says: This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

like image 83
bezmax Avatar answered Nov 09 '22 11:11

bezmax