Commit Graph

1274 Commits

Author SHA1 Message Date
wm4 390772b58f demux_timeline: report network speed of slave connections
demux_timeline doesn't do any transport accesses itself. The slave
demuxers do this (these will actually access the stream layer and
perform e.g. network accesses). As a consequence, demux_timeline always
reported 0 bytes read, and network speed display didn't work.

Fix this by awkwardly reporting the amount of read bytes upwards. This
is not very nice, and requires explicit calls whenever the slave "might"
have read data.

Due to the way the reporting is done, it only works if the slaves do not
run demuxer threads, which makes things even less nice. (Fortunately
they don't anyway, because it would be a waste of resources.) Some
identifiers contain the word "hack" as a warning.

Some of the stupidity comes from the fact that demux.c itself resets the
stats randomly in order to calculate the bytes_per_second value, which
is useless for a slave, but of course is still done, because demux.c
itself is not aware of whether it's on the slave or top-level layer.

Unfortunately, this must do.

In theory, the demuxer thread/cache layer should be separated from
demuxer implementations. This would get rid of all the awkwardness and
nonsense. For example, the only threading involved would be the caching
layer, completely separate from demuxers themselves. It'd be the only
thing calculates speed rates for the player frontend, too (instead of
doing it for each demuxer, even if unused).
2019-09-19 20:37:04 +02:00
wm4 ebf183eeec demux: slightly cleanup network speed reporting
It was an ugly hack, and the next commit will make it even uglier.
Slightly reduce the ugliness to prevent death of too many brain cells,
though it's still an ugly hack.

The cleanup is really minor, but I guess the following commit would be
much worse otherwise. In particular, this commit checks accesses
(instead of having a public field with evil access rules), which should
avoid misunderstandings and incorrect use. Strictly speaking, the added
field is redundant, but the next commit complicates it a bit.
2019-09-19 20:37:04 +02:00
wm4 b230525352 demux_edl: add a special header to disable chapter generation
A bit of a hack.
2019-09-19 20:37:04 +02:00
wm4 b8f282fd32 demux_edl: explicitly error on unknown header types
I think this is better. On the other hand, this is a behavior change.
The EDL "spec" says that unknown fields are igored. But strictly
speaking, unknown headers are not "fields", but unknown entities.
2019-09-19 20:37:04 +02:00
wm4 9f8d9c218b demux_edl: minor cleanup to header parsing
EDL "headers" were always an afterthought, and kind of hacked on top of
the existing code. Improve it slightly, and make it follow the
conventions of the normal parsing. Basically use the same code structure
for them, just that they use different field names.
2019-09-19 20:37:04 +02:00
wm4 7fad173cfd demux, demux_edl: add extension for tracks sourced from separate streams
This commit adds an extension to mpv EDL, which basically allows you to
do the same as --audio-file, --external-file, etc. in a single EDL file.

This is a relatively quick & dirty implementation. The dirty part lies
in the fact that several shortcuts are taken. For example, struct
timeline now forms a singly linked list, which is really weird, but also
means the other timeline using demuxers (cue, mkv) don't need to be
touched. Also, memory management becomes even worse (weird object
ownership rules that are just fragile WTFs). There are some other
dubious small changes, mostly related to the weird representation of
separate streams.

demux_timeline.c contains the actual implementation of the separate
stream handling. For the most part, most things that used to be on the
top level are now in struct virtual_source, of which one for each
separate stream exists. This is basically like running multiple
demux_edl.c in parallel. Some changes could strictly speaking be split
into a separate commit, such as the stream_map type change.

Mostly untested. Seems to work for the intended purpose. Potential for
regressions for other timeline uses (like ordered chapters) is probably
low. One thing which could definitely break and which I didn't test is
the pseudo-DASH fragmented EDL code, of which ytdl can trigger various
forms in obscure situations. (Uh why don't we have a test suite.)

Background:

The intention is to use this for the ytdl wrapper. A certain streaming
site from a particularly brain damaged and plain evil Silicon Valley
company usually provides streams as separate audio and video streams.
The ytdl wrapper simply does use audio-add (i.e. adding it as external
track, like with --audio-file), which works mostly fine. Unfortunately,
mpv manages caching completely separately for external files. This has
the following potential problems:

1. Seek ranges are rendered incorrectly. They always use the "main"
stream, in this case the video stream. E.g. clicking into a cached range
on the OSC could trigger a low level seek if the audio stream is
actually not cached at the target position.

2. The stream cache bloats unnecessarily. Each stream may allocate the
full configured maximum cache size, which is not what the user intends
to do. Cached ranges are not pruned the same way, which creates disjoint
cache ranges, which only use memory and won't help with fast seeking or
playback.

3. mpv will try to aggressively read from both streams. This is done
from different threads, with no regard which stream is more important.
So it might happen that one stream starves the other one, especially if
they have different bitrates.

4. Every stream will use a separate thread, which is an unnecessary
waste of system resources.

In theory, the following solutions are available (this commit works
towards D):

A. Centrally manage reading and caching of all streams. A single thread
would do all I/O, and decide from which stream it should read next. As
long as the total TCP/socket buffering is not too high, this should be
effective to avoid starvation issues. This can also manage the cached
ranges better. It would also get rid of the quite useless additional
demuxer threads. This solution is conceptually simple, but requires
refactoring the entire demuxer middle layer.

B. Attempt to coordinate the demuxer threads. This would maintain a
shared cache and readahead state to solve the mentioned problems
explicitly. While this sounds simple and like an incremental change,
it's probably hard to implement, creates more messy special cases,
solution A. seems just a better and simpler variant of this. (On the
other hand, A. requires refactoring more code.)

C. Render an intersection of the seek ranges across all streams. This
fixes only problem 1.

D. Merge all streams in a dedicated wrapper demuxer. The general demuxer
layer remains unchanged, and reading from separate streams is handled as
special case. This effectively achieves the same as A. In particular,
caching is simply handled by the usual demuxer cache layer, which sees
the wrapper demuxer as a single stream of interleaved packets. One
implementation variant of this is to reuse the EDL infrastructure, which
this commit does.

All in all, solution A would be preferable, because it's cleaner and
works for all external streams in general.

Some previous commit tried to prepare for implementing solution A. This
could still happen. But it could take years until this is finally
seriously started and finished. In any case, this commit doesn't block
or complicate such attempts, which is also why it's the way to go.

It's worth mentioning that original mplayer handles external files by
creating a wrapper demuxer. This is like a less ideal mixture of A. and
D. (The similarity with A. is that extending the mplayer approach to be
fully dynamic and without certain disadvantages caused by the wrapper
would end up with A. anyway. The similarity with D. is that due to the
wrapper, no higher level code needs to be changed.)
2019-09-19 20:37:04 +02:00
wm4 1d0da7d950 demux: make demuxer list static, remove ancient comment
I'd actually very much encourage demuxer implementations outside
problematic libavformat.
2019-09-19 20:37:04 +02:00
wm4 ff1f863bda demux_lavf: increase max. probe size
For those shitty mp3s with extremely large ID3v2/APIC tags, and for
which libavformat insists on reading all data until after the ID3v2.
2019-09-19 20:37:04 +02:00
wm4 c91e659f88 stream: redo buffer handling and allow arbitrary size for stream_peek()
struct stream used to include the stream buffer, including peek buffer,
inline in the struct. It could not be resized, which means the maximum
peek size was set in stone. This meant demux_lavf.c could peek only so
much data.

Change it to use a dynamic buffer. Because it's possible, keep the
inline buffer for default buffer sizes (which are basically always used
outside of file opening). It's unknown whether it really helps with
anything. Probably not.

This is also the fallback plan in case we need something like the old
stream cache in order to deal with mp4 + unseekable http: the code can
now be easily changed to use any buffer size.
2019-09-19 20:37:04 +02:00
wm4 ca142be7e8 demux: another unused function 2019-09-19 20:37:04 +02:00
wm4 adbd035b50 demux: autoselection is gone
Was used by DVD, I think.
2019-09-19 20:37:04 +02:00
wm4 cfa5c73cb5 demux: remove some more minor dead code
Also add clarifications.
2019-09-19 20:37:04 +02:00
wm4 18180ae89b demux: get rid of ->control callback
The only thing left is the notification for track switching. Just get
rid of that.

There's probably no real reason to get rid of control(), but why not. I
think I was actually trying to do some real work but fuck that.
2019-09-19 20:37:04 +02:00
wm4 5114c69c7f demux: change hack for closing subtitle files early
Subtitles (and a few other file types, like playlists) are not streamed,
but fully read on opening. This means keeping the file handle or network
socket open is a waste of resources and could cause other weird
behavior. This is why there's a hack to close them after opening.

Change this hack to make the demuxer itself do this, which is less
weird. (Until recently, demuxer->stream ownership was more complex,
which is why it was done this way.)

There is some evil shit due to a huge ownership/lifetime mess of various
objects. Especially EDL (the currently only nested demuxer case)
requires being careful about mp_cancel and passing down stream pointers.

As one defensive programming measure, stop accessing the "stream"
variable in open_given_type(), even where it would still work. This
includes removing a redundant line of code, and removing the peak call,
which should not be needed anymore, as the remaining demuxers do this
mostly correctly.
2019-09-19 20:37:04 +02:00
wm4 b1c202c12f demux: make demux_open() private
I always wanted to get rid of this, because it makes the ownership rules
for the stream pointer really awkward. demux_edl.c was the only
remaining user of this. Replace it with a semi-clever idea: the init
segment shit can be used to pass the "file" contents as memory block,
and "memory://" itself provides an empty stream. I have no idea if this
actually works, because I didn't immediately find a test stream (would
have to be some youtube DASH shit).
2019-09-19 20:37:04 +02:00
wm4 5c7ecad93a demux: simplify API for returning cache status
Instead of going through those weird DEMUXER_CTRLs, query this
information directly. I'm not sure which kind of brain damage made me
use CTRLs for these. Since there are no other DEMUXER_CTRLs that make
sense for the frontend, remove the remaining infrastructure for them
too.
2019-09-19 20:37:04 +02:00
wm4 b298140b07 demux: return stream file size differently, rip out stream ctrls
The stream size return was the only thing that still required doing
STREAM_CTRLs from frontend through the demuxer layer. This can be done
much easier, so rip it out. Also rip out the now unused infrastructure
for STREAM_CTRLs via demuxer layer.
2019-09-19 20:37:04 +02:00
wm4 f77515ebaf stream_libarchive: remove base filename stuff
Apparently this was so that when playing a video file from a .rar file,
it would load external subtitles with the same name (instead of looking
for mpv's rar:// mangled URL). This was requested on github almost 5
years ago. Seems like a weird feature, and I don't care. Drop it,
because it complicates some in progress change.
2019-09-19 20:37:04 +02:00
wm4 0fa38121a6 demux_timeline: fix off by one error, rearrange weird code
This code set pkt->stream to a value which I'm not sure whether it's
correct. A recent commit overwrote it with a value that is definitely
correct.

There appears to be an off by one error. No fucking clue whether this
was somehow correct, but applying an apparent fix does not seem to break
anything, so whatever.
2019-09-19 20:37:04 +02:00
wm4 b9be20b529 demux: return packets directly from demuxer instead of using sh_stream
Preparation for other potential changes to separate demuxer cache/thread
and actual demuxers.

Most things are untested, but it seems to work somewhat.
2019-09-19 20:37:04 +02:00
wm4 a25b3d61a1 demux, stream: remove old rar support in favor of libarchive
The old rar code could do uncompressed rar, libarchive supports at least
some rar compression algorithms. There is no need to keep the old rar
code.
2019-09-13 17:35:06 +02:00
wm4 a75b249b0b command, demux: remove program property
The "program" property could switch between TS programs. It was rather
complex and rather obscure (even if you deal with TS captures, you
usually don't need it). If anyone actually needs it (did anyone ever
attempt to even use it?), it should be rewritten. The demuxer should
export a program list, and the frontend should handle the "cycling"
logic.
2019-09-13 17:33:58 +02:00
wm4 b30e85508a Remove classic Linux analog TV support, and DVB runtime controls
Linux analog TV support (via tv://) was excessively complex, and
whenever I attempted to use it (cameras or loopback devices), it didn't
work well, or would have required some major work to update it. It's
very much stuck in the analog past (my favorite are the frequency tables
in frequencies.c for analog TV channels which don't exist anymore).

Especially cameras and such work fine with libavdevice and better than
tv://, for example:

  mpv av://v4l2:/dev/video0

(adding --profile=low-latency --untimed even makes it mostly realtime)

Adding a new input layer that targets such "modern" uses would be
acceptable, if anyone is interested in it. The old TV code is just too
focused on actual analog TV.

DVB is rather obscure, but has an active maintainer, so don't remove it.
However, the demux/stream ctrl layer must go, so remove controls for
channel switching. Most of these could be reimplemented by using the
normal method for option runtime changes.
2019-09-13 17:32:19 +02:00
wm4 a9d83eac40 Remove optical disc fancification layers
This removes anything related to DVD/BD/CD that negatively affected the
core code. It includes trying to rewrite timestamps (since DVDs and
Blurays do not set packet stream timestamps to playback time, and can
even have resets mid-stream), export of chapters, stream languages,
export of title/track lists, and all that.

Only basic seeking is supported. It is very much possible that seeking
completely fails on some discs (on some parts of the timeline), because
timestamp rewriting was removed.

Note that I don't give a shit about optical media. If you want to watch
them, rip them. Keeping some bare support for DVD/BD is the most I'm
going to do to appease the type of lazy, obnoxious users who will care.
There are other players which are better at optical discs.
2019-09-13 17:31:59 +02:00
Tom Yan 763eaad2aa demux: ignore forced demuxer type for directories
this for example allows --demuxer=rawaudio to work on directories
2019-09-02 01:24:26 +03:00
wm4 c379950ce0 codec_tags: fix wrong buffer size
Obvious mistake. This reported 44 bytes more data than what was
available. Could cause out of bounds reads. Security researchers would
claim a major victory if they found something like this in more popular
software, and would create a website for it.
2019-07-03 17:47:24 +03:00
Philip Sequeira a38aa74454 demux_mkv: copy attachments (fonts) from ordered chapter sources
They might be needed for rendering subs from those sources.

Fixes #6009.
2019-06-12 23:34:47 +03:00
zc62 de2b1920f3 demux: support cue sheets longer than 100 minutes
Remove the 2-digit-number restriction when reading the number of
minutes in the cue sheet INDEX command.

Fixes #6481
2019-04-01 23:39:08 +02:00
Jan Ekström 199aabddcc Merge branch 'master' into pr6360
Manual changes done:
  * Merged the interface-changes under the already master'd changes.
  * Moved the hwdec-related option changes to video/decode/vd_lavc.c.
2019-03-11 01:00:27 +02:00
Philip Sequeira 89eacf8131 demux_edl: don't assume data follows a comment line
There could be another comment line or the end of the file.

Fixes #6529.
2019-03-03 13:13:45 +01:00
Gunnar Marten b275232141 demux: fix seek range update after head packets are pruned
The seek range update was to early and did not take the removed head
packets into account. And therefore missed that the queue was not
BOF anymore.
This led to not be able to backward seek before the first packet of
the first seek range.

Fix it by moving the seek range update after the possible removal and
the change of the BOF flag.

Fixes: #6522
2019-03-01 00:55:06 +02:00
Benjamin Barenblat 585f9ff42f demux: make ALBUM ReplayGain tags optional when using libavformat
Commit e392d6610d modified the native
demuxer to use track gain as a fallback for album gain if the latter is
not present. This commit makes functionally equivalent changes in the
libavformat demuxer.
2019-01-16 16:58:33 +01:00
sfan5 e0419fb181 demux: fix regression in decision about stream caching
The `streaming` flag covers more cases than just networked streams,
such as files read from NFS, SMB or FUSE mountpoints.
2018-12-06 18:46:29 +01:00
Niklas Haas 3dc2d7d7dd demux: fix memleak in allocation with params=NULL
The default behavior for `does not own stream` should be false, but this
condition is inverted so we need to default the base case to `true`.
2018-12-06 15:47:16 +01:00
wm4 af9722cd3e demux: fix some theoretical UB with no impact
If the number of chapters is 0, the chapter list can be NULL. clang
complains that we pass NULL to qsort(). This is yet another pointless UB
that exists for no reason other than wasting your time.
2018-12-06 10:33:52 +01:00
wm4 ace16fcfff demux_mkv: simplify avi compat. codec_tags.c GUID lookup
The redundancy here always annoyed me. Back then I didn't change it
because it's hard to test and I just had fixed something. This doesn't
matter anymore, so simplify it, without testing and with the risk that
something breaks (why care).
2018-12-06 10:31:59 +01:00
wm4 21c9ee71e2 demux: remove some dead code
No idea what that shit is. Likely forgotten when timed metadata was
introduced, and some of the old mechanisms were replaced.
2018-12-06 10:31:30 +01:00
wm4 9d8afcf79e demux: add another stream recording feature
--record-file is nice, but only sometimes. If you watch some sort of
livestream which you want to record, it's actually much nicer not to
record what you're currently "seeing", but anything you're receiving.
2018-12-06 10:31:10 +01:00
wm4 02756c3735 demux_lavf: to get effective HLS bitrate
In theory, this could be easily done with custom I/O. In practice, all
the halfassed garbage in FFmpeg shits itself and fucks up like there's
no tomorrow. There are several problems:

1. FFmpeg pretends you can do custom I/O, but in reality there's a lot
that custom I/O can do. hls.c even contains explicit checks to disable
important things if custom I/O is used! In particular, you can't use the
HTTP keepalive functionality (needed for somewhat decent HLS
performance), because some cranky asshole in the cursed FFmpeg dev.
community blocked it.

2. The implementation of nested I/O callbacks (io_open/io_close) is
bogus and halfassed (like everything in FFmpeg, really). It will call
io_open on some URLs without ever calling io_close. Instead, it'll call
avio_close() on the context directly. From what I can tell, avio_close()
is incompable to custom I/O anyway (overwhelmed by their own garbage,
the fFmpeg devs created the io_close callback for this reason, because
they couldn't fix their own fucking garbage). This commit adds some
shitty workaround for this (technically triggers UB, but with that
garbage heap of a library we depend on it's not like it matters).

3. Even then, you can't proxy I/O contexts (see 1.), but we can just
keep track of the opened nested I/O contexts. The bytes_read is
documented as not public, but reading it is literally the only way to
get what we want.

A more reasonable approach would probably be using curl. It could
transparently handle the keep-alive thing, as well as propagating
cookies etc. (which doesn't work with the FFmpeg approach if you use
custom I/O). Of course even better if there were an independent HLS
implementation anywhere. FFmpeg's HLS support is so embarrassing
pathetic and just goes to show that they belong into the past
(multimedia from 2000-2010) and should either modernize or fuck off.
With FFmpeg's shit-crusted structures, todic communities, and retarded
assholes denying progress, probably the latter. Did I already mention
that FFmpeg is a shit fucked steaming pile of garbage shit?

And all just to get some basic I/O stats, that any proper HLS consumer
requires in order to implement adaptive streaming correctly (i.e.
browser based players, and nothing FFmshit based).
2018-12-06 10:30:57 +01:00
wm4 4dfaa37384 demux, stream: readd cache-speed in some other form
it's more like an input speed rather than a cache speed, but who cares.
2018-12-06 10:30:41 +01:00
Anton Kindestam 8b83c89966 Merge commit '559a400ac36e75a8d73ba263fd7fa6736df1c2da' into wm4-commits--merge-edition
This bumps libmpv version to 1.103
2018-12-05 19:19:24 +01:00
wm4 315004a38a demux_lavf: hack-fix EDL mp4 DASH hack
I encountered a stream that fails with "Could not demux init fragment.".
It turns out this is a regression from the recent change to that code.
The assumption was that demux_lavf.c would treat this as concatenated
stream - which it does, but not for probing.

Doing this transparently is hard without doing it properly. Doing it
properly would mean creating some sort of stream_concat (reminiscent of
that FFmpeg security bug). I probably don't want to go there, and I
think libavformat should just support this directly, so whatever.
Hack-fix this with the knowledge that the init segment will always
contain the headers.
2018-10-01 10:41:01 +02:00
wm4 36e7ef96fc demux: allow cache sizes > 2GB
There was no reason to limit this. Only some int fields had to be
changed to size_t.
2018-10-01 10:41:01 +02:00
wm4 20d381d1e9 demux_lavf: v4l streams are not seekable
FFmpeg is retarded enough not to give us any indication whether it is
(unless we query fields not in the ABI/API). I bet FFmpeg developers
love it when library users have to litter their code with duplicated
information.
2018-10-01 10:41:01 +02:00
Tom Yan 95636c65e7 demux/packet: fix demux_packet_shorten
for the rawaudio demuxer to do the expected gapless playback
2018-09-30 12:32:03 +03:00
wm4 559a400ac3 demux, stream: rip out the classic stream cache
The demuxer cache is the only cache now. Might need another change to
combat seeking failures in mp4 etc. The only bad thing is the loss of
cache-speed, which was sort of nice to have.
2018-08-31 12:55:22 +02:00
wm4 120dcdf5cc demux: allow cache sizes > 2GB
There was no reason to limit this. Only some int fields had to be
changed to size_t.
2018-08-24 12:56:41 +02:00
wm4 9467e90c5b demux_lavf: v4l streams are not seekable
FFmpeg is retarded enough not to give us any indication whether it is
(unless we query fields not in the ABI/API). I bet FFmpeg developers
love it when library users have to litter their code with duplicated
information.
2018-08-24 12:55:10 +02:00
sfan5 2e7f60c386 demux_edl: add title option to override title of chapters 2018-08-13 19:09:57 +02:00
Aman Gupta d5cad85625 player: expose hearing/visual impaired flags on audio tracks
Signed-off-by: Aman Gupta <aman@tmm1.net>
2018-08-13 19:09:44 +02:00
Nicolas F 4d1269d9db demux_mkv: add A_MLP to mkv_audio_tags
Fixes #5923
2018-06-22 21:17:26 +03:00
wm4 31bce1cbe7 demux_lavf: drop obscure genpts option
This code shouldn't even exist in libavformat. If you still need it, you
can enable it via --demuxer-lavf-o.
2018-05-31 01:24:51 +03:00
wm4 4e750e31a1 demux: fix/improve aspects of EOF signaling
When the current packet queue was completely empty, and EOF was reached,
the queue->is_eof flag was not correctly set to true. Change this by
reading ds->eof to check whether the stream is considered EOF. We also
need to make sure update_seek_ranges() is called in this case, so change
the code to simply call it when queue->is_eof changes.

Also, read_packet() needs to call adjust_seek_range_on_packet() if
ds->eof changes. In that case, the decoder also needs to be notified
about EOF. So both of these should be called when ds->eof changes to
true. (Other code outside of this function deals with the case when
ds->eof is changed to false.)

In addition, this code was kind of shoddy about calling wakeup_ds()
correctly. It looks like there was an inverted condition, and sent a
wakeup to the decoder only when ds->eof was already true, which is
obviously bogus. The final EOF case tried to be somehow clever about
checking in->last_eof for notifying the codec, which is sort of OK, but
seems to be strictly worse than just checking whether ds->eof changed.
Fix these things.
2018-05-25 10:46:24 +02:00
wm4 5df811bd53 demux_lavf: remove ffm blacklist entry
ffm (ffserver) was removed from ffmpeg.
2018-05-25 10:17:06 +02:00
wm4 982416266c demux_lavf: drop obscure genpts option
This code shouldn't even exist in libavformat. If you still need it, you
can enable it via --demuxer-lavf-o.
2018-05-24 19:56:35 +02:00
wm4 fe6b2f9103 m_config: add a special define to access main config
Passing NULL to mp_get_config_group() returns the main option struct.
This is just a dumb hack to deal with inconsistencies caused by legacy
things (as I'll claim), and will probably be changed in the future. So
before littering the whole code base with hard to find NULL parameters,
require using callers an easy to find separate define.
2018-05-24 19:56:35 +02:00
wm4 c24520b7f3 demux: add a way to destroy the demuxer asynchronously
This will enable the player core to terminate the demuxers in a "nicer"
way without having to block on network. If it just used demux_free(), it
would either have to block on network, or like currently, essentially
kill all I/O forcefully.

The API is slightly awkward, because demuxer lifetime is bound to its
allocation. On the other hand, changing that would also be awkward, and
introduce weird in-between states that would have to be handled in tons
of places.

Currently unused, to be user later.
2018-05-24 19:56:35 +02:00
wm4 29a51900c6 player: some further cleanup of the mp_cancel crap
Alway give each demuxer its own mp_cancel instance. This makes
management of the mp_cancel things much easier. Also, instead of having
add/remove functions for mp_cancel slaves, replace them with a simpler
to use set_parent function. Remove cancel_and_free_demuxer(), which had
mpctx as parameter only to check an assumption. With this commit,
demuxers have their own mp_cancel, so add demux_cancel_and_free() which
makes use of it.
2018-05-24 19:56:35 +02:00
wm4 d33e5972b3 demux: get rid of free_demuxer[_and_stream]()
Them being separate is just dumb. Replace them with a single
demux_free() function, and free its stream by default. Not freeing the
stream is only needed in 1 special case (demux_disc.c), use a special
flag to not free the stream in this case.
2018-05-24 19:56:35 +02:00
wm4 d7ca95c3ea command: whitelist some blocking accesses for certain demuxers/streams
The properties/commands touched in this commit are all for obscure
special inputs (BD/DVD/DVB/TV), and they all block on the demuxer/stream
layer. For network streams, this blocking is very unwelcome. They will
affect playback and probably introduce pauses and frame drops. The
player can even freeze fully, and the logic that tries to make playback
abortable even if frozen complicates the player.

Since the mentioned accesses are not needed for network streams, but
they will block on network streams even though they're going to fail,
add a flag that coarsely enables/disables these accesses. Essentially it
establishes a whitelist of demuxers/streams which support them.

In theory you could to access BD/DVD images over network (or add such
support, I don't think it's a thing in mpv). In these cases these
controls still can block and could even "freeze" the player completely.

Writing to the "program" and "cache-size" properties still can block
even for network streams. Just don't use them if you don't want freezes.
2018-05-24 19:56:35 +02:00
wm4 76dc5d9aa9 command: make loadlist command async and abortable
Don't allow it to freeze everything when loading a playlist from network
(although you definitely shouldn't do that, but whatever).

This also affects the really obscure --ordered-chapters-files option.
The --playlist option on the other hand has no choice but to freeze the
shit, because there's no concept of aborting the player during command
line parsing.
2018-05-24 19:56:35 +02:00
wm4 f9713921a3 demux: add a "cancel" field
Instead of relying on demuxer->stream->cancel. This is better because
the stream is potentially closed and replaced.
2018-05-24 19:56:35 +02:00
wm4 31b78ad7fa misc: move mp_cancel from stream.c to thread_tools.c
It seems a bit inappropriate to have dumped this into stream.c, even if
it's roughly speaking its main user. At least it made its way somewhat
unfortunately to other components not related to the stream or demuxer
layer at all.

I'm too greedy to give this weird helper its own file, so dump it into
thread_tools.c.

Probably a somewhat pointless change.
2018-05-24 19:56:35 +02:00
wm4 75b2e6ed67 demux: late streams on start shouldn't restrict the seek range
If a stream starts later than the others at the start of the file, it
shouldn't restrict the seek range to the time stamp where it begins.
This is similar to the previous commit, just for the other end.
2018-05-24 19:56:34 +02:00
wm4 2fc59ea8b3 demux: streams that reached EOF shouldn't restrict the seek range
Normally, the seek range is the minimum overlap of the cached ranges of
each stream. But if one of the streams ends earlier, this leads to the
seek range getting cut off, even if you could seek there.

Change it so that EOF streams cannot restrict the end of the seek range.
They can only extend it. This is the opposite from not-EOF streams, so
they need to be handled separately. In particular, they get exluded from
normal end range calculation, but when full EOF is reached, all streams
are EOF, and the maximum end time can be used to set the seek end time.
(In theory we could also take the max with the demuxer signaled total
file duration, but let's not for now.)

Also, if a stream is completely empty, essentially skip it, instead of
considering the range unseekable. (Also, we don't need to mess with
seek_start in this case, because it will be NOPTS and is skipped
anyway.)
2018-05-24 19:56:34 +02:00
wm4 9ceccd6fca demux: fix/improve aspects of EOF signaling
When the current packet queue was completely empty, and EOF was reached,
the queue->is_eof flag was not correctly set to true. Change this by
reading ds->eof to check whether the stream is considered EOF. We also
need to make sure update_seek_ranges() is called in this case, so change
the code to simply call it when queue->is_eof changes.

Also, read_packet() needs to call adjust_seek_range_on_packet() if
ds->eof changes. In that case, the decoder also needs to be notified
about EOF. So both of these should be called when ds->eof changes to
true. (Other code outside of this function deals with the case when
ds->eof is changed to false.)

In addition, this code was kind of shoddy about calling wakeup_ds()
correctly. It looks like there was an inverted condition, and sent a
wakeup to the decoder only when ds->eof was already true, which is
obviously bogus. The final EOF case tried to be somehow clever about
checking in->last_eof for notifying the codec, which is sort of OK, but
seems to be strictly worse than just checking whether ds->eof changed.
Fix these things.
2018-05-24 19:56:34 +02:00
wm4 4e05f75261 demux_lavf: remove ffm blacklist entry
ffm (ffserver) was removed from ffmpeg.
2018-05-24 19:56:34 +02:00
Aman Gupta 814869759c demux, player: fix playback of sparse video streams (w/ still images)
Fixes several issues playing back mpegts with video streams marked
as having "still images". For example, see this video which has
frames only every 6s: https://s3.amazonaws.com/tmm1/music-choice.ts

Changes include:
- start playback right away, without waiting for first video frame
- do not consider the sparse video stream in demuxer underrun detection
- do not require multiple video frames for the VO
- use audio as the master stream for demuxer metadata events
- use audio stream for playback time

Signed-off-by: Aman Gupta <aman@tmm1.net>
2018-05-24 10:26:41 -07:00
Aman Gupta b24bd4e570 demux_lavf: co-locate disposition checks
Signed-off-by: Aman Gupta <aman@tmm1.net>
2018-05-24 10:26:41 -07:00
wm4 137e34e3e9 demux_mkv: adjust log verbosity levels
With -v -v ("debug" level), which is the default for --log-file, this
would log every damn Matroska EBML element and some other uninteresting
things, which was very noisy.

Adjust the log levels to make them less noisy. Also, change some log
calls to MP_ERR for things which are actually errors.
2018-04-29 02:21:32 +03:00
wm4 c767451796 demux_lavf: discard "und" language tag
Going by ISO 639.2, "und" means "Undetermined". Whatever it's supposed
to mean, in practice it's user for "unset". We prefer if the language
tag remains simply unset in this case.

This removes an ugliness with mp4 in partricular, because libavformat
will export unset languages as such, which affects most mp4 files.
2018-04-29 02:21:32 +03:00
wm4 e7e06a47a0 demux: support for some kinds of timed metadata
This makes ICY title changes show up at approximately the correct time,
even if the demuxer buffer is huge. (It'll still be wrong if the stream
byte cache contains a meaningful amount of data.)

It should have the same effect for mid-stream metadata changes in e.g.
OGG (untested).

This is still somewhat fishy, but in parts due to ICY being fishy, and
FFmpeg's metadata change API being somewhat fishy. For example, what
happens if you seek? With FFmpeg AVFMT_EVENT_FLAG_METADATA_UPDATED and
AVSTREAM_EVENT_FLAG_METADATA_UPDATED we hope that FFmpeg will correctly
restore the correct metadata when the first packet is returned.

If you seke with ICY, we're out of luck, and some audio will be
associated with the wrong tag until we get a new title through ICY
metadata update at an essentially random point (it's mostly inherent to
ICY). Then the tags will switch back and forth, and this behavior will
stick with the data stored in the demuxer cache. Fortunately, this can
happen only if the HTTP stream is actually seekable, which it usually is
not for ICY things. Seeking doesn't even make sense with ICY, since you
can't know the exact metadata location. Basically ICY metsdata sucks.

Some complexity is due to a microoptimization: I didn't want additional
atomic accesses for each packet if no timed metadata is used. (It
probably doesn't matter at all.)
2018-04-18 01:17:42 +03:00
Aman Gupta 8f1c40f702 demux: mark eia608 packets as keyframes
This fixes an issue where captions stop rendering after an
in-demuxer-cache seek, because the demuxer keeps waiting to find
a keyframe (ds->skip_to_keyframe set to true in execute_cache_seek).
2018-04-17 01:02:47 +03:00
Aman Gupta b8de7d6ff3 demux, player: mark dependent tracks
ffmpeg marks audio tracks which are not meant to be played standalone
as DEPENDENT. these are typically used in DVB broadcasts for audio
descriptions, and are meant to be mixed into the main audio track during
playback.
2018-04-17 01:01:50 +03:00
wm4 028e51d8af demux_lavf: use new libavformat semantics for stream resync
I changed avio_flush() and introduced avformat_flush() exactly for this
reason.

Used with DVD/BD only (on seeks and when setting the "angle" property).
Seems to work, but wasn't tested too thoroughly (I don't care about
optical discs, I only want this ugly stuff gone that might even violate
the API/ABI).
2018-04-16 22:47:33 +03:00
wm4 fdb39f313b demux: fix deadlock on "program" property changes
Tries to recursively lock a non-recursive lock, which usually ends in a
deadlock. Must have been broken by some past refactor.
2018-04-15 21:07:13 +03:00
wm4 4381753207 demux_mkv: fix certain cases of recursive SeekHeads
Some shittily muxed files (by a certain HandBrake+libavformat combo)
contain a SeekHead pointing to a SeekHead at the end of the file, which
in turn points to track headers (also at the end of the file). This
failed because the demuxer didn't bother to actually read the elements
listed by the second SeekHead, so no track headers were read, and
playback broke.

Somehow commit 6fe75c38 broke this for no reason. It adds a "needed"
field, which seems completely pointless and replaced the "parsed" flag
in an incomplete way. In particular, the "needed" field was not set when
a _recursive_ SeekHead was read, so those elements were not read. Just
get rid of the field and use "parsed" instead.
2018-04-15 21:03:49 +03:00
sergey.dobrodey 36161f0456 demux_lavf: skip demuxer hack iteration if hacks are disabled 2018-04-12 02:10:46 +03:00
Jan Ekström c33faee6ba demux_mkv: add V_AV1 identifier for AV1
Quickly tested by a person who had FFmpeg linked with libaom.
Seems as simple as the VP9 mappings, where there is no extradata/
initialization data off-band, and just stuff in the packets
themselves.

Do note that the AV1 video format itself at this point is still
not frozen, so what you might produce one day might not be
decodable the following day.
2018-04-08 13:53:29 -07:00
wm4 7d10728aaa demux, stream: ignore packets and errors on forced exit
When this happens, network calls are forcibly aborted (more or less),
but demuxers might keep going, as most of them do not check for forced
exits properly. This can possibly lead to broken packets being added.
Also do not attempt to read more packets in this situation.

Also do not print a stream open failed message if opening was aborted
anyway.
2018-03-26 19:47:07 +02:00
Aman Gupta 4961682f1e demux: fix comment typo 2018-03-11 22:13:12 -07:00
wm4 5f41fbb6d9 demux: correctly report buffered size as 0 if there are no packets
Since the demuxer cache addition, ds->queue->head can actually be set to
non-NULL, but the decoder can still be at EOF (with no packets to come).
This made it report an unknown buffered size, instead of 0. Fix this by
checking the decoder part of the packet queue instead.

Probably doesn't matter much, but fixes an annoying "???" on the CLI
status line in some situations.
2018-03-08 17:12:32 -08:00
Philip Langdale f0223e1b83 tv: Recognise v4l2 'JPEG' fourcc
Naturally, there's more than one fourcc that indicates an mjpeg
stream.

I have a particular ancient webcam here (Logitech QuickCam Messanger)
that only supports the single 'JPEG' format, but there are other
devices out there which support both 'JPEG' and 'MJPG' with no visible
differences, and others where the streams are slightly different.

Regardless of those details, it remains correct to treat 'JPEG'
the same as 'MJPG' from a stream consumption perspective.
2018-03-04 16:28:24 -08:00
wm4 0200a71e2f demux_lavf: add some hacks for SDP
Just the usual guess-what-opaque-ffmpeg-thing-supports.

See #5550. It looks like we can reduce packet drop by having the cache
enabled automatically.
2018-03-03 02:38:01 +02:00
wm4 16eca7139a demux_lavf: add --demuxer-lavf-probe-info=nostreams
Another attempt to try to make it behave in certain situations.
2018-03-03 02:38:01 +02:00
wm4 16d033814c demux: move some code to a separate function
No functional changes.
2018-03-03 02:38:01 +02:00
wm4 e4cb6fd0fd demux: improve audio tag merging for OGG files
It's a mess: mp3 files have user tags as global metadata (because the
id3v2 tag is global and there is only 1 stream), while OGG files have it
per-track (because it's per-stream on the lowest level). mpv needs to
try to make something nice out of the mess.

It did so by trying to detect audio-only OGG files, and then copying the
per-stream metadata to the global metadata. Make the heuristic for
detecting this slightly more clever, so it works for files with extra,
unrelated streams, like the awful libavformat cover art hack.

Fixes #5577.
2018-03-03 02:38:01 +02:00
wm4 14c2f20bff demux_lavf: don't mess up in streams with unknown size and init segment
The return value of stream_get_size() will be -1 if it fails. We
shouldn't mess up this value if a mp4 init segment is used.
2018-03-03 02:38:01 +02:00
wm4 6f27a165a8 demux_mkv: enable libavcodec parser for eac3
It appears some (or all) mkv files with EAC3 are muxed in a way that
breaks FFmpeg's spdifenc. I suspect it's because either dependent
substream packets are localted in their own packets, or the reverse. Or
possibly this is case where the muxer did not respect packet boundaries
at all. Enabling the EAC3 parser seems to fix this anyway, because why
waste your precious time on retarded Dolby bullshit technology? (Which
idiot came up with this shitty substream garbage?)

Observed with dolby_digital_plus_channel_check_lossless-DWEU.mkv.

Fixes #5578.
2018-03-03 02:38:01 +02:00
wm4 9f802d134b demux_edl: fix undefined behavior if mp4 init segment is not provided
param_names[n] is only valid for n<nparam.
2018-03-03 02:38:01 +02:00
wm4 706bb1d0c7 Fix recent FFmpeg deprecations
This includes codec/muxer/demuxer iteration (different iteration
function, registration functions deprecated), and the renaming of
AVFormatContext.filename to url (plus making it a malloced string).

Libav doesn't have the new API yet, so it will break. I hope they will
add the new APIs too.
2018-02-13 17:45:29 -08:00
wm4 e167812406 demux: lower demuxer cache default sizes
Reduce backward/forward from 400MB/400MB to 50MB/150MB. Too many
complaints about high memory usage.

Note that external tracks (like ytdl DASH with external audio tracks)
will double the amounts, because an external track uses its own demuxer
and cache.
2018-02-13 17:45:29 -08:00
wm4 a9f97b26d8 Revert "demux_mkv: remove remaining GPL code"
This reverts commit b7f90be567.

The author agreed to the relicensing now (if that code is affected by
the original copyright at all - that was the only line possibly left of
it).
2018-01-31 03:54:59 +01:00
wm4 7f3c7100d5 cue: strip quotes and leading whitespace from tags
If tags like TITLE have the whole parameter in " quotes, strip them.
Also remove the leading whitespace, since even with a single space it
was always included.

Fixes #5462.
2018-01-30 14:01:15 +01:00
wm4 6d36fad83c video: make decoder wrapper a filter
Move dec_video.c to filters/f_decoder_wrapper.c. It essentially becomes
a source filter. vd.h mostly disappears, because mp_filter takes care of
the dataflow, but its remains are in struct mp_decoder_fns.

One goal is to simplify dataflow by letting the filter framework handle
it (or more accurately, using its conventions). One result is that the
decode calls disappear from video.c, because we simply connect the
decoder wrapper and the filter chain with mp_pin_connect().

Another goal is to eventually remove the code duplication between the
audio and video paths for this. This commit prepares for this by trying
to make f_decoder_wrapper.c extensible, so it can be used for audio as
well later.

Decoder framedropping changes a bit. It doesn't seem to be worse than
before, and it's an obscure feature, so I'm content with its new state.
Some special code that was apparently meant to avoid dropping too many
frames in a row is removed, though.

I'm not sure how the source code tree should be organized. For one,
video/decode/vd_lavc.c is the only file in its directory, which is a bit
annoying.
2018-01-30 03:10:27 -08:00
wm4 eaced0ebb0 demux: add a per stream wakeup callback
This is supposed to help making data flow easier and wakeup handling
more efficient. Once that change is done, reading a packet on any
stream won't have to wakeup and poll all decoders (which helps reducing
the mess even if all decoders are on the same thread).

This also improves the accuracy of wakeups by tracking better whether
a wakeup is needed.
2018-01-30 03:10:27 -08:00
wm4 20cc22437e demux_lavf: work around another aspect of libavformat garbage API
AV_DISPOSITION_ATTACHED_PIC usually means the video track isn't real,
and merely reflects the presence of an embedded image in tag data (such
as ID3v2 tags), with some inconsistent hack to make libavformat return
it as video packet once.

Except it doesn't mean that. It can be randomly set on other streams
that do sort of behave like video streams, such as chapter thumbnail
tracks in mp4 files. AV_DISPOSITION_TIMED_THUMBNAILS is set in these
cases. In theory, there can supposedly be more such cases, but only the
chapter thumbnail one currently exists. So add it as exception.

This restores displaying these thumbnails as video frames, for better or
worse. (Before, only the first thumbnail was displayed.)
2018-01-26 23:29:42 -08:00
wm4 ef324e1316 demux_lavf: export correct seekability state for HLS live streams
Requires newest FFmpeg git, which has a change that makes the HLS
demuxer set an AVFMTCTX_UNSEEKABLE flag if seeking is not available,
which is the case for HLS live streams. This should make the player
frontend behave pretty well, instead of crapping up irrecoverably.
2018-01-26 23:29:42 -08:00
wm4 11f5713e3b options: add an option type for byte sizes
And use it for 2 demuxer options. It could be used for more options
later. (Though the --cache options can not use this, because they use KB
as base unit.)
2018-01-25 20:18:32 -08:00
wm4 c88ab96a78
video: warn user against FFmpeg's lies
I found that at least for mjpeg streams, FFmpeg will set packet pts/dts
anyway. The mjpeg raw video demuxer (along with some other raw formats)
has a "framerate" demuxer option which defaults to 25, so all mjpeg
streams will be played at 25 FPS by default.

mpv doesn't like this much. If AVFMT_NOTIMESTAMPS is set, it prints a
warning, that might print a bogus FPS value for the assumed framerate.
The code was originally written with the assumption that FFmpeg would
not set pts/dts for such formats, but since it does, the printed
estimated framerate will never be used. --fps will also not be used by
default in this situation.

To make this hopefully less confusing, explicitly state the situation
when the AVFMT_NOTIMESTAMPS flag is set, and give instructions how to
work it around.

Also, remove the warning in dec_video.c. We don't know what FPS it's
going to assume anyway. If there are really no timestamps in the stream,
it will trigger our normal missing pts workaround. Add the assumed FPS
there.

In theory, we could just clear packet timestamps if AVFMT_NOTIMESTAMPS
is set, and make up our own timestamps. That is non-trivial for advanced
video codecs like h264, so I'm not going there. For seeking and
buffering estimation the situation thus remains half-broken.

This is a mitigation for #5419.
2018-01-22 23:48:27 -08:00
wm4 6827901230 ta: introduce talloc_dup() and use it in some places
It was actually already implemented as ta_dup_ptrtype(), but that seems
like a clunky name. Also we still use the talloc_ names throughout the
source, and I'd rather use an old name instead of a mixing inconsistent
naming conventions.
2018-01-18 01:42:36 -08:00
wm4 4d87c700e0
demux: reword an outdated comment 2018-01-18 01:25:54 -08:00
wm4 082029f850
player: redo hack for video keyframe seeks with external audio
If you play a video with an external audio track, and do backwards
keyframe seeks, then audio can be missing. This is because a backwards
seek can end up way before the seek target (this is just how this seek
mode works). The audio file will be seeked at the correct seek target
(since audio usually has a much higher seek granularity), which results
in silence being played until the video reaches the originally intended
seek target.

There was a hack in audio.c to deal with this. Replace it with a
different hack. The new hack probably works about as well as the old
hack, except it doesn't add weird crap to the audio resync path (which
is some of the worst code here, so this is some nice preparation for
rewriting it). As a more practical advantage, it doesn't discard the
audio demuxer packet cache. The old code did, which probably ruined
seeking in youtube DASH streams.

A non-hacky solution would be handling external files in the demuxer
layer. Then chaining the seeks would be pretty easy. But we're pretty
far from that, because it would either require intrusive changes to the
demuxer layer, or wouldn't be flexible enough to load/unload external
files at runtime. Maybe later.
2018-01-18 01:25:53 -08:00
sfan5 e2a176ede2 demux_lavf: add required format hacks for DASH 2018-01-15 12:37:32 +01:00
wm4 7816a61609 demux: include beginning of stream state in cached seekable range
Similar to 1eec7d2315, but for the beginning of the stream (named BOF in
this commit).

We can know this only if demuxing actually started from the beginning.
If there is a seek to the beginning (even if you use --start=-1000), we
don't know in general whether the demuxer truly returns the start of the
file. We could probably make a heuristic with assuming that this is what
happens if the seek target is before the start time or so, but this is
not included in this commit.
2018-01-10 22:32:37 -08:00
wm4 c0cc145069 demux: fight libavformat cover art hack harder
libavformat's cover art hack (aka attached pictures) breaks the ability
of the demuxer cache to keep multiple seek ranges. This happens because
the cover art packet has neither position nor timestamp, and libavformat
gives us the packet even though we intended to drop it.

The cover art hack works by adding the cover art packet to the read
packet stream once when demuxing starts (or after seeks). mpv treats
cover art in a similar way internally, but we have to compensate for
libavformat's shortcomings, and add the cover art packet ourselves when
we need it. So we don't want libavformat to return the packet.

We normally prevent this in demux_lavc.c/select_tracks() and explicitly
disable cover art streams. (We add it in dequeue_packet() instead.) But
libavformat will actually add the cover art packet even if we disable
the cover art stream, because it adds it at initialization time, and
does not bother to check again in av_read_frame() (apparently). The
packet is actually read, and upsets the demuxer cache logic. In
addition, this also means we probably decoded the cover art picture
twice in some situations.

Fix this by explicitly checking/discarding this in yet another place.

(Screw this hack...)
2018-01-10 22:32:37 -08:00
wm4 4a11c28237 demux: add missing seekpoint when cached ranges are joined
The impact was that you couldn't exactly seek to the join point with a
keyframe seek, even though there was a keyframe. This commit fixes it by
preserving the necessary metadata that got lost on cached range joining.

This is so absurdly obscure that it gets a longer code comment.
2018-01-10 22:32:37 -08:00
wm4 b71c8251b0 demux: silence pointless/confusing warning
This warning was printed when the demuxer cache tried to join two
adjacent seek ranges, but failed if the last keyframe in the second
range was within the (overlapping) first range. This is a weird corner
case which to support probably would not be worth it.

So this code just printed a warning and discarded the second range. As
it turns out, this can happen relatively often if you seek a lot, and
the seek ranges are very tiny (such as consisting of only 1 keyframe).
Dropping the second range in these cases is OK and probably cheaper than
trying to actually join them. Change the warning to verbose level.

(It seems this could actually be "supported", because if keyframe_latest
is not set, there will be no other keyframes, so it could just be unset,
with the exception that q1->keyframe_latest in the code below must not
be overwritten. But still, too much trouble for a special case that
likely does not matter, and it would have to be tested too.)
2018-01-07 05:03:15 -08:00
wm4 b1a11191fd demux_null: mark as seekable
No reason not to, and enables some strange constructions with
--external-file (although the result is not too smooth for certain
reasons).
2018-01-06 14:42:22 -08:00
wm4 1eec7d2315 demux: include EOF state in cached seekable range
This means if the user tries to seek past EOF, and we know EOF was seen
already, then use a cached seek, instead of triggering a low level seek.

This requires some annoying tracking, but seems pretty simple otherwise.

One advantage of doing this is that if the user tries to do this kind of
seek, there's no unnecessary waiting for a reaction by network (and in
most cases, redundant downloading of data just to discard it again).

Another is that this avoids creating overlapping seek ranges: previously, the
low level seek would naturally create a new range. Then it would read and add
data from the end of the stream due to the low level demuxer not being able to
seek to the target and selecting the last seek point before the end of the
stream. Consequently, this new range would overlap with the previous cached
range. But since the cache joining code is written such that you join the
current range with the _next_ range (instead of the previous as it would be
needed in this case), the overlapping ranges were left alone, until seeking back
to the previous range. That was ugly, sort of harmless, and could happen in
other cases, but this avoidable case was pretty easy to trigger.
2018-01-05 18:34:29 -08:00
wm4 8e1390e734 demux: export some debugging fields about low level demuxer behavior
Export them as explicitly undocumented debugging fields for the
"demuxer-cache-state" property.

Should be somewhat helpful to debug "wtf is the demuxer" doing
situations better, especially when seeking. It also becomes visible how
long the demuxer is blocked on an "old" seek when you keep seeking while
the first seek hasn't finished.
2018-01-05 18:34:29 -08:00
wm4 95dce50347 demux: fix crash due to incorrect seek range accounting
update_seek_ranges() has some special code that attempts to correctly
adjust seek ranges for subtitle tracks. (Subtitle are a nightmare for
seek ranges, because they are sparse, so using the packet list is not
enough to reliably determine the valid cached range.)

This had code like this inside the modified if statement:

  range->seek_start = MP_PTS_MAX(range->seek_start, <something>);

If seek_start is NOPTS, then seek_start will be set to <something>,
breaking some other code that checks seek_start for NOPTS to see if it's
empty. Fix this by explicitly checking whether seek_start is NOPTS
before adjusting it.

The crash happened in prune_old_packets() because the range was marked
as non-empty, yet there was no packet in it to prune. This was with
files with muxed subtitles, when seeking back to the start. This should
not happen anymore with the change. Also add an assert() to
check_queue_consistency() that checks for this specific case.

There's still some mess. In theory, subtitle tracks could be completely
empty, yet their seek range would span the entire file. Seek range
tracking of subtitle files is slightly broken (even before this change).
Some of this should probably be revisited later, including not just
using seek_start to determine whether a seek range should be pruned due
to being empty.
2018-01-05 18:34:29 -08:00
wm4 ff506c1e49 demux_mkv: fix x264 hack if video track uses header compression
The x264 hack requires reading the first video packet, which in turn we
handle with a hack in demux_mkv.c to get the packet without having to
add special crap to demux.c. Another useless MKV feature (which they
enabled by default at one point and which caused many demuxers to break
completely, only to disable it again when it was too late) conflicts
with this, because we actually pass a block as packet contents, instead
of after "decompression".

Fix this by calling demux_mkv_decode().
2017-12-30 00:37:58 -07:00
wm4 5e50fe3049 demux_mkv: add hack to pass along x264 version to decoder
This fixes when resuming certain broken h264 files encoded by x264. See
FFmpeg commit 840b41b2a643fc8f0617c0370125a19c02c6b586 about the x264
bug itself.

Normally, the unregistered user data SEI (that contains the x264 version
string) is informational only. But libavcodec uses it to workaround a
x264 bug, which was recently fixed in both libavcodec and x264. The fact
that both encoder and decoder were buggy is the reason that it was not
found earlier, and there are apparently a lot of files around created by
the broken decoder. If libavcodec sees the SEI, this bug can be worked
around by using the old behavior.

If you resume a file with mpv (i.e. seeking when the file loads),
libavcodec never sees the first video packet. Consequently it has to
assume the file is not broken, and never applies the workaround,
resulting in garbage being played.

Fix this by always feeding the first video packet to the decoder on
init, and then flushing the codec (to avoid that an unwanted image is
output). Flushing the codec does not remove info such as the x264
version. We also abuse the fact that the first avcodec_send_packet()
always pushes the frame into the decoder (so we don't have to trigger
the decoder by requsting an output frame).
2017-12-28 00:59:22 -07:00
wm4 f6a582e0b2 demux_mkv: maintain a small packet read queue
This is less of a mess than the single-item queue in tmp_block, and also
might help us in the future.
2017-12-28 00:59:22 -07:00
wm4 29af787217 player: update duration based on highest timestamp demuxed
This will help with things like livestreams.

As a minor detail, subtitles are excluded, because they sometimes have
"unused" events after video and audio ends. To avoid this annoying
corner case, just ignore them.
2017-12-24 21:49:12 +01:00
wm4 c12d897a3a player: allow seeking in cached parts of unseekable streams
Before this change and before the seekable stream cache became a thing,
we could possibly seek using the stream cache. But we couldn't know
whether the seek would succeed. We knew the available byte range, but
could in general not tell whether a demuxer would stay within the range
when trying to seek to a specific time position. We preferred to have
safe defaults, so seeking in streams that were detected as unseekable
were not honored. We allowed overriding this via --force-seekable=yes,
in which case it depended on your luck whether the seek would work, or
the player crapped its pants.

With the demuxer packet cache, we can tell exactly whether a seek will
work (at least if there's only 1 seek range). We can just let seeks go
through. Everything to allow this is already in place, and this commit
just moves around some minor things.

Note that the demux_seek() return value was not used before, because low
level (i.e. network level) seeks are usually asynchronous, and if they
fail, the state is pretty much undefined. We simply repurpose the return
value to signal whether cache seeking worked. If it didn't, we can just
resume playback normally, because demuxing continues unaffected, and no
decoder are reset.

This should be particularly helpful to people who for some reason stream
data into stdin via streamlink and such.
2017-12-24 21:45:12 +01:00
wm4 30686dcec3 demux_mkv: fix off by one error
Caused by the relatively recent change to packet parsing. This time it
was probably triggered by lace type 0, which reduces the byte length of
a 0 sized packet to 3 (timestamp + flag) instead of 4 (lace count for
other lace types). The thing about laces is just my guess why it worked
for other 0 sized packets, though.

Also remove the redundant and now incorrect check below.

Fixes #5271.
2017-12-23 14:07:21 -07:00
wm4 2c3a172ef1 demux: note refresh state separately in debug output
This log line tells us why the demuxer is trying to read more, which us
useful when debugging queue overflows. Probably barely useful, but I
think keeping that flag separately also makes the code slightly easier
to understand.
2017-12-23 00:32:59 +01:00
wm4 382a8ac0b0 demux: bump the demuxer cache readahead duration
Set it to 10 hours, which is practically unlimited. (Avoiding use of
"inf", since that might interact strangely with the option parser and
such.)
2017-12-23 00:32:59 +01:00
wm4 cc8759a855 demux: always discard cached packets on track switches
This fixes weird behavior in the following case:

- open a file
- make sure the max. demuxer forward cache is smaller than the
  file's video track
- make sure the max. readahead duration is larger than the file's
  duration
- disable the audio track
- seek to the beginning of the file
- once the cache has filled enable the audio track
- a queue overflow warning should appear
(- looking at the seek ranges is also interesting)

The queue overflow warning happens because the packed queue for the
video track will use up the full quota set by --demuxer-max-bytes. When
the audio track is enabled, reading an audio packet would technically
overflow the packet cache by the size of whatever packet is read next.

This means the demuxer signals EOF to the decoder, and once playback has
consumed enough video packets so that audio packets can be read again,
the decoder resumes from EOF. This interacts badly with A/V
synchronization and the whole thing can randomly crap itself until audio
has fully recovered.

We didn't care about this so far, but we want to raise the readahead
duration to something very high, so that the demuxer cache is fully
used. This means this case can be hit quite quickly by switching audio
or subtitle tracks, and is not really an obscure corner case anymore.

Fix this by always losing all cache. Since the cache can't be used
anyway until the newly selected track has been read, this is not much of
a disadvantage. The only thing that could be brought up is that
unselecting the track again could resume operation normally. (Maybe this
would be useful if network died completely without chance of recovery.
Then you could watch the already buffered video anyway by deselecting
the audio track again.) But given the headaches, this seems like the
better solution.

Unfortunately this requires adding new new strange fields and strangely
fragmenting state management functions again. I'm sure whoever works on
this in the future will hate me. Currently it seems like the lesser
evil, and much simpler and robust than the other potential solutions.

In case this needs to be revisited, here is a reminder for readers from
the future what alternative solutions were considered, without those
disadvantages:

A first attempted solution allowed the demuxer to buffer some additional
packets on track switching. This would allow it to read enough data to
feed the decoder at least. But it was still awkward, as it didn't allow
the demuxer to continue prefetching the newly selected track. It also
barely worked, because you could make the forward buffer "over full" by
seeking back with seekable cache enabled, and then it couldn't read
packets anyway.

As alternative solution, we could always demux and cache all tracks,
even if they're deselected. This would also not require a network-level
seek for the "refresh" logic (it's the thing that lets the video decoder
continue as if nothing happened, while actually seeking back in the
stream to get the missing audio packets, in the case of enabling a
previously disabled audio track). But it would also possibly waste
network and memory resources, depending on what the user actually wants.

A second solution would just account the queue sizes for each stream
separately. We could freely fill up the audio packet queue, even if the
video queue is full. Since the demuxer API returns interleaved packets
and doesn't let you predict which packet type comes next, this is not as
simple as it sounds, but it'd probably tie in nicely with the "refresh"
logic.

A third solution would be removing buffered video packets from the end
of the packet queue. Since the "refresh" logic gets these anyway, there
is no reason to keep them if they prevent the audio packet queue from
catching up with the video one. But this would require additional logic,
would interact badly with a bunch of other corner cases. And as far as
the code goes, it's rather complex, because all the logic is written
with FIFO behavior in mind (including the fact that the packet queue is
a singly linked list with no backwards links, making removal from the
end harder).
2017-12-23 00:32:59 +01:00
wm4 b782c90180 demux_timeline: disable pointless packet cache for sub-demuxers
It seems like there's nothing stopping from sub-demuxers from keeping
packets in the cache, even if it's completely pointless. The top-most
demuxer (demux_timeline) already takes care of caching, so sub-demuxers
only waste space and time with this.

Add a function that can disable the packet cache even at runtime and
after packets are read. (It's not clear whether it really can happen
that packets are read before demux_timeline gets the sub-demuxers, but
there's no reason to make it too fragile.) Call it on all sub-demuxers.

For this to work, it seems we have to move the code for setting the
seekable_cache flag to before demux_timeline is potentially initialized,
because otherwise the cache would be reenabled if the demuxer triggering
timeline support is a timeline segment itself (e.g. ordered chapters).
2017-12-10 06:37:49 +02:00
wm4 451a502c1d demux: fix accounting for seekable ranges on track switches
This fixes missing audio when cycling through audio tracks with anything
that uses nested demuxers, such as demux_timeline, which us used for
EDL, --merge-files, ordered chapters, and youtube-dl pseudo DASH
support. When this bug happened, reenabling an audio track would lead to
silence for the duration of the readahead amount.

The underlying reason is the incorrectly updated buffered range on track
switch. It accidentally included the amount covered by the deselected
stream. But the cause of the observed effect was that demux_timeline
issued a refresh seek to the underlying slave demuxer, which in turn
thought it could do a cache seek, because the seek range still included
everything.

update_stream_selection_state() calls update_seek_ranges() to update the
seek ranges after a track switch. When reenabling the track, ds->eager
was set to false during update_seek_ranges(), which made it think the
stream was sparse, and thus it didn't restrict the current seek range
(making later code think everything was buffered). Fix this by moving
some code, so we first update the ds->eager flag, then the seek ranges.

Also verbose log the low level stream selection calls.
2017-12-10 06:37:49 +02:00
Nicolas F 744b67d9e5 Fix various typos in log messages 2017-12-03 21:24:18 +01:00
wm4 efbb919997 player: minor fix/simplification of OSD time/duration handling
Always display the duration as "unknown" if the duration is known. Also
fix that at least demux_lavf reported unknown duration as 0 (fix by
setting the default to unknown in demux.c).

Remove the dumb _u formatter function, and use a different approach to
avoiding displaying "unknown" as playback time on playback start (set
last_seek_pts for that).
2017-11-24 13:58:57 +01:00
wm4 cd6f964b56 demux_mkv: remove unnecessary parsing for vp9
We can finally get rid of this crap.

Depends on a ffmpeg-mpv change. Always worked with Libav (ever since
they fixed it properly).
2017-11-17 14:18:57 +01:00
wm4 41243e7c4f demux_lavf: always give libavformat the filename when probing
This gives the filename or URL to the libavformat probing logic, which
might use the file extension as a "help" to decide which format the file
is. This helps with mp3 files that have large id3v2 tags and prevents
the idiotic ffmpeg probing logic to think that a mp3 file is amr.

(What we really want is knowing whether we _really_ need to feed more
data to libavformat to detect the format. And without having to pre-read
excessive amounts of data for relatively normal streams.)
2017-11-12 19:38:45 +01:00
wm4 987291d042 demux_playlist: support .url files
Requested. Not tested due to lack of real samples. Fixes #5107.
2017-11-12 15:51:48 +01:00
wm4 871a8a316a demux: avoid queue overflow warning when joining two ranges
If the backbuffer is much larger than the forward buffer, and if you
join a small range with a large range (larger than the forward buffer),
then the seek issues to the end of the range after joining will overflow
the queue.

Normally, read_more will be false when the forward buffer is full, but
the resume seek after joining will set need_refresh to true, which
forces more reading and thus triggers the overfloe warning.

Attempt to fix this by not setting read_more to true on refresh seeks.
Set prefetch_more instead. read_more will still be set if an A/V stream
has no data.

This doesn't help with the following problems related to using refresh
seeks for track switching:

- If the forward buffer is full, then enabling another track will
  obviously immediately overflow the queue, and immediately lead to
  marking the new track as having no more data (i.e. EOF). We could cut
  down the forward buffer or so, but there's no simple way to implement
  it. Another possibility would be dropping all buffers and trying to
  resume again, but this would likely be complex as well.
- Subtitle tracks will not even show a warning (because they are sparse,
  and we have no way of telling whether a packet is missing, or there's
  just no packet near the current position). Before this commit,
  enabling an empty subtitle track would probably have overflown the
  queue, because ds->refreshing was never set to true. Possibly this
  could be solved by determining a demuxer read position, which would
  reflect until which PTS all subtitle packets should have been demuxed.

The forward buffer limit was intended as a last safeguard to avoid
excessive memory usage against badly interleaved files or decoders going
crazy (up to reading the whole into memory and OOM'ing the user's
system). It's not good at all to limit prefetch. Possibly solutions
include having another smaller limit for prefetch, or maybe having only
a total buffer limit, and discarding back buffer if more data has to be
read. The current solution is making the forward buffer larger than the
forward duration (--cache-secs) would require, but of course this
depends on the stream's bitrate.
2017-11-11 06:23:50 +01:00
wm4 8e50dc1b4d demux: export demuxer cache sizes in bytes
Plus sort of document them, together with the already existing
undocumented fields. (This is mostly for debugging, so use is
discouraged.)
2017-11-10 16:43:18 +01:00
wm4 1b0dc7d169 demux: use seekable cache for network by default, bump prefetch limit
The option for enabling it has now an "auto" choice, which is the
default, and which will enable it if the media is thought to be via
network or if the stream cache is enabled (same logic as --cache-secs).

Also bump the --cache-secs default from 10 to 120.
2017-11-10 16:30:43 +01:00
wm4 618b8a33e5 demux_mkv: fix potential uninitialized variable read 2017-11-10 12:49:53 +01:00
wm4 6bcdcaeeea demux: set default back buffer to some high value
Some back buffer is required to make the immediate forward range
seekable. This is because the back buffer limit is strictly enforced.
Just set a rather high back buffer by default. It's not use if
--demuxer-seekable-cache is disabled, so this is without risk.
2017-11-10 12:37:19 +01:00
wm4 b0de1ac36c demux: limit number of seek ranges to a static maximum
Limit the number of cached ranges to MAX_SEEK_RANGES, which is the same
number of maximally exported seek ranges. It makes no sense to keep
them, as the user won't see them anyway. Remove the smallest ones to
enforce the limit if the number grows too high.
2017-11-10 12:32:40 +01:00
wm4 c8bb78bad8 demux: speed up cache seeking with a coarse index
Helps a little bit, I guess. But in general, t(h)rashing the cache kills
us anyway.

This has a fixed number of index entries. Entries are added/removed as
packets go through the packet queue. Only keyframes after index_distance
seconds are added. If there are too many keyframe packets, the existing
index is reduced by half, and index_distance is doubled. This should
provide somewhat even spacing between the entries.
2017-11-10 12:17:34 +01:00
wm4 2485b899c3 demux: avoid wasting time by stopping packet search as early as possible
The packet queue is sorted, so we can stop the search if we have found a
packet, and the next packet in the queue has a higher PTS than the seek
PTS (for the sake of SEEK_FORWARD, we still consider the first packet
with a higher PTS).

Also, as a mostly cosmetic change, but which might be "faster", check
target for NULL, instead of target_diff for a magic float value.
2017-11-10 12:11:33 +01:00
wm4 968a24772e demux: simplify remove_packet() function
Turns out this is only ever used to remove the head element anyway.
2017-11-10 11:35:19 +01:00
wm4 65d36013dd demux: fix failure to join ranges with subtitles in some cases
Subtitle streams are sparse, and no overlap is required to correctly
join two cached ranges. This was not correctly handled iff the two
ranges had different subtitle packets close to the join point.
2017-11-10 11:06:07 +01:00
wm4 4681b4b28b demux: reverse which range is reused when joining them
Which one to use doesn't really matter, but reusing the first one will
probably be slightly more convenient later on.
2017-11-10 10:46:54 +01:00
wm4 f123cc4c9b demux: fix a race condition with async seeking
demux_add_packet() must completely ignore any packets that are added
while a queued seek is not initiated yet.

The main issue is that after setting in->seeking==true, the central lock
is released, and it can take "a while" until it's reacquired on the
demux thread and the seek is actually initiated. During that time,
packets could be read and added, that have nothing to do with the new
state.
2017-11-10 10:23:49 +01:00
wm4 d3bc93cf2e demux: get rid of an unnecessary field 2017-11-10 10:15:37 +01:00
wm4 ed1af99727 demux: attempt to accurately reflect seek range with muxed subtitles
If subtitles are part of the stream, determining the seekable range
becomes harder. Subtitles are sparse, and can have packets in irregular
intervals, or even completely lack packets. The usual logic of computing
the seek range by the min/max packet timestamps fails.

Solve this by making the only assumption we can make: subtitle packets
are implicitly demuxed along with other packets. We also assume perfect
interleaving for this, but you really can't do anything with sparse
packets that makes sense without this assumption.

One special case is if we prune sparse packets within the current
seekable range. Obviously this should limit the seekable range to after
the pruned packet.
2017-11-10 08:57:37 +01:00
wm4 7c1e7468e6 demux: reduce indentation for two functions
Remove the single-exit, that added a huge if statement containing
everything, just for some corner case.
2017-11-10 04:41:56 +01:00
wm4 6493ef2e34 demux: some minor mostly cosmetics
None of these change functionality in any way (although the log level
changes obviously change the terminal output).
2017-11-10 04:36:50 +01:00
wm4 a0b6f805f9 demux: simplify a function
update_stream_selection_state() doesn't need all these arguments. Not
sure what I was thinking here.
2017-11-10 04:08:15 +01:00
wm4 8c5ef33044 demux: change how refreshes on track switching are handled
Instead of weirdly deciding this on every packet read and having the
code far away from where it's actually needed, just run it where it's
actually needed.
2017-11-10 03:56:24 +01:00
wm4 25ed7ff0c8 demux: get rid of weird backwards loop
A typical idiom for calling functions that remove something from the
array being iterated, but it's not needed here. I have no idea why this
was ever done.
2017-11-10 03:26:40 +01:00
wm4 9c330b53e3 demux: avoid broken readahead when joining ranges
Setting ds->refreshing for unselected streams could lead to a
nonsensical queue overflow warning, because read_packet() took it as a
reason to continue reading.

Also add some more information to the queue overflow warning (even if
that one doesn't have anything to do with this bug - it was for
unselected streams only).
2017-11-10 03:19:25 +01:00
wm4 c494049e76 demux: reduce difference between threaded and non-threaded mode
This fixes an endless loop with threading disabled, such as for example
when playing a file with an external subtitle file, and seeking to the
beginning. Something will set in->seeking, but the seek is never
executed, which made demux_read_packet() loop endlessly. (External
subtitles will use non-threaded mode for whatever reasons.)

Fix this by by making the unthreaded code to execute the worker thread
body, which reduces the difference in logic.
2017-11-10 02:55:02 +01:00
wm4 935e406d63 demux: support multiple seekable cached ranges
Until now, the demuxer cache was limited to a single range. Extend this
to multiple range. Should be useful for slow network streams.

This commit changes a lot in the internal demuxer cache logic, so
there's a lot of room for bugs and regressions. The logic without
demuxer cache is mostly untouched, but also involved with the code
changes. Or in other words, this commit probably fucks up shit.

There are two things which makes multiple cached ranges rather hard:

1. the need to resume the demuxer at the end of a cached range when
   seeking to it
2. joining two adjacent ranges when the lowe range "grows" into it (and
   resuming the demuxer at the end of the new joined range)

"Resuming" the demuxer means that we perform a low level seek to the end
of a cached range, and properly append new packets to it, without adding
packets multiple times or creating holes due to missing packets.

Since audio and video never line up exactly, there is no clean "cut"
possible, at which you could resume the demuxer cleanly (for 1.) or
which you could use to detect that two ranges are perfectly adjacent
(for 2.). The way how the demuxer interleaves multiple streams is also
unpredictable. Typically you will have to expect that it randomly allows
one of the streams to be ahead by a bit, and so on.

To deal with this, we have heuristics in place to detect when one packet
equals or is "behind" a packet that was demuxed earlier. We reuse the
refresh seek logic (used to "reread" packets into the demuxer cache when
enabling a track), which checks for certain packet invariants.
Currently, it observes whether either the raw packet position, or the
packet DTS is strictly monotonically increasing. If none of them are
true, we discard old ranges when creating a new one.

This heavily depends on the file format and the demuxer behavior. For
example, not all file formats have DTS, and the packet position can be
unset due to libavformat not always setting it (e.g. when parsers are
used).

At the same time, we must deal with all the complicated state used to
track prefetching and seek ranges. In some complicated corner cases, we
just give up and discard other seek ranges, even if the previously
mentioned packet invariants are fulfilled.

To handle joining, we're being particularly dumb, and require a small
overlap to be confident that two ranges join perfectly. (This could be
done incrementally with as little overlap as 1 packet, but corner cases
would eat us: each stream needs to be joined separately, and the cache
pruning logic could remove overlapping packets for other streams again.)

Another restriction is that switching the cached range will always
trigger an asynchronous low level seek to resume demuxing at the new
range. Some users might find this annoying.

Dealing with interleaved subtitles is not fully handled yet. It will
clamp the seekable range to where subtitle packets are.
2017-11-09 10:23:57 +01:00
wm4 4ef0887f7b demux: explicitly discard 0 sized packets
libavcodec can't deal with them, because its API doesn't distinguish
between 0 sized packets and sending EOF. As such, keeping them doesn't
do any good, ever. This actually fixes some obscure mkv sample (see
previous commit).
2017-11-06 17:13:42 +01:00
wm4 e598b19dad demux_mkv: allow 0 sized packets
Fixes some obscure sample that uses fixed size laces with 0-sized lace
size. Some broken shit. (Maybe the decoder wouldn't care about these
packets, but the demuxer attempted to resync after these packet reading
errors, even though they were perfectly recoverable. But I don't care
enough about this.)

Sample link: https://samples.ffmpeg.org/Matroska/switzler084d_dl.mkv
2017-11-06 17:12:58 +01:00
wm4 7334d93b30 demux: slightly simplify pruning
We can compute the overhead size easily now - no need for awkward
incremental updates to cached values on top of it.
2017-11-06 17:11:31 +01:00
wm4 9e1fbffc37 demux_mkv: rewrite packet reading to avoid 1 memcpy()
This directly reads individual mkv sub-packets (block laces) into a
dedicated AVBufferRefs, which can be directly used for creating packets
without a additional copy of the packet data. This also means we switch
parsing of block header fields and lacing metadata to read directly from
the stream, instead of a memory buffer.

This could have been much easier if libavcodec didn't require padding
the packet data with zero bytes. We could just have each packet
reference a slice of the block data. But as it is, the only way to get
padding without a copy is to read the laces into individually allocated
(and padded) memory block, which required a larger rewrite.

This probably makes recovering from broken mkv files slightly worse if
the transport is unseekable. We just read, and then check if we've
overread. But I think that shouldn't be a real concern.

No actual measureable performance change. Potential for some
regressions, as this is quite intrusive, and touches weird obscure shit
like mkv lacing. Still keeping it because I like how it removes some
redundant EBML parsing functions.
2017-11-05 18:13:34 +01:00
wm4 8aa1db3b17 demux: refactoring in preparation for multiple seek range support
This adds a bunch of stuff (mostly unused or redundant) as preparation
for supporting multiple seek ranges. Actual support is probably still
far away.

One change that messes deeper with the actual code is that we account
for total buffered bytes instead of just the backwards bytes now. This
way, prune_old_packets() doesn't have to iterate over all seek ranges to
determine whether something needs pruning.
2017-11-04 23:45:21 +01:00
wm4 10d0963d85 demux: improve and optimize cache pruning and seek range determination
The main purpose of this commit is avoiding any hidden O(n^2) algorithms
in the code for pruning the demuxer cache, and for determining the
seekable boundaries of the cache. The old code could loop over the whole
packet queue on every packet pruned in certain corner cases.

There are two ways how to reach the goal:
 1) commit a cardinal sin
 2) do everything incrementally

The cardinal sin is adding an extra field to demux_packet, which caches
the determined seekable range for a keyframe range. demux_packet is a
rather general data structure and thus shouldn't have any fields that
are not inherent to its use, and are only needed as an implementation
detail of code using it. But what are you gonna do, sue me?

In the future, demux.c might have its own packet struct though. Then the
other existing cardinal sin (the "next" field, from MPlayer times) could
be removed as well.

This commit also changes slightly how the seek end is determined. There
is a note on the manpage in case anyone finds the new behavior
confusing. It's somewhat cleaner and  might be needed for supporting
multiple ranges (although that's unclear).
2017-11-04 23:18:42 +01:00
wm4 6e998be7be demux: reduce overhead when searching over keyframe ranges
The demuxer cache seeking mechanism looks at keyframe ranges to
determine the earlierst PTS of a packet. Instead of looping over all
packets twice (once to find the next keyframe, a second time to find the
seek PTS), do it in one go.

For that basically turn recompute_keyframe_target_pts() into an
iteration functionn. Functionality should be unchanged with this commit.
2017-11-04 18:18:42 +01:00
wm4 104e18214c demux: avoid excessive readahead after cache seek
The base_ts field is used to guess the decoder position, and when set to
NOPTS, it just read ahead arbitrarily. Also demux_add_packet() sets
base_ts to the new timestamp when appending a packet, which would also
make it readahead by a too large amount.

Fix this by setting base_ts after a seek. This assumes that normally, a
cached seek target will always have the timestamp set. This is actually
not quite clear (as it calls recompute_keyframe_target_pts(), which
looks at multiple packets), but maybe it works well enough.
2017-11-04 17:43:22 +01:00
wm4 c1f981f863 demux: make pruning more efficient for unseekable demuxer cache
Don't do any of the extra work related to pruning the backbuffer if
demuxer cache seeking is disabled.

As a small extra, always prune packets with no timestamps immediately,
or queue heads that are not keyframes. (Both of them would be pruned
from the backbuffer by the normal logic anyway.)
2017-11-04 17:32:34 +01:00
wm4 d46c9c2e62 demux: on queue overflow wake up reader thread on EOF only
This seems to make more sense.
2017-11-03 16:36:59 +01:00
wm4 49ae599883 demux: don't show queue overflow warning when merely prefetching
If fulfilling --demuxer-readahead-secs requires more memory than allowed
by --demuxer-max-bytes, the queue obviously overflows. But the warning
is normally only for the case when trying to find the next video or
audio packet fails, and decoding can't continue.

Use a separate variable for determining whether to prefetch, and if the
queue has overflown, skip the message. In fact, skip the EOF setting and
waking up the decoder thread as well, because the EOF flag should not be
(have been) set in this situation, and waking up the reader thread helps
only if the EOF state changed.
2017-11-03 16:36:21 +01:00
wm4 4fca1856e1 demux: don't allow subtitles to mess up buffered time display
In a shit show of subtle corner case interactions, making the demuxer
cache buffer the entire file can display a small buffered time if
subtitles are enabled. The reason is that some subtitle decoders may
read in advance infinitely, i.e. they read the entire subtitle stream.
Then, since the other streams (audio/video) have logically reached EOF,
and the subtitle stream is set to ds->active==true. This will have to be
fixed properly later to account buffering for subtitle-only files
(another corner case) correctly, but for now this is less annoying.
2017-11-03 14:58:13 +01:00
wm4 57248915fa demux: add option to create CC tracks eagerly
We don't hope to auto-detect them at load time, as that would be too
much of a pain - even FFmpeg requires fetching and parsing of video
packets, and exposes the information only via deprecated API.

But there still needs to be a way to select them by default. This is
also needed to get the first CC packet at all (without seeking back).

This commit also attempts to clean up locking a bit, which is a PITA,
but it's better be careful & clean.
2017-11-03 13:55:32 +01:00
Nicolas F e6a68e2330 demux_mkv: add V_SNOW tag to mkv_video_tags
Apparently, and to nobody's surprise, mkv can contain snow. It does
so with the V_SNOW tag. We can now play back snow-inside-mkv in mpv.
2017-11-03 01:03:39 +01:00
wm4 a7f4ecb012 Bump libav* API use
(Not tested on Windows and OSX.)
2017-10-30 20:55:42 +01:00
wm4 2d958dbf2b demux: refactor to export seek ranges
Even though only 1 seek range is supported at the time.

Other than preparation for possibly future features, the main gain is
actually that we finally separate the reporting for the buffering, and
the seek ranges. These can be subtly different, so it's good to have a
clear separation.

This commit also fixes that the ts_reader wasn't rebased to the start
time, which could make the player show "???" for buffered cache amount
in some .ts files and others (especially at the end, when ts_reader
could become higher than ts_max). It also fixes writing the cache-end
field in the demuxer-cache-state property: it checked ts_start against
NOPTS, which makes no sense.

ts_start was never used (except for the bug mentioned above), so get rid
of it completely. This also makes it convenient to move the segment
check for last_ts to the demux_add_packet() function.
2017-10-30 15:28:59 +01:00
Daniel Kucera e9dc4ac86f demux_lavf: return AVERROR_EOF on file end
Signed-off-by: Daniel Kucera <daniel.kucera@gmail.com>
Signed-off-by: wm4 <wm4@nowhere>

Uses different style and different logic from original PR.
2017-10-30 12:42:00 +01:00
wm4 3413fe4dfd demux_mkv: don't probe start time by default
It isn't all that reliable, and improving it would make startup slower
and require more complexity. There isn't even a good reason to do this
(other than semi-broken mkv files), so don't do it. Also see previous
commit.
2017-10-27 18:41:47 +02:00
wm4 ae8b531207 demux_timeline: don't use segments for DASH
Recent regression. Crashes because it sets the segmented flag, without
actually setting the fields required for segmentation.
2017-10-26 00:38:20 +02:00
wm4 ec8cad40f2 demux: better computation of seek start target
Avoids that cache seeking is not possible with files that have audio
frames with no timestamps (such as avi, sometimes mkv sub-packets from
lacing). These would set back_pts (first seekable PTS) to NOPTS, and
thus disable cache seeking completely. Instead, prune such packets until
we find one with timestamps.

One corner case is that the new next good packet might be in the forward
cache. In this case we defer dropping until the next time this code is
run, and the reader position has possibly moved past the drop point.
2017-10-25 16:39:33 +02:00
wm4 d235380cd3 demux: reject cache seeks if parts of the range are unset
In theory, start/ts_min could be set to NOPTS, in which case
"pts < start" for a valid pts would always evaluate to false.

Also remove the redundant "in-cache seek is possible.." message, as
there's always another message when cache seeks are done.
2017-10-25 16:39:33 +02:00
wm4 03a0e8336a demux: fall back to DTS when determining seek target
Fixes AVI in particular, which abuses DTS for reordered PTS. (It's not
really DTS...)
2017-10-25 16:39:33 +02:00
wm4 e6348504b3 demux: disallow seeking if there are streams with no timestamps
The seek range computation ignored streams with no timestamps. For
things like buffer estimation this is OK and wanted, but the seek range
needs to be conservative.
2017-10-25 16:39:33 +02:00
wm4 3d71651523 demux: fix tracking of forward/backward cache size
Which parts of the queue are considered forward or backward cache
depends on ds->reader_header. The packet at ds->reader_head, as well as
all packets following it (via the ->next field) are considered forward.
The fw_packs/fw_bytes/bw_bytes must be updated accordingly.

This broke in demux_add_packet(), when ds->reader_head was _not_ set on
the first packet (or before). This could happen since commit
05ae571241, which can require skipping packets (so they immediately end
up in the backbuffer).
2017-10-25 16:39:33 +02:00
wm4 56d9dafbbb demux: respect timeline boundaries for cache seeks
With the timeline code, a packet at the start or end of a segment can
refer to an invisible frame. So it doesn't extend the seek range, and
the timestamp should be clipped to the actual segment range.

Also restructure recompute_keyframe_target_pts() to be hopefully less
confusing.
2017-10-25 16:39:33 +02:00
wm4 8bf399e02e demux: don't report unknown queue state if no packets were added
Restores some behavior from before the demuxer cache changes, though
affects mostly just OSD display. The unknown queue state is reserved for
streams with missing or messed up timestamps.
2017-10-25 16:39:33 +02:00
wm4 374e3bd83c demux_timeline: trust attached picture flag
Fully fixes behavior of the files mentioned in the previous commit. Will
probably lead to worse behavior if someone tries to fix real video and
cover art tracks, but that's a broken fringe case anyway.
2017-10-25 16:39:33 +02:00
wm4 3d32cb1649 demux: set correct stream index for attached pictures
This fixes .cue files with audio files that contain attached pictures to
some degree. demux_timeline.c just discarded packets with unset index,
so the picture was never fed to the decoder.
2017-10-25 16:39:33 +02:00
James Ross-Gowan 257a2b9646 win32: add more-POSIXy versions of open() and fstat()
Directory-opening never worked on Windows because MSVCRT's open()
doesn't open directories and its fstat() doesn't recognise directory
handles. These are just MSVCRT restrictions, and the Windows API itself
has no problem with opening directories as file objects, so reimplement
mpv's mp_open and mp_stat to use the Windows API directly. This should
fix directory playback.

This also populates the st_dev and st_ino fields of struct stat, so
filesystem loop checking in demux_playlist.c should now work on Windows.

Fixes #4711
2017-10-25 22:37:20 +11:00
wm4 a5b51f75dc demux: get rid of demux_packet.new_segment field
The new_segment field was used to track the decoder data flow handler of
timeline boundaries, which are used for ordered chapters etc. (anything
that sets demuxer_desc.load_timeline). This broke seeking with the
demuxer cache enabled. The demuxer is expected to set the new_segment
field after every seek or segment boundary switch, so the cached packets
basically contained incorrect values for this, and the decoders were not
initialized correctly.

Fix this by getting rid of the flag completely. Let the decoders instead
compare the segment information by content, which is hopefully enough.
(In theory, two segments with same information could perhaps appear in
broken-ish corner cases, or in an attempt to simulate looping, and such.
I preferred the simple solution over others, such as generating unique
and stable segment IDs.)

We still add a "segmented" field to make it explicit whether segments
are used, instead of doing something silly like testing arbitrary other
segment fields for validity.

Cached seeking with timeline stuff is still slightly broken even with
this commit: the seek logic is not aware of the overlap that segments
can have, and the timestamp clamping that needs to be performed in
theory to account for the fact that a packet might contain a frame that
is always clipped off by segment handling. This can be fixed later.
2017-10-24 19:35:55 +02:00
wm4 bb9679d9a3 demux_timeline: change virtual_stream array to array of pointers
Needed for a failed thing, leaving it anyway because it causes no harm
and might be less awkward if struct virtual_stream is possibly extended
anyway in the future.
2017-10-24 19:24:20 +02:00
wm4 05ae571241 demux: fix cached SEEK_FORWARD seeks into end of cached regions/EOF
Although seeking past the cached range will trigger a low level seek, a
seek into the region between cache end and last video key frame would
simply seek to the video key frame. This meant that you could get
"stuck" at the end of the file instead of terminating playback when
trying to seek past the end.

One change is that we fix this by _actually_ allowing SEEK_FORWARD to
seek past the last video keyframe in find_seek_target().

In that case, or otherwise seeking to cache buffer end, it could happen
that we set ds->reader_head=NULL if the seek target is after the current
packet. We allow this, because the end of the cached region is defined
by the existence of "any" packet, not necessarily a key frame. Seeking
there still makes sense, because we know that there is going to be more
packets (or EOF) that satisfy the seek target.

The problem is that just resuming demuxing with reader_head==NULL will
simply return any packets that come its way, even non-keyframe ones.
Some decoders will produce ugly soup in this case. (In practice, this
was not a problem, because seeking at the end of the cached region was
rare before this commit, and also some decoders like h264 will skip
broken frames by default anyway.)

So the other change of this commit is to enable key frame skipping.

As a nasty implementation detail, we use a separate flag, instead of
setting reader_head to the first key frame encounted (reader_head being
NULL can happen after a normal seek or on playback start, and then we
want to mirror the underlying demuxer behavior, for better or worse).

This change is relatively untested, so you get to keep the pieces for
yourself.
2017-10-23 20:55:11 +02:00
wm4 512509705e demux: report buffered duration of 0 during seeking instead of unknown
Looks ugly on the status line and could upset the buffering logic.
2017-10-23 19:36:20 +02:00
wm4 dbd22f43be demux: drop redundant SEEK_BACKWARD flag
Seems like most code dealing with this was for setting it in redundant
cases. Now SEEK_BACKWARD is redundant, and SEEK_FORWARD is the odd one
out.

Also fix that SEEK_FORWARD was not correctly unset in try_seek_cache().

In demux_mkv_seek(), make the arbitrary decision that a video stream is
not required for the subtitle prefetch logic to be active. We might want
subtitles with long duration even with audio only playback, or if the
file is used as external subtitle.
2017-10-23 19:05:39 +02:00
wm4 34676fc94d demux: fix crash with cue/ordered chapter files
If a packet uses segmentation, the codec field must be set. Copying the
codec field was forgotten as an oversight, which is why this just
crashes. This showed up only now, because demux_copy_packet() was not
used before in the main demux path until recently.

Fixes #5027.
2017-10-23 11:31:45 +02:00
wm4 60df01512c command: read the diff if you want to know 2017-10-21 21:13:53 +02:00
wm4 633077814e *** empty log message *** 2017-10-21 20:42:40 +02:00
wm4 0004af3e71 demux: replace redundant field with a better redundant field 2017-10-21 20:36:06 +02:00
wm4 719a435d36 demux: add a back buffer and the ability to seek into it
This improves upon the previous commit, and partially rewrites it (and
other code). It does:

- disable the seeking within cache by default, and add an option to
  control it
- mess with the buffer estimation reporting code, which will most likely
  lead to funny regressions even if the new features are not enabled
- add a back buffer to the packet cache
- enhance the seek code so you can seek into the back buffer
- unnecessarily change a bunch of other stuff for no reason
- fuck up everything and vomit ponies and rainbows

This should actually be pretty usable. One thing we should add are some
properties to report the proper buffer state. Then the OSC could show a
nice buffer range. Also configuration of the buffers could be made
simpler. Once this has been tested enough, it can be enabled by default,
and might replace the stream cache's byte ringbuffer.

In addition it may or may not be possible to keep other buffer ranges
when seeking outside of the current range, but that would be much more
complex.
2017-10-21 19:26:33 +02:00
Aman Gupta 83c9f169c4 demux: optimize seeks within readahead cache
If a suitable keyframe cannot be found in each stream's
readahead cache, fallback to a regular seek.
2017-10-21 13:29:37 +02:00
wm4 044af63d98 demux: improvements to previous commits
More the ignore_eof field to the internal demux_stream struct. This is
relatively messy, because the internal struct exists only once the
stream is created, and after that setting the ignore_eof flag is a race
condition. We could bother with adding demux_add_sh_stream() parameters
for this, but let's not. So in theory a tiny race condition is
introduced, which can never be triggered since all demux API functions
are called by the playback thread only anyway.

Fix that ts_offset is accessed without log (this was introduced much
earlier by myself).

Introduce an alternative way of avoiding the annoying EOF reached
messages by not resetting the EOF flags for CC streams when a CC packet
is added. This makes the second commit in the PR which added the
original fix unnecessary.

As another cosmetic change merge the check in cached_demux_control()
into a single if().

In the future, the CC pseudo-stream should probably be replaced with an
entire pseudo-demuxer or such, which would avoid some of the messiness
(or maybe not, we don't know yet).
2017-10-20 22:30:59 +02:00
Aman Gupta f57ff79867 demux: ignore false underrun reporting from eia_608 captions decoder 2017-10-20 22:14:54 +02:00
wm4 b7f90be567 demux_mkv: remove remaining GPL code
Fuck this thing.
2017-10-10 17:35:47 +02:00
wm4 158b69f04c build: switch preliminary LGPL mode from v3 to v2.1
iive agreed to relicense things that are still in mpv to LGPLv2.1. So
change the licenses of the affected files, and rename the configure
switch for LGPL mode to --enable-preliminary-lgpl2.

(The "preliminary" part will probably be removed from the configure
switch soon as well.)

Also player/main.c hasn't had GPL parts since a few commits ago.
2017-10-05 15:57:30 +02:00
wm4 4e5d7cbf21 demux_mkv: replace deprecated av_copy_packet_side_data()
It's deprecated, and av_packet_copy_props() is nearly equivalent. It's
also more widely supported.
2017-10-03 14:45:18 +02:00
wm4 bfa9b62858 build: add preliminary LGPL mode
See "Copyright" file for caveats.

This changes the remaining "almost LGPL" files to LGPL, because we think
that the conditions the author set for these was finally fulfilled.
2017-09-21 13:56:27 +02:00
wm4 028faacff5 video: add metadata handling for spherical video
This adds handling of spherical video metadata: retrieving it from
demux_lavf and demux_mkv, passing it through filters, and adjusting it
with vf_format. This does not include support for rendering this type of
video.

We don't expect we need/want to support the other projection types like
cube maps, so we don't include that for now. They can be added later as
needed.

Also raise the maximum sizes of stringified image params, since they
can get really long.
2017-08-21 14:56:07 +02:00
wm4 79a39aeebd demux_lavf: use partial read for AVIOContext.read_packet
More betterer.
2017-08-17 17:28:01 +02:00
wm4 0e36b77aae demux_mkv: avoid an error message in a corner case
If --demuxer-mkv-probe-start-time=no is used, and a seek is triggered on
start, then cluster_start will be 0, and the packet reading code will
print an error message about not finding valid data. This fixes itself
since it invokes the resync code, but it's still pretty ugly. Avoid this
by always initializing cluster_start.
2017-08-08 15:19:50 +02:00
Jan Ekström 0389852db0 {demux_mf,osdep/io}: disable glob usage when it is not available
This currently is only limited to Android. Its stdlib contains the
things that mpv's POSIX check checks for, but unfortunately not
glob().

This fixes Android compilation broken in 70a70b9da .
2017-08-05 01:51:29 +03:00