Update to MPlayer SVN rev 30134 and FFmpeg SVN rev 20947.
[vaapi:sewalliniusms-mplayer.git] / libmpdemux / demuxer.c
1 /*
2  * DEMUXER v2.5
3  *
4  * This file is part of MPlayer.
5  *
6  * MPlayer is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * MPlayer is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with MPlayer; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25
26 #include <sys/types.h>
27 #include <sys/stat.h>
28
29 #include "config.h"
30 #include "mp_msg.h"
31 #include "help_mp.h"
32 #include "m_config.h"
33
34 #include "libvo/fastmemcpy.h"
35
36 #include "stream/stream.h"
37 #include "demuxer.h"
38 #include "stheader.h"
39 #include "mf.h"
40
41 #include "libaf/af_format.h"
42 #include "libmpcodecs/dec_teletext.h"
43
44 #ifdef CONFIG_ASS
45 #include "libass/ass.h"
46 #include "libass/ass_mp.h"
47 #endif
48
49 #ifdef CONFIG_LIBAVCODEC
50 #include "libavcodec/avcodec.h"
51 #if MP_INPUT_BUFFER_PADDING_SIZE < FF_INPUT_BUFFER_PADDING_SIZE
52 #error MP_INPUT_BUFFER_PADDING_SIZE is too small!
53 #endif
54 #endif
55
56 // This is quite experimental, in particular it will mess up the pts values
57 // in the queue - on the other hand it might fix some issues like generating
58 // broken files with mencoder and stream copy.
59 // Better leave it disabled for now, if we find no use for it this code should
60 // just be removed again.
61 #define PARSE_ON_ADD 0
62
63 void resync_video_stream(sh_video_t *sh_video);
64 void resync_audio_stream(sh_audio_t *sh_audio);
65
66 // Demuxer list
67 extern const demuxer_desc_t demuxer_desc_rawaudio;
68 extern const demuxer_desc_t demuxer_desc_rawvideo;
69 extern const demuxer_desc_t demuxer_desc_tv;
70 extern const demuxer_desc_t demuxer_desc_mf;
71 extern const demuxer_desc_t demuxer_desc_avi;
72 extern const demuxer_desc_t demuxer_desc_y4m;
73 extern const demuxer_desc_t demuxer_desc_asf;
74 extern const demuxer_desc_t demuxer_desc_real;
75 extern const demuxer_desc_t demuxer_desc_smjpeg;
76 extern const demuxer_desc_t demuxer_desc_matroska;
77 extern const demuxer_desc_t demuxer_desc_realaudio;
78 extern const demuxer_desc_t demuxer_desc_vqf;
79 extern const demuxer_desc_t demuxer_desc_mov;
80 extern const demuxer_desc_t demuxer_desc_vivo;
81 extern const demuxer_desc_t demuxer_desc_fli;
82 extern const demuxer_desc_t demuxer_desc_film;
83 extern const demuxer_desc_t demuxer_desc_roq;
84 extern const demuxer_desc_t demuxer_desc_gif;
85 extern const demuxer_desc_t demuxer_desc_ogg;
86 extern const demuxer_desc_t demuxer_desc_avs;
87 extern const demuxer_desc_t demuxer_desc_pva;
88 extern const demuxer_desc_t demuxer_desc_nsv;
89 extern const demuxer_desc_t demuxer_desc_mpeg_ts;
90 extern const demuxer_desc_t demuxer_desc_lmlm4;
91 extern const demuxer_desc_t demuxer_desc_mpeg_ps;
92 extern const demuxer_desc_t demuxer_desc_mpeg_pes;
93 extern const demuxer_desc_t demuxer_desc_mpeg_es;
94 extern const demuxer_desc_t demuxer_desc_mpeg_gxf;
95 extern const demuxer_desc_t demuxer_desc_mpeg4_es;
96 extern const demuxer_desc_t demuxer_desc_h264_es;
97 extern const demuxer_desc_t demuxer_desc_rawdv;
98 extern const demuxer_desc_t demuxer_desc_mpc;
99 extern const demuxer_desc_t demuxer_desc_audio;
100 extern const demuxer_desc_t demuxer_desc_xmms;
101 extern const demuxer_desc_t demuxer_desc_mpeg_ty;
102 extern const demuxer_desc_t demuxer_desc_rtp;
103 extern const demuxer_desc_t demuxer_desc_rtp_nemesi;
104 extern const demuxer_desc_t demuxer_desc_lavf;
105 extern const demuxer_desc_t demuxer_desc_lavf_preferred;
106 extern const demuxer_desc_t demuxer_desc_aac;
107 extern const demuxer_desc_t demuxer_desc_nut;
108 extern const demuxer_desc_t demuxer_desc_mng;
109
110 /* Please do not add any new demuxers here. If you want to implement a new
111  * demuxer, add it to libavformat, except for wrappers around external
112  * libraries and demuxers requiring binary support. */
113
114 const demuxer_desc_t *const demuxer_list[] = {
115     &demuxer_desc_rawaudio,
116     &demuxer_desc_rawvideo,
117 #ifdef CONFIG_TV
118     &demuxer_desc_tv,
119 #endif
120     &demuxer_desc_mf,
121 #ifdef CONFIG_LIBAVFORMAT
122     &demuxer_desc_lavf_preferred,
123 #endif
124     &demuxer_desc_avi,
125     &demuxer_desc_y4m,
126     &demuxer_desc_asf,
127     &demuxer_desc_nsv,
128     &demuxer_desc_real,
129     &demuxer_desc_smjpeg,
130     &demuxer_desc_matroska,
131     &demuxer_desc_realaudio,
132     &demuxer_desc_vqf,
133     &demuxer_desc_mov,
134     &demuxer_desc_vivo,
135     &demuxer_desc_fli,
136     &demuxer_desc_film,
137     &demuxer_desc_roq,
138 #ifdef CONFIG_GIF
139     &demuxer_desc_gif,
140 #endif
141 #ifdef CONFIG_OGGVORBIS
142     &demuxer_desc_ogg,
143 #endif
144 #ifdef CONFIG_WIN32DLL
145     &demuxer_desc_avs,
146 #endif
147     &demuxer_desc_pva,
148     &demuxer_desc_mpeg_ts,
149     &demuxer_desc_lmlm4,
150     &demuxer_desc_mpeg_ps,
151     &demuxer_desc_mpeg_pes,
152     &demuxer_desc_mpeg_es,
153     &demuxer_desc_mpeg_gxf,
154     &demuxer_desc_mpeg4_es,
155     &demuxer_desc_h264_es,
156     &demuxer_desc_audio,
157     &demuxer_desc_mpeg_ty,
158 #ifdef CONFIG_LIVE555
159     &demuxer_desc_rtp,
160 #endif
161 #ifdef CONFIG_LIBNEMESI
162     &demuxer_desc_rtp_nemesi,
163 #endif
164 #ifdef CONFIG_LIBAVFORMAT
165     &demuxer_desc_lavf,
166 #endif
167 #ifdef CONFIG_MUSEPACK
168     &demuxer_desc_mpc,
169 #endif
170 #ifdef CONFIG_LIBDV095
171     &demuxer_desc_rawdv,
172 #endif
173     &demuxer_desc_aac,
174 #ifdef CONFIG_LIBNUT
175     &demuxer_desc_nut,
176 #endif
177 #ifdef CONFIG_XMMS
178     &demuxer_desc_xmms,
179 #endif
180 #ifdef CONFIG_MNG
181     &demuxer_desc_mng,
182 #endif
183     /* Please do not add any new demuxers here. If you want to implement a new
184      * demuxer, add it to libavformat, except for wrappers around external
185      * libraries and demuxers requiring binary support. */
186     NULL
187 };
188
189 void free_demuxer_stream(demux_stream_t *ds)
190 {
191     ds_free_packs(ds);
192     free(ds);
193 }
194
195 demux_stream_t *new_demuxer_stream(struct demuxer_st *demuxer, int id)
196 {
197     demux_stream_t *ds = malloc(sizeof(demux_stream_t));
198     *ds = (demux_stream_t){
199         .id = id,
200         .demuxer = demuxer,
201         .asf_seq = -1,
202     };
203     return ds;
204 }
205
206
207 /**
208  * Get demuxer description structure for a given demuxer type
209  *
210  * @param file_format    type of the demuxer
211  * @return               structure for the demuxer, NULL if not found
212  */
213 static const demuxer_desc_t *get_demuxer_desc_from_type(int file_format)
214 {
215     int i;
216
217     for (i = 0; demuxer_list[i]; i++)
218         if (file_format == demuxer_list[i]->type)
219             return demuxer_list[i];
220
221     return NULL;
222 }
223
224
225 demuxer_t *new_demuxer(stream_t *stream, int type, int a_id, int v_id,
226                        int s_id, char *filename)
227 {
228     demuxer_t *d = malloc(sizeof(demuxer_t));
229     memset(d, 0, sizeof(demuxer_t));
230     d->stream = stream;
231     d->stream_pts = MP_NOPTS_VALUE;
232     d->reference_clock = MP_NOPTS_VALUE;
233     d->movi_start = stream->start_pos;
234     d->movi_end = stream->end_pos;
235     d->seekable = 1;
236     d->synced = 0;
237     d->filepos = -1;
238     d->audio = new_demuxer_stream(d, a_id);
239     d->video = new_demuxer_stream(d, v_id);
240     d->sub = new_demuxer_stream(d, s_id);
241     d->type = type;
242     if (type)
243         if (!(d->desc = get_demuxer_desc_from_type(type)))
244             mp_msg(MSGT_DEMUXER, MSGL_ERR,
245                    "BUG! Invalid demuxer type in new_demuxer(), "
246                    "big troubles ahead.");
247     if (filename) // Filename hack for avs_check_file
248         d->filename = strdup(filename);
249     stream_reset(stream);
250     stream_seek(stream, stream->start_pos);
251     return d;
252 }
253
254 extern int dvdsub_id;
255
256 sh_sub_t *new_sh_sub_sid(demuxer_t *demuxer, int id, int sid)
257 {
258     if (id > MAX_S_STREAMS - 1 || id < 0) {
259         mp_msg(MSGT_DEMUXER, MSGL_WARN,
260                "Requested sub stream id overflow (%d > %d)\n", id,
261                MAX_S_STREAMS);
262         return NULL;
263     }
264     if (demuxer->s_streams[id])
265         mp_msg(MSGT_DEMUXER, MSGL_WARN, "Sub stream %i redefined\n", id);
266     else {
267         sh_sub_t *sh = calloc(1, sizeof(sh_sub_t));
268         demuxer->s_streams[id] = sh;
269         sh->sid = sid;
270         mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_SUBTITLE_ID=%d\n", sid);
271     }
272     if (sid == dvdsub_id) {
273         demuxer->sub->id = id;
274         demuxer->sub->sh = demuxer->s_streams[id];
275     }
276     return demuxer->s_streams[id];
277 }
278
279 void free_sh_sub(sh_sub_t *sh)
280 {
281     mp_msg(MSGT_DEMUXER, MSGL_DBG2, "DEMUXER: freeing sh_sub at %p\n", sh);
282     free(sh->extradata);
283 #ifdef CONFIG_ASS
284     if (sh->ass_track)
285         ass_free_track(sh->ass_track);
286 #endif
287     free(sh->lang);
288 #ifdef CONFIG_LIBAVCODEC
289     av_parser_close(sh->parser);
290     av_freep(&sh->avctx);
291 #endif
292     free(sh);
293 }
294
295 sh_audio_t *new_sh_audio_aid(demuxer_t *demuxer, int id, int aid)
296 {
297     if (id > MAX_A_STREAMS - 1 || id < 0) {
298         mp_msg(MSGT_DEMUXER, MSGL_WARN,
299                "Requested audio stream id overflow (%d > %d)\n", id,
300                MAX_A_STREAMS);
301         return NULL;
302     }
303     if (demuxer->a_streams[id])
304         mp_msg(MSGT_DEMUXER, MSGL_WARN, MSGTR_AudioStreamRedefined, id);
305     else {
306         sh_audio_t *sh = calloc(1, sizeof(sh_audio_t));
307         mp_msg(MSGT_DEMUXER, MSGL_V, MSGTR_FoundAudioStream, id);
308         demuxer->a_streams[id] = sh;
309         sh->aid = aid;
310         sh->ds = demuxer->audio;
311         // set some defaults
312         sh->samplesize = 2;
313         sh->sample_format = AF_FORMAT_S16_NE;
314         sh->audio_out_minsize = 8192;   /* default size, maybe not enough for Win32/ACM */
315         sh->pts = MP_NOPTS_VALUE;
316         mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_ID=%d\n", aid);
317     }
318     return demuxer->a_streams[id];
319 }
320
321 void free_sh_audio(demuxer_t *demuxer, int id)
322 {
323     sh_audio_t *sh = demuxer->a_streams[id];
324     demuxer->a_streams[id] = NULL;
325     mp_msg(MSGT_DEMUXER, MSGL_DBG2, "DEMUXER: freeing sh_audio at %p\n", sh);
326     free(sh->wf);
327     free(sh->codecdata);
328     free(sh->lang);
329 #ifdef CONFIG_LIBAVCODEC
330     av_parser_close(sh->parser);
331     av_freep(&sh->avctx);
332 #endif
333     free(sh);
334 }
335
336 sh_video_t *new_sh_video_vid(demuxer_t *demuxer, int id, int vid)
337 {
338     if (id > MAX_V_STREAMS - 1 || id < 0) {
339         mp_msg(MSGT_DEMUXER, MSGL_WARN,
340                "Requested video stream id overflow (%d > %d)\n", id,
341                MAX_V_STREAMS);
342         return NULL;
343     }
344     if (demuxer->v_streams[id])
345         mp_msg(MSGT_DEMUXER, MSGL_WARN, MSGTR_VideoStreamRedefined, id);
346     else {
347         sh_video_t *sh = calloc(1, sizeof(sh_video_t));
348         mp_msg(MSGT_DEMUXER, MSGL_V, MSGTR_FoundVideoStream, id);
349         demuxer->v_streams[id] = sh;
350         sh->vid = vid;
351         sh->ds = demuxer->video;
352         mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_VIDEO_ID=%d\n", vid);
353     }
354     return demuxer->v_streams[id];
355 }
356
357 void free_sh_video(sh_video_t *sh)
358 {
359     mp_msg(MSGT_DEMUXER, MSGL_DBG2, "DEMUXER: freeing sh_video at %p\n", sh);
360     free(sh->bih);
361 #ifdef CONFIG_LIBAVCODEC
362     av_parser_close(sh->parser);
363     av_freep(&sh->avctx);
364 #endif
365     free(sh);
366 }
367
368 void free_demuxer(demuxer_t *demuxer)
369 {
370     int i;
371     mp_msg(MSGT_DEMUXER, MSGL_DBG2, "DEMUXER: freeing demuxer at %p\n",
372            demuxer);
373     if (demuxer->desc->close)
374         demuxer->desc->close(demuxer);
375     // Very ugly hack to make it behave like old implementation
376     if (demuxer->desc->type == DEMUXER_TYPE_DEMUXERS)
377         goto skip_streamfree;
378     // free streams:
379     for (i = 0; i < MAX_A_STREAMS; i++)
380         if (demuxer->a_streams[i])
381             free_sh_audio(demuxer, i);
382     for (i = 0; i < MAX_V_STREAMS; i++)
383         if (demuxer->v_streams[i])
384             free_sh_video(demuxer->v_streams[i]);
385     for (i = 0; i < MAX_S_STREAMS; i++)
386         if (demuxer->s_streams[i])
387             free_sh_sub(demuxer->s_streams[i]);
388     // free demuxers:
389     free_demuxer_stream(demuxer->audio);
390     free_demuxer_stream(demuxer->video);
391     free_demuxer_stream(demuxer->sub);
392  skip_streamfree:
393     if (demuxer->info) {
394         for (i = 0; demuxer->info[i] != NULL; i++)
395             free(demuxer->info[i]);
396         free(demuxer->info);
397     }
398     free(demuxer->filename);
399     if (demuxer->chapters) {
400         for (i = 0; i < demuxer->num_chapters; i++)
401             free(demuxer->chapters[i].name);
402         free(demuxer->chapters);
403     }
404     if (demuxer->attachments) {
405         for (i = 0; i < demuxer->num_attachments; i++) {
406             free(demuxer->attachments[i].name);
407             free(demuxer->attachments[i].type);
408             free(demuxer->attachments[i].data);
409         }
410         free(demuxer->attachments);
411     }
412     if (demuxer->teletext)
413         teletext_control(demuxer->teletext, TV_VBI_CONTROL_STOP, NULL);
414     free(demuxer);
415 }
416
417
418 static void ds_add_packet_internal(demux_stream_t *ds, demux_packet_t *dp)
419 {
420     // append packet to DS stream:
421     ++ds->packs;
422     ds->bytes += dp->len;
423     if (ds->last) {
424         // next packet in stream
425         ds->last->next = dp;
426         ds->last = dp;
427     } else {
428         // first packet in stream
429         ds->first = ds->last = dp;
430     }
431     mp_dbg(MSGT_DEMUXER, MSGL_DBG2,
432            "DEMUX: Append packet to %s, len=%d  pts=%5.3f  pos=%u  [packs: A=%d V=%d]\n",
433            (ds == ds->demuxer->audio) ? "d_audio" : "d_video", dp->len,
434            dp->pts, (unsigned int) dp->pos, ds->demuxer->audio->packs,
435            ds->demuxer->video->packs);
436 }
437
438 #ifdef CONFIG_LIBAVCODEC
439 static void allocate_parser(AVCodecContext **avctx, AVCodecParserContext **parser, unsigned format)
440 {
441     enum CodecID codec_id = CODEC_ID_NONE;
442     extern int avcodec_initialized;
443     if (!avcodec_initialized) {
444         avcodec_init();
445         avcodec_register_all();
446         avcodec_initialized = 1;
447     }
448     switch (format) {
449     case 0x2000:
450     case 0x332D6361:
451     case 0x332D4341:
452     case MKTAG('d', 'n', 'e', 't'):
453     case MKTAG('s', 'a', 'c', '3'):
454         codec_id = CODEC_ID_AC3;
455         break;
456     case MKTAG('E', 'A', 'C', '3'):
457         codec_id = CODEC_ID_EAC3;
458         break;
459     case 0x2001:
460     case 0x86:
461         codec_id = CODEC_ID_DTS;
462         break;
463     case 0x55:
464     case 0x5500736d:
465     case MKTAG('.', 'm', 'p', '3'):
466     case MKTAG('M', 'P', 'E', ' '):
467     case MKTAG('L', 'A', 'M', 'E'):
468         codec_id = CODEC_ID_MP3;
469         break;
470     case 0x50:
471     case MKTAG('.', 'm', 'p', '2'):
472     case MKTAG('.', 'm', 'p', '1'):
473         codec_id = CODEC_ID_MP2;
474         break;
475     }
476     if (codec_id != CODEC_ID_NONE) {
477         *avctx = avcodec_alloc_context();
478         if (!*avctx)
479             return;
480         *parser = av_parser_init(codec_id);
481         if (!*parser)
482             av_freep(avctx);
483     }
484 }
485
486 static void get_parser(sh_common_t *sh, AVCodecContext **avctx, AVCodecParserContext **parser)
487 {
488     *avctx  = NULL;
489     *parser = NULL;
490
491     if (!sh || !sh->needs_parsing)
492         return;
493
494     *avctx  = sh->avctx;
495     *parser = sh->parser;
496     if (*parser)
497         return;
498
499     allocate_parser(avctx, parser, sh->format);
500     sh->avctx  = *avctx;
501     sh->parser = *parser;
502 }
503
504 int ds_parse(demux_stream_t *ds, uint8_t **buffer, int *len, double pts, off_t pos)
505 {
506     AVCodecContext *avctx;
507     AVCodecParserContext *parser;
508     get_parser(ds->sh, &avctx, &parser);
509     if (!parser)
510         return *len;
511     return av_parser_parse2(parser, avctx, buffer, len, *buffer, *len, pts, pts, pos);
512 }
513 #endif
514
515 void ds_add_packet(demux_stream_t *ds, demux_packet_t *dp)
516 {
517 #if PARSE_ON_ADD && defined(CONFIG_LIBAVCODEC)
518     int len = dp->len;
519     int pos = 0;
520     while (len > 0) {
521         uint8_t *parsed_start = dp->buffer + pos;
522         int parsed_len = len;
523         int consumed = ds_parse(ds->sh, &parsed_start, &parsed_len, dp->pts, dp->pos);
524         pos += consumed;
525         len -= consumed;
526         if (parsed_start == dp->buffer && parsed_len == dp->len) {
527             ds_add_packet_internal(ds, dp);
528         } else if (parsed_len) {
529             demux_packet_t *dp2 = new_demux_packet(parsed_len);
530             dp2->pos = dp->pos;
531             dp2->pts = dp->pts; // should be parser->pts but that works badly
532             memcpy(dp2->buffer, parsed_start, parsed_len);
533             ds_add_packet_internal(ds, dp2);
534         }
535     }
536 #else
537     ds_add_packet_internal(ds, dp);
538 #endif
539 }
540
541 void ds_read_packet(demux_stream_t *ds, stream_t *stream, int len,
542                     double pts, off_t pos, int flags)
543 {
544     demux_packet_t *dp = new_demux_packet(len);
545     len = stream_read(stream, dp->buffer, len);
546     resize_demux_packet(dp, len);
547     dp->pts = pts;
548     dp->pos = pos;
549     dp->flags = flags;
550     // append packet to DS stream:
551     ds_add_packet(ds, dp);
552 }
553
554 // return value:
555 //     0 = EOF or no stream found or invalid type
556 //     1 = successfully read a packet
557
558 int demux_fill_buffer(demuxer_t *demux, demux_stream_t *ds)
559 {
560     // Note: parameter 'ds' can be NULL!
561     return demux->desc->fill_buffer(demux, ds);
562 }
563
564 // return value:
565 //     0 = EOF
566 //     1 = successful
567 #define MAX_ACUMULATED_PACKETS 64
568 int ds_fill_buffer(demux_stream_t *ds)
569 {
570     demuxer_t *demux = ds->demuxer;
571     if (ds->current)
572         free_demux_packet(ds->current);
573     ds->current = NULL;
574     if (mp_msg_test(MSGT_DEMUXER, MSGL_DBG3)) {
575         if (ds == demux->audio)
576             mp_dbg(MSGT_DEMUXER, MSGL_DBG3,
577                    "ds_fill_buffer(d_audio) called\n");
578         else if (ds == demux->video)
579             mp_dbg(MSGT_DEMUXER, MSGL_DBG3,
580                    "ds_fill_buffer(d_video) called\n");
581         else if (ds == demux->sub)
582             mp_dbg(MSGT_DEMUXER, MSGL_DBG3, "ds_fill_buffer(d_sub) called\n");
583         else
584             mp_dbg(MSGT_DEMUXER, MSGL_DBG3,
585                    "ds_fill_buffer(unknown 0x%X) called\n", (unsigned int) ds);
586     }
587     while (1) {
588         if (ds->packs) {
589             demux_packet_t *p = ds->first;
590 #if 0
591             if (demux->reference_clock != MP_NOPTS_VALUE) {
592                 if (   p->pts != MP_NOPTS_VALUE
593                     && p->pts >  demux->reference_clock
594                     && ds->packs < MAX_ACUMULATED_PACKETS) {
595                     if (demux_fill_buffer(demux, ds))
596                         continue;
597                 }
598             }
599 #endif
600             // copy useful data:
601             ds->buffer = p->buffer;
602             ds->buffer_pos = 0;
603             ds->buffer_size = p->len;
604             ds->pos = p->pos;
605             ds->dpos += p->len; // !!!
606             ++ds->pack_no;
607             if (p->pts != MP_NOPTS_VALUE) {
608                 ds->pts = p->pts;
609                 ds->pts_bytes = 0;
610             }
611             ds->pts_bytes += p->len;    // !!!
612             if (p->stream_pts != MP_NOPTS_VALUE)
613                 demux->stream_pts = p->stream_pts;
614             ds->flags = p->flags;
615             // unlink packet:
616             ds->bytes -= p->len;
617             ds->current = p;
618             ds->first = p->next;
619             if (!ds->first)
620                 ds->last = NULL;
621             --ds->packs;
622             return 1;
623         }
624         if (demux->audio->packs >= MAX_PACKS
625             || demux->audio->bytes >= MAX_PACK_BYTES) {
626             mp_msg(MSGT_DEMUXER, MSGL_ERR, MSGTR_TooManyAudioInBuffer,
627                    demux->audio->packs, demux->audio->bytes);
628             mp_msg(MSGT_DEMUXER, MSGL_HINT, MSGTR_MaybeNI);
629             break;
630         }
631         if (demux->video->packs >= MAX_PACKS
632             || demux->video->bytes >= MAX_PACK_BYTES) {
633             mp_msg(MSGT_DEMUXER, MSGL_ERR, MSGTR_TooManyVideoInBuffer,
634                    demux->video->packs, demux->video->bytes);
635             mp_msg(MSGT_DEMUXER, MSGL_HINT, MSGTR_MaybeNI);
636             break;
637         }
638         if (!demux_fill_buffer(demux, ds)) {
639 #if PARSE_ON_ADD && defined(CONFIG_LIBAVCODEC)
640             uint8_t *parsed_start = NULL;
641             int parsed_len = 0;
642             ds_parse(ds->sh, &parsed_start, &parsed_len, MP_NOPTS_VALUE, 0);
643             if (parsed_len) {
644                 demux_packet_t *dp2 = new_demux_packet(parsed_len);
645                 dp2->pts = MP_NOPTS_VALUE;
646                 memcpy(dp2->buffer, parsed_start, parsed_len);
647                 ds_add_packet_internal(ds, dp2);
648                 continue;
649             }
650 #endif
651             mp_dbg(MSGT_DEMUXER, MSGL_DBG2,
652                    "ds_fill_buffer()->demux_fill_buffer() failed\n");
653             break; // EOF
654         }
655     }
656     ds->buffer_pos = ds->buffer_size = 0;
657     ds->buffer = NULL;
658     mp_msg(MSGT_DEMUXER, MSGL_V,
659            "ds_fill_buffer: EOF reached (stream: %s)  \n",
660            ds == demux->audio ? "audio" : "video");
661     ds->eof = 1;
662     return 0;
663 }
664
665 int demux_read_data(demux_stream_t *ds, unsigned char *mem, int len)
666 {
667     int x;
668     int bytes = 0;
669     while (len > 0) {
670         x = ds->buffer_size - ds->buffer_pos;
671         if (x == 0) {
672             if (!ds_fill_buffer(ds))
673                 return bytes;
674         } else {
675             if (x > len)
676                 x = len;
677             if (mem)
678                 fast_memcpy(mem + bytes, &ds->buffer[ds->buffer_pos], x);
679             bytes += x;
680             len -= x;
681             ds->buffer_pos += x;
682         }
683     }
684     return bytes;
685 }
686
687 /**
688  * \brief read data until the given 3-byte pattern is encountered, up to maxlen
689  * \param mem memory to read data into, may be NULL to discard data
690  * \param maxlen maximum number of bytes to read
691  * \param read number of bytes actually read
692  * \param pattern pattern to search for (lowest 8 bits are ignored)
693  * \return whether pattern was found
694  */
695 int demux_pattern_3(demux_stream_t *ds, unsigned char *mem, int maxlen,
696                     int *read, uint32_t pattern)
697 {
698     register uint32_t head = 0xffffff00;
699     register uint32_t pat = pattern & 0xffffff00;
700     int total_len = 0;
701     do {
702         register unsigned char *ds_buf = &ds->buffer[ds->buffer_size];
703         int len = ds->buffer_size - ds->buffer_pos;
704         register long pos = -len;
705         if (unlikely(pos >= 0)) { // buffer is empty
706             ds_fill_buffer(ds);
707             continue;
708         }
709         do {
710             head |= ds_buf[pos];
711             head <<= 8;
712         } while (++pos && head != pat);
713         len += pos;
714         if (total_len + len > maxlen)
715             len = maxlen - total_len;
716         len = demux_read_data(ds, mem ? &mem[total_len] : NULL, len);
717         total_len += len;
718     } while ((head != pat || total_len < 3) && total_len < maxlen && !ds->eof);
719     if (read)
720         *read = total_len;
721     return total_len >= 3 && head == pat;
722 }
723
724 void ds_free_packs(demux_stream_t *ds)
725 {
726     demux_packet_t *dp = ds->first;
727     while (dp) {
728         demux_packet_t *dn = dp->next;
729         free_demux_packet(dp);
730         dp = dn;
731     }
732     if (ds->asf_packet) {
733         // free unfinished .asf fragments:
734         free(ds->asf_packet->buffer);
735         free(ds->asf_packet);
736         ds->asf_packet = NULL;
737     }
738     ds->first = ds->last = NULL;
739     ds->packs = 0; // !!!!!
740     ds->bytes = 0;
741     if (ds->current)
742         free_demux_packet(ds->current);
743     ds->current = NULL;
744     ds->buffer = NULL;
745     ds->buffer_pos = ds->buffer_size;
746     ds->pts = 0;
747     ds->pts_bytes = 0;
748 }
749
750 int ds_get_packet(demux_stream_t *ds, unsigned char **start)
751 {
752     int len;
753     if (ds->buffer_pos >= ds->buffer_size) {
754         if (!ds_fill_buffer(ds)) {
755             // EOF
756             *start = NULL;
757             return -1;
758         }
759     }
760     len = ds->buffer_size - ds->buffer_pos;
761     *start = &ds->buffer[ds->buffer_pos];
762     ds->buffer_pos += len;
763     return len;
764 }
765
766 int ds_get_packet_pts(demux_stream_t *ds, unsigned char **start, double *pts)
767 {
768     int len;
769     *pts = MP_NOPTS_VALUE;
770     len = ds_get_packet(ds, start);
771     if (len < 0)
772         return len;
773     // Return pts unless this read starts from the middle of a packet
774     if (len == ds->buffer_pos)
775         *pts = ds->current->pts;
776     return len;
777 }
778
779 int ds_get_packet_sub(demux_stream_t *ds, unsigned char **start)
780 {
781     int len;
782     if (ds->buffer_pos >= ds->buffer_size) {
783         *start = NULL;
784         if (!ds->packs)
785             return -1;  // no sub
786         if (!ds_fill_buffer(ds))
787             return -1;  // EOF
788     }
789     len = ds->buffer_size - ds->buffer_pos;
790     *start = &ds->buffer[ds->buffer_pos];
791     ds->buffer_pos += len;
792     return len;
793 }
794
795 double ds_get_next_pts(demux_stream_t *ds)
796 {
797     demuxer_t *demux = ds->demuxer;
798     while (!ds->first) {
799         if (demux->audio->packs >= MAX_PACKS
800             || demux->audio->bytes >= MAX_PACK_BYTES) {
801             mp_msg(MSGT_DEMUXER, MSGL_ERR, MSGTR_TooManyAudioInBuffer,
802                    demux->audio->packs, demux->audio->bytes);
803             mp_msg(MSGT_DEMUXER, MSGL_HINT, MSGTR_MaybeNI);
804             return MP_NOPTS_VALUE;
805         }
806         if (demux->video->packs >= MAX_PACKS
807             || demux->video->bytes >= MAX_PACK_BYTES) {
808             mp_msg(MSGT_DEMUXER, MSGL_ERR, MSGTR_TooManyVideoInBuffer,
809                    demux->video->packs, demux->video->bytes);
810             mp_msg(MSGT_DEMUXER, MSGL_HINT, MSGTR_MaybeNI);
811             return MP_NOPTS_VALUE;
812         }
813         if (!demux_fill_buffer(demux, ds))
814             return MP_NOPTS_VALUE;
815     }
816     return ds->first->pts;
817 }
818
819 // ====================================================================
820
821 void demuxer_help(void)
822 {
823     int i;
824
825     mp_msg(MSGT_DEMUXER, MSGL_INFO, "Available demuxers:\n");
826     mp_msg(MSGT_DEMUXER, MSGL_INFO, " demuxer:  type  info:  (comment)\n");
827     mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_DEMUXERS\n");
828     for (i = 0; demuxer_list[i]; i++) {
829         if (demuxer_list[i]->type > DEMUXER_TYPE_MAX)   // Don't display special demuxers
830             continue;
831         if (demuxer_list[i]->comment && strlen(demuxer_list[i]->comment))
832             mp_msg(MSGT_DEMUXER, MSGL_INFO, "%10s  %2d   %s (%s)\n",
833                    demuxer_list[i]->name, demuxer_list[i]->type,
834                    demuxer_list[i]->info, demuxer_list[i]->comment);
835         else
836             mp_msg(MSGT_DEMUXER, MSGL_INFO, "%10s  %2d   %s\n",
837                    demuxer_list[i]->name, demuxer_list[i]->type,
838                    demuxer_list[i]->info);
839     }
840 }
841
842
843 /**
844  * Get demuxer type for a given demuxer name
845  *
846  * @param demuxer_name    string with demuxer name of demuxer number
847  * @param force           will be set if demuxer should be forced.
848  *                        May be NULL.
849  * @return                DEMUXER_TYPE_xxx, -1 if error or not found
850  */
851 int get_demuxer_type_from_name(char *demuxer_name, int *force)
852 {
853     int i;
854     long type_int;
855     char *endptr;
856
857     if (!demuxer_name || !demuxer_name[0])
858         return DEMUXER_TYPE_UNKNOWN;
859     if (force)
860         *force = demuxer_name[0] == '+';
861     if (demuxer_name[0] == '+')
862         demuxer_name = &demuxer_name[1];
863     for (i = 0; demuxer_list[i]; i++) {
864         if (demuxer_list[i]->type > DEMUXER_TYPE_MAX)   // Can't select special demuxers from commandline
865             continue;
866         if (strcmp(demuxer_name, demuxer_list[i]->name) == 0)
867             return demuxer_list[i]->type;
868     }
869
870     // No match found, try to parse name as an integer (demuxer number)
871     type_int = strtol(demuxer_name, &endptr, 0);
872     if (*endptr)  // Conversion failed
873         return -1;
874     if ((type_int > 0) && (type_int <= DEMUXER_TYPE_MAX))
875         return (int) type_int;
876
877     return -1;
878 }
879
880 int extension_parsing = 1; // 0=off 1=mixed (used only for unstable formats)
881
882 int correct_pts = 0;
883 int user_correct_pts = -1;
884
885 /*
886   NOTE : Several demuxers may be opened at the same time so
887   demuxers should NEVER rely on an external var to enable them
888   self. If a demuxer can't do any auto-detection it should only use
889   file_format. The user can explicitly set file_format with the -demuxer
890   option so there is really no need for another extra var.
891   For convenience an option can be added to set file_format directly
892   to the right type (ex: rawaudio,rawvideo).
893   Also the stream can override the file_format so a demuxer which rely
894   on a special stream type can set file_format at the stream level
895   (ex: tv,mf).
896 */
897
898 static demuxer_t *demux_open_stream(stream_t *stream, int file_format,
899                                     int force, int audio_id, int video_id,
900                                     int dvdsub_id, char *filename)
901 {
902     demuxer_t *demuxer = NULL;
903
904     sh_video_t *sh_video = NULL;
905
906     const demuxer_desc_t *demuxer_desc;
907     int fformat = 0;
908     int i;
909
910     // If somebody requested a demuxer check it
911     if (file_format) {
912         if ((demuxer_desc = get_demuxer_desc_from_type(file_format))) {
913             demuxer = new_demuxer(stream, demuxer_desc->type, audio_id,
914                                   video_id, dvdsub_id, filename);
915             if (demuxer_desc->check_file)
916                 fformat = demuxer_desc->check_file(demuxer);
917             if (force || !demuxer_desc->check_file)
918                 fformat = demuxer_desc->type;
919             if (fformat != 0) {
920                 if (fformat == demuxer_desc->type) {
921                     demuxer_t *demux2 = demuxer;
922                     // Move messages to demuxer detection code?
923                     mp_msg(MSGT_DEMUXER, MSGL_INFO,
924                            MSGTR_Detected_XXX_FileFormat,
925                            demuxer_desc->shortdesc);
926                     file_format = fformat;
927                     if (!demuxer->desc->open
928                         || (demux2 = demuxer->desc->open(demuxer))) {
929                         demuxer = demux2;
930                         goto dmx_open;
931                     }
932                 } else {
933                     // Format changed after check, recurse
934                     free_demuxer(demuxer);
935                     return demux_open_stream(stream, fformat, force, audio_id,
936                                              video_id, dvdsub_id, filename);
937                 }
938             }
939             // Check failed for forced demuxer, quit
940             free_demuxer(demuxer);
941             return NULL;
942         }
943     }
944     // Test demuxers with safe file checks
945     for (i = 0; (demuxer_desc = demuxer_list[i]); i++) {
946         if (demuxer_desc->safe_check) {
947             demuxer = new_demuxer(stream, demuxer_desc->type, audio_id,
948                                   video_id, dvdsub_id, filename);
949             if ((fformat = demuxer_desc->check_file(demuxer)) != 0) {
950                 if (fformat == demuxer_desc->type) {
951                     demuxer_t *demux2 = demuxer;
952                     mp_msg(MSGT_DEMUXER, MSGL_INFO,
953                            MSGTR_Detected_XXX_FileFormat,
954                            demuxer_desc->shortdesc);
955                     file_format = fformat;
956                     if (!demuxer->desc->open
957                         || (demux2 = demuxer->desc->open(demuxer))) {
958                         demuxer = demux2;
959                         goto dmx_open;
960                     }
961                 } else {
962                     if (fformat == DEMUXER_TYPE_PLAYLIST)
963                         return demuxer; // handled in mplayer.c
964                     // Format changed after check, recurse
965                     free_demuxer(demuxer);
966                     demuxer = demux_open_stream(stream, fformat, force,
967                                                 audio_id, video_id,
968                                                 dvdsub_id, filename);
969                     if (demuxer)
970                         return demuxer; // done!
971                     file_format = DEMUXER_TYPE_UNKNOWN;
972                 }
973             }
974             free_demuxer(demuxer);
975             demuxer = NULL;
976         }
977     }
978
979     // If no forced demuxer perform file extension based detection
980     // Ok. We're over the stable detectable fileformats, the next ones are
981     // a bit fuzzy. So by default (extension_parsing==1) try extension-based
982     // detection first:
983     if (file_format == DEMUXER_TYPE_UNKNOWN && filename
984         && extension_parsing == 1) {
985         file_format = demuxer_type_by_filename(filename);
986         if (file_format != DEMUXER_TYPE_UNKNOWN) {
987             // we like recursion :)
988             demuxer = demux_open_stream(stream, file_format, force, audio_id,
989                                         video_id, dvdsub_id, filename);
990             if (demuxer)
991                 return demuxer; // done!
992             file_format = DEMUXER_TYPE_UNKNOWN; // continue fuzzy guessing...
993             mp_msg(MSGT_DEMUXER, MSGL_V,
994                    "demuxer: continue fuzzy content-based format guessing...\n");
995         }
996     }
997     // Try detection for all other demuxers
998     for (i = 0; (demuxer_desc = demuxer_list[i]); i++) {
999         if (!demuxer_desc->safe_check && demuxer_desc->check_file) {
1000             demuxer = new_demuxer(stream, demuxer_desc->type, audio_id,
1001                                   video_id, dvdsub_id, filename);
1002             if ((fformat = demuxer_desc->check_file(demuxer)) != 0) {
1003                 if (fformat == demuxer_desc->type) {
1004                     demuxer_t *demux2 = demuxer;
1005                     mp_msg(MSGT_DEMUXER, MSGL_INFO,
1006                            MSGTR_Detected_XXX_FileFormat,
1007                            demuxer_desc->shortdesc);
1008                     file_format = fformat;
1009                     if (!demuxer->desc->open
1010                         || (demux2 = demuxer->desc->open(demuxer))) {
1011                         demuxer = demux2;
1012                         goto dmx_open;
1013                     }
1014                 } else {
1015                     if (fformat == DEMUXER_TYPE_PLAYLIST)
1016                         return demuxer; // handled in mplayer.c
1017                     // Format changed after check, recurse
1018                     free_demuxer(demuxer);
1019                     demuxer = demux_open_stream(stream, fformat, force,
1020                                                 audio_id, video_id,
1021                                                 dvdsub_id, filename);
1022                     if (demuxer)
1023                         return demuxer; // done!
1024                     file_format = DEMUXER_TYPE_UNKNOWN;
1025                 }
1026             }
1027             free_demuxer(demuxer);
1028             demuxer = NULL;
1029         }
1030     }
1031
1032     return NULL;
1033     //====== File format recognized, set up these for compatibility: =========
1034  dmx_open:
1035
1036     demuxer->file_format = file_format;
1037
1038     if ((sh_video = demuxer->video->sh) && sh_video->bih) {
1039         int biComp = le2me_32(sh_video->bih->biCompression);
1040         mp_msg(MSGT_DEMUX, MSGL_INFO,
1041                "VIDEO:  [%.4s]  %dx%d  %dbpp  %5.3f fps  %5.1f kbps (%4.1f kbyte/s)\n",
1042                (char *) &biComp, sh_video->bih->biWidth,
1043                sh_video->bih->biHeight, sh_video->bih->biBitCount,
1044                sh_video->fps, sh_video->i_bps * 0.008f,
1045                sh_video->i_bps / 1024.0f);
1046     }
1047 #ifdef CONFIG_ASS
1048     if (ass_enabled && ass_library) {
1049         for (i = 0; i < MAX_S_STREAMS; ++i) {
1050             sh_sub_t *sh = demuxer->s_streams[i];
1051             if (sh && sh->type == 'a') {
1052                 sh->ass_track = ass_new_track(ass_library);
1053                 if (sh->ass_track && sh->extradata)
1054                     ass_process_codec_private(sh->ass_track, sh->extradata,
1055                                               sh->extradata_len);
1056             } else if (sh && sh->type != 'v')
1057                 sh->ass_track = ass_default_track(ass_library);
1058         }
1059     }
1060 #endif
1061     return demuxer;
1062 }
1063
1064 char *audio_stream = NULL;
1065 char *sub_stream = NULL;
1066 int audio_stream_cache = 0;
1067
1068 char *demuxer_name = NULL;       // parameter from -demuxer
1069 char *audio_demuxer_name = NULL; // parameter from -audio-demuxer
1070 char *sub_demuxer_name = NULL;   // parameter from -sub-demuxer
1071
1072 extern int hr_mp3_seek;
1073
1074 extern float stream_cache_min_percent;
1075 extern float stream_cache_seek_min_percent;
1076
1077 demuxer_t *demux_open(stream_t *vs, int file_format, int audio_id,
1078                       int video_id, int dvdsub_id, char *filename)
1079 {
1080     stream_t *as = NULL, *ss = NULL;
1081     demuxer_t *vd, *ad = NULL, *sd = NULL;
1082     demuxer_t *res;
1083     int afmt = DEMUXER_TYPE_UNKNOWN, sfmt = DEMUXER_TYPE_UNKNOWN;
1084     int demuxer_type;
1085     int audio_demuxer_type = 0, sub_demuxer_type = 0;
1086     int demuxer_force = 0, audio_demuxer_force = 0, sub_demuxer_force = 0;
1087
1088     if ((demuxer_type =
1089          get_demuxer_type_from_name(demuxer_name, &demuxer_force)) < 0) {
1090         mp_msg(MSGT_DEMUXER, MSGL_ERR, "-demuxer %s does not exist.\n",
1091                demuxer_name);
1092     }
1093     if ((audio_demuxer_type =
1094          get_demuxer_type_from_name(audio_demuxer_name,
1095                                     &audio_demuxer_force)) < 0) {
1096         mp_msg(MSGT_DEMUXER, MSGL_ERR, "-audio-demuxer %s does not exist.\n",
1097                audio_demuxer_name);
1098     }
1099     if ((sub_demuxer_type =
1100          get_demuxer_type_from_name(sub_demuxer_name,
1101                                     &sub_demuxer_force)) < 0) {
1102         mp_msg(MSGT_DEMUXER, MSGL_ERR, "-sub-demuxer %s does not exist.\n",
1103                sub_demuxer_name);
1104     }
1105
1106     if (audio_stream) {
1107         as = open_stream(audio_stream, 0, &afmt);
1108         if (!as) {
1109             mp_msg(MSGT_DEMUXER, MSGL_ERR, MSGTR_CannotOpenAudioStream,
1110                    audio_stream);
1111             return NULL;
1112         }
1113         if (audio_stream_cache) {
1114             if (!stream_enable_cache
1115                 (as, audio_stream_cache * 1024,
1116                  audio_stream_cache * 1024 * (stream_cache_min_percent /
1117                                               100.0),
1118                  audio_stream_cache * 1024 * (stream_cache_seek_min_percent /
1119                                               100.0))) {
1120                 free_stream(as);
1121                 mp_msg(MSGT_DEMUXER, MSGL_ERR,
1122                        "Can't enable audio stream cache\n");
1123                 return NULL;
1124             }
1125         }
1126     }
1127     if (sub_stream) {
1128         ss = open_stream(sub_stream, 0, &sfmt);
1129         if (!ss) {
1130             mp_msg(MSGT_DEMUXER, MSGL_ERR, MSGTR_CannotOpenSubtitlesStream,
1131                    sub_stream);
1132             return NULL;
1133         }
1134     }
1135
1136     vd = demux_open_stream(vs, demuxer_type ? demuxer_type : file_format,
1137                            demuxer_force, audio_stream ? -2 : audio_id,
1138                            video_id, sub_stream ? -2 : dvdsub_id, filename);
1139     if (!vd) {
1140         if (as)
1141             free_stream(as);
1142         if (ss)
1143             free_stream(ss);
1144         return NULL;
1145     }
1146     if (as) {
1147         ad = demux_open_stream(as,
1148                                audio_demuxer_type ? audio_demuxer_type : afmt,
1149                                audio_demuxer_force, audio_id, -2, -2,
1150                                audio_stream);
1151         if (!ad) {
1152             mp_msg(MSGT_DEMUXER, MSGL_WARN, MSGTR_OpeningAudioDemuxerFailed,
1153                    audio_stream);
1154             free_stream(as);
1155         } else if (ad->audio->sh
1156                    && ((sh_audio_t *) ad->audio->sh)->format == 0x55) // MP3
1157             hr_mp3_seek = 1;    // Enable high res seeking
1158     }
1159     if (ss) {
1160         sd = demux_open_stream(ss, sub_demuxer_type ? sub_demuxer_type : sfmt,
1161                                sub_demuxer_force, -2, -2, dvdsub_id,
1162                                sub_stream);
1163         if (!sd) {
1164             mp_msg(MSGT_DEMUXER, MSGL_WARN,
1165                    MSGTR_OpeningSubtitlesDemuxerFailed, sub_stream);
1166             free_stream(ss);
1167         }
1168     }
1169
1170     if (ad && sd)
1171         res = new_demuxers_demuxer(vd, ad, sd);
1172     else if (ad)
1173         res = new_demuxers_demuxer(vd, ad, vd);
1174     else if (sd)
1175         res = new_demuxers_demuxer(vd, vd, sd);
1176     else
1177         res = vd;
1178
1179     correct_pts = user_correct_pts;
1180     if (correct_pts < 0)
1181         correct_pts = demux_control(res, DEMUXER_CTRL_CORRECT_PTS, NULL)
1182                       == DEMUXER_CTRL_OK;
1183     return res;
1184 }
1185
1186
1187 void demux_flush(demuxer_t *demuxer)
1188 {
1189     ds_free_packs(demuxer->video);
1190     ds_free_packs(demuxer->audio);
1191     ds_free_packs(demuxer->sub);
1192 }
1193
1194 int demux_seek(demuxer_t *demuxer, float rel_seek_secs, float audio_delay,
1195                int flags)
1196 {
1197     demux_stream_t *d_audio = demuxer->audio;
1198     demux_stream_t *d_video = demuxer->video;
1199     sh_audio_t *sh_audio = d_audio->sh;
1200     sh_video_t *sh_video = d_video->sh;
1201     double tmp = 0;
1202     double pts;
1203
1204     if (!demuxer->seekable) {
1205         if (demuxer->file_format == DEMUXER_TYPE_AVI)
1206             mp_msg(MSGT_SEEK, MSGL_WARN, MSGTR_CantSeekRawAVI);
1207 #ifdef CONFIG_TV
1208         else if (demuxer->file_format == DEMUXER_TYPE_TV)
1209             mp_msg(MSGT_SEEK, MSGL_WARN, MSGTR_TVInputNotSeekable);
1210 #endif
1211         else
1212             mp_msg(MSGT_SEEK, MSGL_WARN, MSGTR_CantSeekFile);
1213         return 0;
1214     }
1215
1216     demux_flush(demuxer);
1217     // clear demux buffers:
1218     if (sh_audio)
1219         sh_audio->a_buffer_len = 0;
1220
1221     demuxer->stream->eof = 0;
1222     demuxer->video->eof = 0;
1223     demuxer->audio->eof = 0;
1224
1225     if (sh_video)
1226         sh_video->timer = 0;    // !!!!!!
1227
1228     if (flags & SEEK_ABSOLUTE)
1229         pts = 0.0f;
1230     else {
1231         if (demuxer->stream_pts == MP_NOPTS_VALUE)
1232             goto dmx_seek;
1233         pts = demuxer->stream_pts;
1234     }
1235
1236     if (flags & SEEK_FACTOR) {
1237         if (stream_control(demuxer->stream, STREAM_CTRL_GET_TIME_LENGTH, &tmp)
1238             == STREAM_UNSUPPORTED)
1239             goto dmx_seek;
1240         pts += tmp * rel_seek_secs;
1241     } else
1242         pts += rel_seek_secs;
1243
1244     if (stream_control(demuxer->stream, STREAM_CTRL_SEEK_TO_TIME, &pts) !=
1245         STREAM_UNSUPPORTED) {
1246         demux_control(demuxer, DEMUXER_CTRL_RESYNC, NULL);
1247         return 1;
1248     }
1249
1250   dmx_seek:
1251     if (demuxer->desc->seek)
1252         demuxer->desc->seek(demuxer, rel_seek_secs, audio_delay, flags);
1253
1254     if (sh_audio)
1255         resync_audio_stream(sh_audio);
1256
1257     return 1;
1258 }
1259
1260 int demux_info_add(demuxer_t *demuxer, const char *opt, const char *param)
1261 {
1262     char **info = demuxer->info;
1263     int n = 0;
1264
1265
1266     for (n = 0; info && info[2 * n] != NULL; n++) {
1267         if (!strcasecmp(opt, info[2 * n])) {
1268             if (!strcmp(param, info[2 * n + 1])) {
1269                 mp_msg(MSGT_DEMUX, MSGL_V, "Demuxer info %s set to unchanged value %s\n", opt, param);
1270                 return 0;
1271             }
1272             mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_DemuxerInfoChanged, opt,
1273                    param);
1274             free(info[2 * n + 1]);
1275             info[2 * n + 1] = strdup(param);
1276             return 0;
1277         }
1278     }
1279
1280     info = demuxer->info = (char **) realloc(info,
1281                                              (2 * (n + 2)) * sizeof(char *));
1282     info[2 * n] = strdup(opt);
1283     info[2 * n + 1] = strdup(param);
1284     memset(&info[2 * (n + 1)], 0, 2 * sizeof(char *));
1285
1286     return 1;
1287 }
1288
1289 int demux_info_print(demuxer_t *demuxer)
1290 {
1291     char **info = demuxer->info;
1292     int n;
1293
1294     if (!info)
1295         return 0;
1296
1297     mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_ClipInfo);
1298     for (n = 0; info[2 * n] != NULL; n++) {
1299         mp_msg(MSGT_DEMUX, MSGL_INFO, " %s: %s\n", info[2 * n],
1300                info[2 * n + 1]);
1301         mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CLIP_INFO_NAME%d=%s\n", n,
1302                info[2 * n]);
1303         mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CLIP_INFO_VALUE%d=%s\n", n,
1304                info[2 * n + 1]);
1305     }
1306     mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CLIP_INFO_N=%d\n", n);
1307
1308     return 0;
1309 }
1310
1311 char *demux_info_get(demuxer_t *demuxer, const char *opt)
1312 {
1313     int i;
1314     char **info = demuxer->info;
1315
1316     for (i = 0; info && info[2 * i] != NULL; i++) {
1317         if (!strcasecmp(opt, info[2 * i]))
1318             return info[2 * i + 1];
1319     }
1320
1321     return NULL;
1322 }
1323
1324 int demux_control(demuxer_t *demuxer, int cmd, void *arg)
1325 {
1326
1327     if (demuxer->desc->control)
1328         return demuxer->desc->control(demuxer, cmd, arg);
1329
1330     return DEMUXER_CTRL_NOTIMPL;
1331 }
1332
1333
1334
1335 double demuxer_get_time_length(demuxer_t *demuxer)
1336 {
1337     double get_time_ans;
1338     sh_video_t *sh_video = demuxer->video->sh;
1339     sh_audio_t *sh_audio = demuxer->audio->sh;
1340     // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
1341     if (demux_control
1342         (demuxer, DEMUXER_CTRL_GET_TIME_LENGTH, (void *) &get_time_ans) <= 0) {
1343         if (sh_video && sh_video->i_bps && sh_audio && sh_audio->i_bps)
1344             get_time_ans = (double) (demuxer->movi_end -
1345                                      demuxer->movi_start) / (sh_video->i_bps +
1346                                                              sh_audio->i_bps);
1347         else if (sh_video && sh_video->i_bps)
1348             get_time_ans = (double) (demuxer->movi_end -
1349                                      demuxer->movi_start) / sh_video->i_bps;
1350         else if (sh_audio && sh_audio->i_bps)
1351             get_time_ans = (double) (demuxer->movi_end -
1352                                      demuxer->movi_start) / sh_audio->i_bps;
1353         else
1354             get_time_ans = 0;
1355     }
1356     return get_time_ans;
1357 }
1358
1359 /**
1360  * \brief demuxer_get_current_time() returns the time of the current play in three possible ways:
1361  *        either when the stream reader satisfies STREAM_CTRL_GET_CURRENT_TIME (e.g. dvd)
1362  *        or using sh_video->pts when the former method fails
1363  *        0 otherwise
1364  * \return the current play time
1365  */
1366 int demuxer_get_current_time(demuxer_t *demuxer)
1367 {
1368     double get_time_ans = 0;
1369     sh_video_t *sh_video = demuxer->video->sh;
1370     if (demuxer->stream_pts != MP_NOPTS_VALUE)
1371         get_time_ans = demuxer->stream_pts;
1372     else if (sh_video)
1373         get_time_ans = sh_video->pts;
1374     return (int) get_time_ans;
1375 }
1376
1377 int demuxer_get_percent_pos(demuxer_t *demuxer)
1378 {
1379     int ans = 0;
1380     int res = demux_control(demuxer, DEMUXER_CTRL_GET_PERCENT_POS, &ans);
1381     int len = (demuxer->movi_end - demuxer->movi_start) / 100;
1382     if (res <= 0) {
1383         off_t pos = demuxer->filepos > 0 ? demuxer->filepos : stream_tell(demuxer->stream);
1384         if (len > 0)
1385             ans = (pos - demuxer->movi_start) / len;
1386         else
1387             ans = 0;
1388     }
1389     if (ans < 0)
1390         ans = 0;
1391     if (ans > 100)
1392         ans = 100;
1393     return ans;
1394 }
1395
1396 int demuxer_switch_audio(demuxer_t *demuxer, int index)
1397 {
1398     int res = demux_control(demuxer, DEMUXER_CTRL_SWITCH_AUDIO, &index);
1399     if (res == DEMUXER_CTRL_NOTIMPL)
1400         index = demuxer->audio->id;
1401     if (demuxer->audio->id >= 0)
1402         demuxer->audio->sh = demuxer->a_streams[demuxer->audio->id];
1403     else
1404         demuxer->audio->sh = NULL;
1405     return index;
1406 }
1407
1408 int demuxer_switch_video(demuxer_t *demuxer, int index)
1409 {
1410     int res = demux_control(demuxer, DEMUXER_CTRL_SWITCH_VIDEO, &index);
1411     if (res == DEMUXER_CTRL_NOTIMPL)
1412         index = demuxer->video->id;
1413     if (demuxer->video->id >= 0)
1414         demuxer->video->sh = demuxer->v_streams[demuxer->video->id];
1415     else
1416         demuxer->video->sh = NULL;
1417     return index;
1418 }
1419
1420 int demuxer_add_attachment(demuxer_t *demuxer, const char *name,
1421                            const char *type, const void *data, size_t size)
1422 {
1423     if (!(demuxer->num_attachments & 31))
1424         demuxer->attachments = realloc(demuxer->attachments,
1425                 (demuxer->num_attachments + 32) * sizeof(demux_attachment_t));
1426
1427     demuxer->attachments[demuxer->num_attachments].name = strdup(name);
1428     demuxer->attachments[demuxer->num_attachments].type = strdup(type);
1429     demuxer->attachments[demuxer->num_attachments].data = malloc(size);
1430     memcpy(demuxer->attachments[demuxer->num_attachments].data, data, size);
1431     demuxer->attachments[demuxer->num_attachments].data_size = size;
1432
1433     return demuxer->num_attachments++;
1434 }
1435
1436 int demuxer_add_chapter(demuxer_t *demuxer, const char *name, uint64_t start,
1437                         uint64_t end)
1438 {
1439     if (demuxer->chapters == NULL)
1440         demuxer->chapters = malloc(32 * sizeof(*demuxer->chapters));
1441     else if (!(demuxer->num_chapters % 32))
1442         demuxer->chapters = realloc(demuxer->chapters,
1443                                     (demuxer->num_chapters + 32) *
1444                                         sizeof(*demuxer->chapters));
1445
1446     demuxer->chapters[demuxer->num_chapters].start = start;
1447     demuxer->chapters[demuxer->num_chapters].end = end;
1448     demuxer->chapters[demuxer->num_chapters].name = strdup(name ? name : MSGTR_Unknown);
1449
1450     mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_ID=%d\n", demuxer->num_chapters);
1451     mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_START=%"PRIu64"\n", demuxer->num_chapters, start);
1452     if (end)
1453         mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_END=%"PRIu64"\n", demuxer->num_chapters, end);
1454     if (name)
1455         mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_CHAPTER_%d_NAME=%s\n", demuxer->num_chapters, name);
1456
1457     return demuxer->num_chapters++;
1458 }
1459
1460 /**
1461  * \brief demuxer_seek_chapter() seeks to a chapter in two possible ways:
1462  *        either using the demuxer->chapters structure set by the demuxer
1463  *        or asking help to the stream layer (e.g. dvd)
1464  * \param chapter - chapter number wished - 0-based
1465  * \param mode 0: relative to current main pts, 1: absolute
1466  * \param seek_pts set by the function to the pts to seek to (if demuxer->chapters is set)
1467  * \param num_chapters number of chapters present (set by this function is param is not null)
1468  * \param chapter_name name of chapter found (set by this function is param is not null)
1469  * \return -1 on error, current chapter if successful
1470  */
1471
1472 int demuxer_seek_chapter(demuxer_t *demuxer, int chapter, int mode,
1473                          float *seek_pts, int *num_chapters,
1474                          char **chapter_name)
1475 {
1476     int ris;
1477     int current, total;
1478     sh_video_t *sh_video = demuxer->video->sh;
1479     sh_audio_t *sh_audio = demuxer->audio->sh;
1480
1481     if (!demuxer->num_chapters || !demuxer->chapters) {
1482         if (!mode) {
1483             ris = stream_control(demuxer->stream,
1484                                  STREAM_CTRL_GET_CURRENT_CHAPTER, &current);
1485             if (ris == STREAM_UNSUPPORTED)
1486                 return -1;
1487             chapter += current;
1488         }
1489
1490         demux_flush(demuxer);
1491
1492         ris = stream_control(demuxer->stream, STREAM_CTRL_SEEK_TO_CHAPTER,
1493                              &chapter);
1494         if (ris != STREAM_UNSUPPORTED)
1495             demux_control(demuxer, DEMUXER_CTRL_RESYNC, NULL);
1496         if (sh_video) {
1497             ds_fill_buffer(demuxer->video);
1498             resync_video_stream(sh_video);
1499         }
1500
1501         if (sh_audio) {
1502             ds_fill_buffer(demuxer->audio);
1503             resync_audio_stream(sh_audio);
1504         }
1505         // exit status may be ok, but main() doesn't have to seek itself
1506         // (because e.g. dvds depend on sectors, not on pts)
1507         *seek_pts = -1.0;
1508
1509         if (num_chapters) {
1510             if (stream_control(demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS,
1511                                num_chapters) == STREAM_UNSUPPORTED)
1512                 *num_chapters = 0;
1513         }
1514
1515         if (chapter_name) {
1516             *chapter_name = NULL;
1517             if (num_chapters && *num_chapters) {
1518                 char *tmp = malloc(16);
1519                 if (tmp) {
1520                     sprintf(tmp, " of %3d", *num_chapters);
1521                     *chapter_name = tmp;
1522                 }
1523             }
1524         }
1525
1526         return ris != STREAM_UNSUPPORTED ? chapter : -1;
1527     } else {  // chapters structure is set in the demuxer
1528         total = demuxer->num_chapters;
1529
1530         if (mode == 1)  //absolute seeking
1531             current = chapter;
1532         else {          //relative seeking
1533             uint64_t now;
1534             now = (sh_video ? sh_video->pts : (sh_audio ? sh_audio->pts : 0.))
1535                   * 1000 + .5;
1536
1537             for (current = total - 1; current >= 0; --current) {
1538                 demux_chapter_t *chapter = demuxer->chapters + current;
1539                 if (chapter->start <= now)
1540                     break;
1541             }
1542             current += chapter;
1543         }
1544
1545         if (current >= total)
1546             return -1;
1547         if (current < 0)
1548             current = 0;
1549
1550         *seek_pts = demuxer->chapters[current].start / 1000.0;
1551
1552         if (num_chapters)
1553             *num_chapters = demuxer->num_chapters;
1554
1555         if (chapter_name) {
1556             if (demuxer->chapters[current].name)
1557                 *chapter_name = strdup(demuxer->chapters[current].name);
1558             else
1559                 *chapter_name = NULL;
1560         }
1561
1562         return current;
1563     }
1564 }
1565
1566 int demuxer_get_current_chapter(demuxer_t *demuxer)
1567 {
1568     int chapter = -1;
1569     if (!demuxer->num_chapters || !demuxer->chapters) {
1570         if (stream_control(demuxer->stream, STREAM_CTRL_GET_CURRENT_CHAPTER,
1571                            &chapter) == STREAM_UNSUPPORTED)
1572             chapter = -1;
1573     } else {
1574         sh_video_t *sh_video = demuxer->video->sh;
1575         sh_audio_t *sh_audio = demuxer->audio->sh;
1576         uint64_t now;
1577         now = (sh_video ? sh_video->pts : (sh_audio ? sh_audio->pts : 0))
1578               * 1000 + 0.5;
1579         for (chapter = demuxer->num_chapters - 1; chapter >= 0; --chapter) {
1580             if (demuxer->chapters[chapter].start <= now)
1581                 break;
1582         }
1583     }
1584     return chapter;
1585 }
1586
1587 char *demuxer_chapter_name(demuxer_t *demuxer, int chapter)
1588 {
1589     if (demuxer->num_chapters && demuxer->chapters) {
1590         if (chapter >= 0 && chapter < demuxer->num_chapters
1591             && demuxer->chapters[chapter].name)
1592             return strdup(demuxer->chapters[chapter].name);
1593     }
1594     return NULL;
1595 }
1596
1597 char *demuxer_chapter_display_name(demuxer_t *demuxer, int chapter)
1598 {
1599     char *chapter_name = demuxer_chapter_name(demuxer, chapter);
1600     if (chapter_name) {
1601         char *tmp = malloc(strlen(chapter_name) + 14);
1602         snprintf(tmp, 63, "(%d) %s", chapter + 1, chapter_name);
1603         free(chapter_name);
1604         return tmp;
1605     } else {
1606         int chapter_num = demuxer_chapter_count(demuxer);
1607         char tmp[30];
1608         if (chapter_num <= 0)
1609             sprintf(tmp, "(%d)", chapter + 1);
1610         else
1611             sprintf(tmp, "(%d) of %d", chapter + 1, chapter_num);
1612         return strdup(tmp);
1613     }
1614 }
1615
1616 float demuxer_chapter_time(demuxer_t *demuxer, int chapter, float *end)
1617 {
1618     if (demuxer->num_chapters && demuxer->chapters && chapter >= 0
1619         && chapter < demuxer->num_chapters) {
1620         if (end)
1621             *end = demuxer->chapters[chapter].end / 1000.0;
1622         return demuxer->chapters[chapter].start / 1000.0;
1623     }
1624     return -1.0;
1625 }
1626
1627 int demuxer_chapter_count(demuxer_t *demuxer)
1628 {
1629     if (!demuxer->num_chapters || !demuxer->chapters) {
1630         int num_chapters = 0;
1631         if (stream_control(demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS,
1632                            &num_chapters) == STREAM_UNSUPPORTED)
1633             num_chapters = 0;
1634         return num_chapters;
1635     } else
1636         return demuxer->num_chapters;
1637 }
1638
1639 int demuxer_angles_count(demuxer_t *demuxer)
1640 {
1641     int ris, angles = -1;
1642
1643     ris = stream_control(demuxer->stream, STREAM_CTRL_GET_NUM_ANGLES, &angles);
1644     if (ris == STREAM_UNSUPPORTED)
1645         return -1;
1646     return angles;
1647 }
1648
1649 int demuxer_get_current_angle(demuxer_t *demuxer)
1650 {
1651     int ris, curr_angle = -1;
1652     ris = stream_control(demuxer->stream, STREAM_CTRL_GET_ANGLE, &curr_angle);
1653     if (ris == STREAM_UNSUPPORTED)
1654         return -1;
1655     return curr_angle;
1656 }
1657
1658
1659 int demuxer_set_angle(demuxer_t *demuxer, int angle)
1660 {
1661     int ris, angles = -1;
1662     sh_video_t *sh_video = demuxer->video->sh;
1663     sh_audio_t *sh_audio = demuxer->audio->sh;
1664
1665     angles = demuxer_angles_count(demuxer);
1666     if ((angles < 1) || (angle > angles))
1667         return -1;
1668
1669     demux_flush(demuxer);
1670
1671     ris = stream_control(demuxer->stream, STREAM_CTRL_SET_ANGLE, &angle);
1672     if (ris == STREAM_UNSUPPORTED)
1673         return -1;
1674
1675     demux_control(demuxer, DEMUXER_CTRL_RESYNC, NULL);
1676     if (sh_video) {
1677         ds_fill_buffer(demuxer->video);
1678         resync_video_stream(sh_video);
1679     }
1680
1681     if (sh_audio) {
1682         ds_fill_buffer(demuxer->audio);
1683         resync_audio_stream(sh_audio);
1684     }
1685
1686     return angle;
1687 }
1688
1689 int demuxer_audio_track_by_lang(demuxer_t *d, char *lang)
1690 {
1691     int i, len;
1692     lang += strspn(lang, ",");
1693     while ((len = strcspn(lang, ",")) > 0) {
1694         for (i = 0; i < MAX_A_STREAMS; ++i) {
1695             sh_audio_t *sh = d->a_streams[i];
1696             if (sh && sh->lang && strncmp(sh->lang, lang, len) == 0)
1697                 return sh->aid;
1698         }
1699         lang += len;
1700         lang += strspn(lang, ",");
1701     }
1702     return -1;
1703 }
1704
1705 int demuxer_sub_track_by_lang(demuxer_t *d, char *lang)
1706 {
1707     int i, len;
1708     lang += strspn(lang, ",");
1709     while ((len = strcspn(lang, ",")) > 0) {
1710         for (i = 0; i < MAX_S_STREAMS; ++i) {
1711             sh_sub_t *sh = d->s_streams[i];
1712             if (sh && sh->lang && strncmp(sh->lang, lang, len) == 0)
1713                 return sh->sid;
1714         }
1715         lang += len;
1716         lang += strspn(lang, ",");
1717     }
1718     return -1;
1719 }
1720
1721 int demuxer_default_audio_track(demuxer_t *d)
1722 {
1723     int i;
1724     for (i = 0; i < MAX_A_STREAMS; ++i) {
1725         sh_audio_t *sh = d->a_streams[i];
1726         if (sh && sh->default_track)
1727             return sh->aid;
1728     }
1729     for (i = 0; i < MAX_A_STREAMS; ++i) {
1730         sh_audio_t *sh = d->a_streams[i];
1731         if (sh)
1732             return sh->aid;
1733     }
1734     return -1;
1735 }
1736
1737 int demuxer_default_sub_track(demuxer_t *d)
1738 {
1739     int i;
1740     for (i = 0; i < MAX_S_STREAMS; ++i) {
1741         sh_sub_t *sh = d->s_streams[i];
1742         if (sh && sh->default_track)
1743             return sh->sid;
1744     }
1745     return -1;
1746 }