Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ 8a6c7a52

History | View | Annotate | Download (104 KB)

1
/*
2
 * various utility functions for use within FFmpeg
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21
#include "avformat.h"
22
#include "internal.h"
23
#include "libavcodec/opt.h"
24
#include "metadata.h"
25
#include "libavutil/avstring.h"
26
#include "riff.h"
27
#include <sys/time.h>
28
#include <time.h>
29
#include <strings.h>
30

    
31
#undef NDEBUG
32
#include <assert.h>
33

    
34
/**
35
 * @file libavformat/utils.c
36
 * various utility functions for use within FFmpeg
37
 */
38

    
39
unsigned avformat_version(void)
40
{
41
    return LIBAVFORMAT_VERSION_INT;
42
}
43

    
44
/* fraction handling */
45

    
46
/**
47
 * f = val + (num / den) + 0.5.
48
 *
49
 * 'num' is normalized so that it is such as 0 <= num < den.
50
 *
51
 * @param f fractional number
52
 * @param val integer value
53
 * @param num must be >= 0
54
 * @param den must be >= 1
55
 */
56
static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
57
{
58
    num += (den >> 1);
59
    if (num >= den) {
60
        val += num / den;
61
        num = num % den;
62
    }
63
    f->val = val;
64
    f->num = num;
65
    f->den = den;
66
}
67

    
68
/**
69
 * Fractional addition to f: f = f + (incr / f->den).
70
 *
71
 * @param f fractional number
72
 * @param incr increment, can be positive or negative
73
 */
74
static void av_frac_add(AVFrac *f, int64_t incr)
75
{
76
    int64_t num, den;
77

    
78
    num = f->num + incr;
79
    den = f->den;
80
    if (num < 0) {
81
        f->val += num / den;
82
        num = num % den;
83
        if (num < 0) {
84
            num += den;
85
            f->val--;
86
        }
87
    } else if (num >= den) {
88
        f->val += num / den;
89
        num = num % den;
90
    }
91
    f->num = num;
92
}
93

    
94
/** head of registered input format linked list */
95
AVInputFormat *first_iformat = NULL;
96
/** head of registered output format linked list */
97
AVOutputFormat *first_oformat = NULL;
98

    
99
AVInputFormat  *av_iformat_next(AVInputFormat  *f)
100
{
101
    if(f) return f->next;
102
    else  return first_iformat;
103
}
104

    
105
AVOutputFormat *av_oformat_next(AVOutputFormat *f)
106
{
107
    if(f) return f->next;
108
    else  return first_oformat;
109
}
110

    
111
void av_register_input_format(AVInputFormat *format)
112
{
113
    AVInputFormat **p;
114
    p = &first_iformat;
115
    while (*p != NULL) p = &(*p)->next;
116
    *p = format;
117
    format->next = NULL;
118
}
119

    
120
void av_register_output_format(AVOutputFormat *format)
121
{
122
    AVOutputFormat **p;
123
    p = &first_oformat;
124
    while (*p != NULL) p = &(*p)->next;
125
    *p = format;
126
    format->next = NULL;
127
}
128

    
129
int match_ext(const char *filename, const char *extensions)
130
{
131
    const char *ext, *p;
132
    char ext1[32], *q;
133

    
134
    if(!filename)
135
        return 0;
136

    
137
    ext = strrchr(filename, '.');
138
    if (ext) {
139
        ext++;
140
        p = extensions;
141
        for(;;) {
142
            q = ext1;
143
            while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
144
                *q++ = *p++;
145
            *q = '\0';
146
            if (!strcasecmp(ext1, ext))
147
                return 1;
148
            if (*p == '\0')
149
                break;
150
            p++;
151
        }
152
    }
153
    return 0;
154
}
155

    
156
static int match_format(const char *name, const char *names)
157
{
158
    const char *p;
159
    int len, namelen;
160

    
161
    if (!name || !names)
162
        return 0;
163

    
164
    namelen = strlen(name);
165
    while ((p = strchr(names, ','))) {
166
        len = FFMAX(p - names, namelen);
167
        if (!strncasecmp(name, names, len))
168
            return 1;
169
        names = p+1;
170
    }
171
    return !strcasecmp(name, names);
172
}
173

    
174
AVOutputFormat *guess_format(const char *short_name, const char *filename,
175
                             const char *mime_type)
176
{
177
    AVOutputFormat *fmt, *fmt_found;
178
    int score_max, score;
179

    
180
    /* specific test for image sequences */
181
#if CONFIG_IMAGE2_MUXER
182
    if (!short_name && filename &&
183
        av_filename_number_test(filename) &&
184
        av_guess_image2_codec(filename) != CODEC_ID_NONE) {
185
        return guess_format("image2", NULL, NULL);
186
    }
187
#endif
188
    /* Find the proper file type. */
189
    fmt_found = NULL;
190
    score_max = 0;
191
    fmt = first_oformat;
192
    while (fmt != NULL) {
193
        score = 0;
194
        if (fmt->name && short_name && !strcmp(fmt->name, short_name))
195
            score += 100;
196
        if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
197
            score += 10;
198
        if (filename && fmt->extensions &&
199
            match_ext(filename, fmt->extensions)) {
200
            score += 5;
201
        }
202
        if (score > score_max) {
203
            score_max = score;
204
            fmt_found = fmt;
205
        }
206
        fmt = fmt->next;
207
    }
208
    return fmt_found;
209
}
210

    
211
AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
212
                             const char *mime_type)
213
{
214
    AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
215

    
216
    if (fmt) {
217
        AVOutputFormat *stream_fmt;
218
        char stream_format_name[64];
219

    
220
        snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
221
        stream_fmt = guess_format(stream_format_name, NULL, NULL);
222

    
223
        if (stream_fmt)
224
            fmt = stream_fmt;
225
    }
226

    
227
    return fmt;
228
}
229

    
230
enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
231
                            const char *filename, const char *mime_type, enum CodecType type){
232
    if(type == CODEC_TYPE_VIDEO){
233
        enum CodecID codec_id= CODEC_ID_NONE;
234

    
235
#if CONFIG_IMAGE2_MUXER
236
        if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
237
            codec_id= av_guess_image2_codec(filename);
238
        }
239
#endif
240
        if(codec_id == CODEC_ID_NONE)
241
            codec_id= fmt->video_codec;
242
        return codec_id;
243
    }else if(type == CODEC_TYPE_AUDIO)
244
        return fmt->audio_codec;
245
    else
246
        return CODEC_ID_NONE;
247
}
248

    
249
AVInputFormat *av_find_input_format(const char *short_name)
250
{
251
    AVInputFormat *fmt;
252
    for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
253
        if (match_format(short_name, fmt->name))
254
            return fmt;
255
    }
256
    return NULL;
257
}
258

    
259
/* memory handling */
260

    
261

    
262
int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
263
{
264
    int ret= av_new_packet(pkt, size);
265

    
266
    if(ret<0)
267
        return ret;
268

    
269
    pkt->pos= url_ftell(s);
270

    
271
    ret= get_buffer(s, pkt->data, size);
272
    if(ret<=0)
273
        av_free_packet(pkt);
274
    else
275
        av_shrink_packet(pkt, ret);
276

    
277
    return ret;
278
}
279

    
280

    
281
int av_filename_number_test(const char *filename)
282
{
283
    char buf[1024];
284
    return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
285
}
286

    
287
static AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
288
{
289
    AVInputFormat *fmt1, *fmt;
290
    int score;
291

    
292
    fmt = NULL;
293
    for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
294
        if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
295
            continue;
296
        score = 0;
297
        if (fmt1->read_probe) {
298
            score = fmt1->read_probe(pd);
299
        } else if (fmt1->extensions) {
300
            if (match_ext(pd->filename, fmt1->extensions)) {
301
                score = 50;
302
            }
303
        }
304
        if (score > *score_max) {
305
            *score_max = score;
306
            fmt = fmt1;
307
        }else if (score == *score_max)
308
            fmt = NULL;
309
    }
310
    return fmt;
311
}
312

    
313
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
314
    int score=0;
315
    return av_probe_input_format2(pd, is_opened, &score);
316
}
317

    
318
static int set_codec_from_probe_data(AVStream *st, AVProbeData *pd, int score)
319
{
320
    AVInputFormat *fmt;
321
    fmt = av_probe_input_format2(pd, 1, &score);
322

    
323
    if (fmt) {
324
        if (!strcmp(fmt->name, "mp3")) {
325
            st->codec->codec_id = CODEC_ID_MP3;
326
            st->codec->codec_type = CODEC_TYPE_AUDIO;
327
        } else if (!strcmp(fmt->name, "ac3")) {
328
            st->codec->codec_id = CODEC_ID_AC3;
329
            st->codec->codec_type = CODEC_TYPE_AUDIO;
330
        } else if (!strcmp(fmt->name, "mpegvideo")) {
331
            st->codec->codec_id = CODEC_ID_MPEG2VIDEO;
332
            st->codec->codec_type = CODEC_TYPE_VIDEO;
333
        } else if (!strcmp(fmt->name, "m4v")) {
334
            st->codec->codec_id = CODEC_ID_MPEG4;
335
            st->codec->codec_type = CODEC_TYPE_VIDEO;
336
        } else if (!strcmp(fmt->name, "h264")) {
337
            st->codec->codec_id = CODEC_ID_H264;
338
            st->codec->codec_type = CODEC_TYPE_VIDEO;
339
        } else if (!strcmp(fmt->name, "dts")) {
340
            st->codec->codec_id = CODEC_ID_DTS;
341
            st->codec->codec_type = CODEC_TYPE_AUDIO;
342
        }
343
    }
344
    return !!fmt;
345
}
346

    
347
/************************************************************/
348
/* input media file */
349

    
350
/**
351
 * Open a media file from an IO stream. 'fmt' must be specified.
352
 */
353
int av_open_input_stream(AVFormatContext **ic_ptr,
354
                         ByteIOContext *pb, const char *filename,
355
                         AVInputFormat *fmt, AVFormatParameters *ap)
356
{
357
    int err;
358
    AVFormatContext *ic;
359
    AVFormatParameters default_ap;
360

    
361
    if(!ap){
362
        ap=&default_ap;
363
        memset(ap, 0, sizeof(default_ap));
364
    }
365

    
366
    if(!ap->prealloced_context)
367
        ic = avformat_alloc_context();
368
    else
369
        ic = *ic_ptr;
370
    if (!ic) {
371
        err = AVERROR(ENOMEM);
372
        goto fail;
373
    }
374
    ic->iformat = fmt;
375
    ic->pb = pb;
376
    ic->duration = AV_NOPTS_VALUE;
377
    ic->start_time = AV_NOPTS_VALUE;
378
    av_strlcpy(ic->filename, filename, sizeof(ic->filename));
379

    
380
    /* allocate private data */
381
    if (fmt->priv_data_size > 0) {
382
        ic->priv_data = av_mallocz(fmt->priv_data_size);
383
        if (!ic->priv_data) {
384
            err = AVERROR(ENOMEM);
385
            goto fail;
386
        }
387
    } else {
388
        ic->priv_data = NULL;
389
    }
390

    
391
    if (ic->iformat->read_header) {
392
        err = ic->iformat->read_header(ic, ap);
393
        if (err < 0)
394
            goto fail;
395
    }
396

    
397
    if (pb && !ic->data_offset)
398
        ic->data_offset = url_ftell(ic->pb);
399

    
400
#if LIBAVFORMAT_VERSION_MAJOR < 53
401
    ff_metadata_demux_compat(ic);
402
#endif
403

    
404
    ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
405

    
406
    *ic_ptr = ic;
407
    return 0;
408
 fail:
409
    if (ic) {
410
        int i;
411
        av_freep(&ic->priv_data);
412
        for(i=0;i<ic->nb_streams;i++) {
413
            AVStream *st = ic->streams[i];
414
            if (st) {
415
                av_free(st->priv_data);
416
                av_free(st->codec->extradata);
417
            }
418
            av_free(st);
419
        }
420
    }
421
    av_free(ic);
422
    *ic_ptr = NULL;
423
    return err;
424
}
425

    
426
/** size of probe buffer, for guessing file type from file contents */
427
#define PROBE_BUF_MIN 2048
428
#define PROBE_BUF_MAX (1<<20)
429

    
430
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
431
                       AVInputFormat *fmt,
432
                       int buf_size,
433
                       AVFormatParameters *ap)
434
{
435
    int err, probe_size;
436
    AVProbeData probe_data, *pd = &probe_data;
437
    ByteIOContext *pb = NULL;
438

    
439
    pd->filename = "";
440
    if (filename)
441
        pd->filename = filename;
442
    pd->buf = NULL;
443
    pd->buf_size = 0;
444

    
445
    if (!fmt) {
446
        /* guess format if no file can be opened */
447
        fmt = av_probe_input_format(pd, 0);
448
    }
449

    
450
    /* Do not open file if the format does not need it. XXX: specific
451
       hack needed to handle RTSP/TCP */
452
    if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
453
        /* if no file needed do not try to open one */
454
        if ((err=url_fopen(&pb, filename, URL_RDONLY)) < 0) {
455
            goto fail;
456
        }
457
        if (buf_size > 0) {
458
            url_setbufsize(pb, buf_size);
459
        }
460

    
461
        for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
462
            int score= probe_size < PROBE_BUF_MAX ? AVPROBE_SCORE_MAX/4 : 0;
463
            /* read probe data */
464
            pd->buf= av_realloc(pd->buf, probe_size + AVPROBE_PADDING_SIZE);
465
            pd->buf_size = get_buffer(pb, pd->buf, probe_size);
466
            memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
467
            if (url_fseek(pb, 0, SEEK_SET) < 0) {
468
                url_fclose(pb);
469
                if (url_fopen(&pb, filename, URL_RDONLY) < 0) {
470
                    pb = NULL;
471
                    err = AVERROR(EIO);
472
                    goto fail;
473
                }
474
            }
475
            /* guess file format */
476
            fmt = av_probe_input_format2(pd, 1, &score);
477
        }
478
        av_freep(&pd->buf);
479
    }
480

    
481
    /* if still no format found, error */
482
    if (!fmt) {
483
        err = AVERROR_NOFMT;
484
        goto fail;
485
    }
486

    
487
    /* check filename in case an image number is expected */
488
    if (fmt->flags & AVFMT_NEEDNUMBER) {
489
        if (!av_filename_number_test(filename)) {
490
            err = AVERROR_NUMEXPECTED;
491
            goto fail;
492
        }
493
    }
494
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
495
    if (err)
496
        goto fail;
497
    return 0;
498
 fail:
499
    av_freep(&pd->buf);
500
    if (pb)
501
        url_fclose(pb);
502
    if (ap && ap->prealloced_context)
503
        av_free(*ic_ptr);
504
    *ic_ptr = NULL;
505
    return err;
506

    
507
}
508

    
509
/*******************************************************/
510

    
511
static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
512
                               AVPacketList **plast_pktl){
513
    AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
514
    if (!pktl)
515
        return NULL;
516

    
517
    if (*packet_buffer)
518
        (*plast_pktl)->next = pktl;
519
    else
520
        *packet_buffer = pktl;
521

    
522
    /* add the packet in the buffered packet list */
523
    *plast_pktl = pktl;
524
    pktl->pkt= *pkt;
525
    return &pktl->pkt;
526
}
527

    
528
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
529
{
530
    int ret, i;
531
    AVStream *st;
532

    
533
    for(;;){
534
        AVPacketList *pktl = s->raw_packet_buffer;
535

    
536
        if (pktl) {
537
            *pkt = pktl->pkt;
538
            if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||
539
               !s->streams[pkt->stream_index]->probe_packets ||
540
               s->raw_packet_buffer_remaining_size < pkt->size){
541
                AVProbeData *pd = &s->streams[pkt->stream_index]->probe_data;
542
                av_freep(&pd->buf);
543
                pd->buf_size = 0;
544
                s->raw_packet_buffer = pktl->next;
545
                s->raw_packet_buffer_remaining_size += pkt->size;
546
                av_free(pktl);
547
                return 0;
548
            }
549
        }
550

    
551
        av_init_packet(pkt);
552
        ret= s->iformat->read_packet(s, pkt);
553
        if (ret < 0) {
554
            if (!pktl || ret == AVERROR(EAGAIN))
555
                return ret;
556
            for (i = 0; i < s->nb_streams; i++)
557
                s->streams[i]->probe_packets = 0;
558
            continue;
559
        }
560
        st= s->streams[pkt->stream_index];
561

    
562
        switch(st->codec->codec_type){
563
        case CODEC_TYPE_VIDEO:
564
            if(s->video_codec_id)   st->codec->codec_id= s->video_codec_id;
565
            break;
566
        case CODEC_TYPE_AUDIO:
567
            if(s->audio_codec_id)   st->codec->codec_id= s->audio_codec_id;
568
            break;
569
        case CODEC_TYPE_SUBTITLE:
570
            if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
571
            break;
572
        }
573

    
574
        if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
575
                     !st->probe_packets))
576
            return ret;
577

    
578
        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
579
        s->raw_packet_buffer_remaining_size -= pkt->size;
580

    
581
        if(st->codec->codec_id == CODEC_ID_PROBE){
582
            AVProbeData *pd = &st->probe_data;
583

    
584
            --st->probe_packets;
585

    
586
            pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
587
            memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
588
            pd->buf_size += pkt->size;
589
            memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
590

    
591
            if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
592
                set_codec_from_probe_data(st, pd, 1);
593
                if(st->codec->codec_id != CODEC_ID_PROBE){
594
                    pd->buf_size=0;
595
                    av_freep(&pd->buf);
596
                }
597
            }
598
        }
599
    }
600
}
601

    
602
/**********************************************************/
603

    
604
/**
605
 * Get the number of samples of an audio frame. Return -1 on error.
606
 */
607
static int get_audio_frame_size(AVCodecContext *enc, int size)
608
{
609
    int frame_size;
610

    
611
    if(enc->codec_id == CODEC_ID_VORBIS)
612
        return -1;
613

    
614
    if (enc->frame_size <= 1) {
615
        int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
616

    
617
        if (bits_per_sample) {
618
            if (enc->channels == 0)
619
                return -1;
620
            frame_size = (size << 3) / (bits_per_sample * enc->channels);
621
        } else {
622
            /* used for example by ADPCM codecs */
623
            if (enc->bit_rate == 0)
624
                return -1;
625
            frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
626
        }
627
    } else {
628
        frame_size = enc->frame_size;
629
    }
630
    return frame_size;
631
}
632

    
633

    
634
/**
635
 * Return the frame duration in seconds. Return 0 if not available.
636
 */
637
static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
638
                                   AVCodecParserContext *pc, AVPacket *pkt)
639
{
640
    int frame_size;
641

    
642
    *pnum = 0;
643
    *pden = 0;
644
    switch(st->codec->codec_type) {
645
    case CODEC_TYPE_VIDEO:
646
        if(st->time_base.num*1000LL > st->time_base.den){
647
            *pnum = st->time_base.num;
648
            *pden = st->time_base.den;
649
        }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
650
            *pnum = st->codec->time_base.num;
651
            *pden = st->codec->time_base.den;
652
            if (pc && pc->repeat_pict) {
653
                *pnum = (*pnum) * (1 + pc->repeat_pict);
654
            }
655
        }
656
        break;
657
    case CODEC_TYPE_AUDIO:
658
        frame_size = get_audio_frame_size(st->codec, pkt->size);
659
        if (frame_size < 0)
660
            break;
661
        *pnum = frame_size;
662
        *pden = st->codec->sample_rate;
663
        break;
664
    default:
665
        break;
666
    }
667
}
668

    
669
static int is_intra_only(AVCodecContext *enc){
670
    if(enc->codec_type == CODEC_TYPE_AUDIO){
671
        return 1;
672
    }else if(enc->codec_type == CODEC_TYPE_VIDEO){
673
        switch(enc->codec_id){
674
        case CODEC_ID_MJPEG:
675
        case CODEC_ID_MJPEGB:
676
        case CODEC_ID_LJPEG:
677
        case CODEC_ID_RAWVIDEO:
678
        case CODEC_ID_DVVIDEO:
679
        case CODEC_ID_HUFFYUV:
680
        case CODEC_ID_FFVHUFF:
681
        case CODEC_ID_ASV1:
682
        case CODEC_ID_ASV2:
683
        case CODEC_ID_VCR1:
684
        case CODEC_ID_DNXHD:
685
        case CODEC_ID_JPEG2000:
686
            return 1;
687
        default: break;
688
        }
689
    }
690
    return 0;
691
}
692

    
693
static void update_initial_timestamps(AVFormatContext *s, int stream_index,
694
                                      int64_t dts, int64_t pts)
695
{
696
    AVStream *st= s->streams[stream_index];
697
    AVPacketList *pktl= s->packet_buffer;
698

    
699
    if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
700
        return;
701

    
702
    st->first_dts= dts - st->cur_dts;
703
    st->cur_dts= dts;
704

    
705
    for(; pktl; pktl= pktl->next){
706
        if(pktl->pkt.stream_index != stream_index)
707
            continue;
708
        //FIXME think more about this check
709
        if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
710
            pktl->pkt.pts += st->first_dts;
711

    
712
        if(pktl->pkt.dts != AV_NOPTS_VALUE)
713
            pktl->pkt.dts += st->first_dts;
714

    
715
        if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
716
            st->start_time= pktl->pkt.pts;
717
    }
718
    if (st->start_time == AV_NOPTS_VALUE)
719
        st->start_time = pts;
720
}
721

    
722
static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
723
{
724
    AVPacketList *pktl= s->packet_buffer;
725
    int64_t cur_dts= 0;
726

    
727
    if(st->first_dts != AV_NOPTS_VALUE){
728
        cur_dts= st->first_dts;
729
        for(; pktl; pktl= pktl->next){
730
            if(pktl->pkt.stream_index == pkt->stream_index){
731
                if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
732
                    break;
733
                cur_dts -= pkt->duration;
734
            }
735
        }
736
        pktl= s->packet_buffer;
737
        st->first_dts = cur_dts;
738
    }else if(st->cur_dts)
739
        return;
740

    
741
    for(; pktl; pktl= pktl->next){
742
        if(pktl->pkt.stream_index != pkt->stream_index)
743
            continue;
744
        if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
745
           && !pktl->pkt.duration){
746
            pktl->pkt.dts= cur_dts;
747
            if(!st->codec->has_b_frames)
748
                pktl->pkt.pts= cur_dts;
749
            cur_dts += pkt->duration;
750
            pktl->pkt.duration= pkt->duration;
751
        }else
752
            break;
753
    }
754
    if(st->first_dts == AV_NOPTS_VALUE)
755
        st->cur_dts= cur_dts;
756
}
757

    
758
static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
759
                               AVCodecParserContext *pc, AVPacket *pkt)
760
{
761
    int num, den, presentation_delayed, delay, i;
762
    int64_t offset;
763

    
764
    if (pc && pc->pict_type == FF_B_TYPE)
765
        st->codec->has_b_frames = 1;
766

    
767
    /* do we have a video B-frame ? */
768
    delay= st->codec->has_b_frames;
769
    presentation_delayed = 0;
770
    /* XXX: need has_b_frame, but cannot get it if the codec is
771
        not initialized */
772
    if (delay &&
773
        pc && pc->pict_type != FF_B_TYPE)
774
        presentation_delayed = 1;
775

    
776
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
777
       /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
778
        pkt->dts -= 1LL<<st->pts_wrap_bits;
779
    }
780

    
781
    // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
782
    // we take the conservative approach and discard both
783
    // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
784
    if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
785
        av_log(s, AV_LOG_WARNING, "invalid dts/pts combination\n");
786
        pkt->dts= pkt->pts= AV_NOPTS_VALUE;
787
    }
788

    
789
    if (pkt->duration == 0) {
790
        compute_frame_duration(&num, &den, st, pc, pkt);
791
        if (den && num) {
792
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
793

    
794
            if(pkt->duration != 0 && s->packet_buffer)
795
                update_initial_durations(s, st, pkt);
796
        }
797
    }
798

    
799
    /* correct timestamps with byte offset if demuxers only have timestamps
800
       on packet boundaries */
801
    if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
802
        /* this will estimate bitrate based on this frame's duration and size */
803
        offset = av_rescale(pc->offset, pkt->duration, pkt->size);
804
        if(pkt->pts != AV_NOPTS_VALUE)
805
            pkt->pts += offset;
806
        if(pkt->dts != AV_NOPTS_VALUE)
807
            pkt->dts += offset;
808
    }
809

    
810
    if (pc && pc->dts_sync_point >= 0) {
811
        // we have synchronization info from the parser
812
        int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
813
        if (den > 0) {
814
            int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
815
            if (pkt->dts != AV_NOPTS_VALUE) {
816
                // got DTS from the stream, update reference timestamp
817
                st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
818
                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
819
            } else if (st->reference_dts != AV_NOPTS_VALUE) {
820
                // compute DTS based on reference timestamp
821
                pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
822
                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
823
            }
824
            if (pc->dts_sync_point > 0)
825
                st->reference_dts = pkt->dts; // new reference
826
        }
827
    }
828

    
829
    /* This may be redundant, but it should not hurt. */
830
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
831
        presentation_delayed = 1;
832

    
833
//    av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
834
    /* interpolate PTS and DTS if they are not present */
835
    //We skip H264 currently because delay and has_b_frames are not reliably set
836
    if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){
837
        if (presentation_delayed) {
838
            /* DTS = decompression timestamp */
839
            /* PTS = presentation timestamp */
840
            if (pkt->dts == AV_NOPTS_VALUE)
841
                pkt->dts = st->last_IP_pts;
842
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
843
            if (pkt->dts == AV_NOPTS_VALUE)
844
                pkt->dts = st->cur_dts;
845

    
846
            /* this is tricky: the dts must be incremented by the duration
847
            of the frame we are displaying, i.e. the last I- or P-frame */
848
            if (st->last_IP_duration == 0)
849
                st->last_IP_duration = pkt->duration;
850
            if(pkt->dts != AV_NOPTS_VALUE)
851
                st->cur_dts = pkt->dts + st->last_IP_duration;
852
            st->last_IP_duration  = pkt->duration;
853
            st->last_IP_pts= pkt->pts;
854
            /* cannot compute PTS if not present (we can compute it only
855
            by knowing the future */
856
        } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
857
            if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
858
                int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
859
                int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
860
                if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
861
                    pkt->pts += pkt->duration;
862
    //                av_log(NULL, AV_LOG_DEBUG, "id:%d old:%"PRId64" new:%"PRId64" dur:%d cur:%"PRId64" size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
863
                }
864
            }
865

    
866
            /* presentation is not delayed : PTS and DTS are the same */
867
            if(pkt->pts == AV_NOPTS_VALUE)
868
                pkt->pts = pkt->dts;
869
            update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
870
            if(pkt->pts == AV_NOPTS_VALUE)
871
                pkt->pts = st->cur_dts;
872
            pkt->dts = pkt->pts;
873
            if(pkt->pts != AV_NOPTS_VALUE)
874
                st->cur_dts = pkt->pts + pkt->duration;
875
        }
876
    }
877

    
878
    if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
879
        st->pts_buffer[0]= pkt->pts;
880
        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
881
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
882
        if(pkt->dts == AV_NOPTS_VALUE)
883
            pkt->dts= st->pts_buffer[0];
884
        if(st->codec->codec_id == CODEC_ID_H264){ //we skiped it above so we try here
885
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
886
        }
887
        if(pkt->dts > st->cur_dts)
888
            st->cur_dts = pkt->dts;
889
    }
890

    
891
//    av_log(NULL, AV_LOG_ERROR, "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n", presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
892

    
893
    /* update flags */
894
    if(is_intra_only(st->codec))
895
        pkt->flags |= PKT_FLAG_KEY;
896
    else if (pc) {
897
        pkt->flags = 0;
898
        /* keyframe computation */
899
        if (pc->key_frame == 1)
900
            pkt->flags |= PKT_FLAG_KEY;
901
        else if (pc->key_frame == -1 && pc->pict_type == FF_I_TYPE)
902
            pkt->flags |= PKT_FLAG_KEY;
903
    }
904
    if (pc)
905
        pkt->convergence_duration = pc->convergence_duration;
906
}
907

    
908

    
909
static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
910
{
911
    AVStream *st;
912
    int len, ret, i;
913

    
914
    av_init_packet(pkt);
915

    
916
    for(;;) {
917
        /* select current input stream component */
918
        st = s->cur_st;
919
        if (st) {
920
            if (!st->need_parsing || !st->parser) {
921
                /* no parsing needed: we just output the packet as is */
922
                /* raw data support */
923
                *pkt = st->cur_pkt; st->cur_pkt.data= NULL;
924
                compute_pkt_fields(s, st, NULL, pkt);
925
                s->cur_st = NULL;
926
                if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
927
                    (pkt->flags & PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
928
                    ff_reduce_index(s, st->index);
929
                    av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
930
                }
931
                break;
932
            } else if (st->cur_len > 0 && st->discard < AVDISCARD_ALL) {
933
                len = av_parser_parse2(st->parser, st->codec, &pkt->data, &pkt->size,
934
                                       st->cur_ptr, st->cur_len,
935
                                       st->cur_pkt.pts, st->cur_pkt.dts,
936
                                       st->cur_pkt.pos);
937
                st->cur_pkt.pts = AV_NOPTS_VALUE;
938
                st->cur_pkt.dts = AV_NOPTS_VALUE;
939
                /* increment read pointer */
940
                st->cur_ptr += len;
941
                st->cur_len -= len;
942

    
943
                /* return packet if any */
944
                if (pkt->size) {
945
                got_packet:
946
                    pkt->duration = 0;
947
                    pkt->stream_index = st->index;
948
                    pkt->pts = st->parser->pts;
949
                    pkt->dts = st->parser->dts;
950
                    pkt->pos = st->parser->pos;
951
                    pkt->destruct = NULL;
952
                    compute_pkt_fields(s, st, st->parser, pkt);
953

    
954
                    if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & PKT_FLAG_KEY){
955
                        ff_reduce_index(s, st->index);
956
                        av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
957
                                           0, 0, AVINDEX_KEYFRAME);
958
                    }
959

    
960
                    break;
961
                }
962
            } else {
963
                /* free packet */
964
                av_free_packet(&st->cur_pkt);
965
                s->cur_st = NULL;
966
            }
967
        } else {
968
            AVPacket cur_pkt;
969
            /* read next packet */
970
            ret = av_read_packet(s, &cur_pkt);
971
            if (ret < 0) {
972
                if (ret == AVERROR(EAGAIN))
973
                    return ret;
974
                /* return the last frames, if any */
975
                for(i = 0; i < s->nb_streams; i++) {
976
                    st = s->streams[i];
977
                    if (st->parser && st->need_parsing) {
978
                        av_parser_parse2(st->parser, st->codec,
979
                                        &pkt->data, &pkt->size,
980
                                        NULL, 0,
981
                                        AV_NOPTS_VALUE, AV_NOPTS_VALUE,
982
                                        AV_NOPTS_VALUE);
983
                        if (pkt->size)
984
                            goto got_packet;
985
                    }
986
                }
987
                /* no more packets: really terminate parsing */
988
                return ret;
989
            }
990
            st = s->streams[cur_pkt.stream_index];
991
            st->cur_pkt= cur_pkt;
992

    
993
            if(st->cur_pkt.pts != AV_NOPTS_VALUE &&
994
               st->cur_pkt.dts != AV_NOPTS_VALUE &&
995
               st->cur_pkt.pts < st->cur_pkt.dts){
996
                av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
997
                    st->cur_pkt.stream_index,
998
                    st->cur_pkt.pts,
999
                    st->cur_pkt.dts,
1000
                    st->cur_pkt.size);
1001
//                av_free_packet(&st->cur_pkt);
1002
//                return -1;
1003
            }
1004

    
1005
            if(s->debug & FF_FDEBUG_TS)
1006
                av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d,  flags=%d\n",
1007
                    st->cur_pkt.stream_index,
1008
                    st->cur_pkt.pts,
1009
                    st->cur_pkt.dts,
1010
                    st->cur_pkt.size,
1011
                    st->cur_pkt.flags);
1012

    
1013
            s->cur_st = st;
1014
            st->cur_ptr = st->cur_pkt.data;
1015
            st->cur_len = st->cur_pkt.size;
1016
            if (st->need_parsing && !st->parser) {
1017
                st->parser = av_parser_init(st->codec->codec_id);
1018
                if (!st->parser) {
1019
                    /* no parser available: just output the raw packets */
1020
                    st->need_parsing = AVSTREAM_PARSE_NONE;
1021
                }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
1022
                    st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1023
                }
1024
                if(st->parser && (s->iformat->flags & AVFMT_GENERIC_INDEX)){
1025
                    st->parser->next_frame_offset=
1026
                    st->parser->cur_offset= st->cur_pkt.pos;
1027
                }
1028
            }
1029
        }
1030
    }
1031
    if(s->debug & FF_FDEBUG_TS)
1032
        av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, flags=%d\n",
1033
            pkt->stream_index,
1034
            pkt->pts,
1035
            pkt->dts,
1036
            pkt->size,
1037
            pkt->flags);
1038

    
1039
    return 0;
1040
}
1041

    
1042
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1043
{
1044
    AVPacketList *pktl;
1045
    int eof=0;
1046
    const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1047

    
1048
    for(;;){
1049
        pktl = s->packet_buffer;
1050
        if (pktl) {
1051
            AVPacket *next_pkt= &pktl->pkt;
1052

    
1053
            if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1054
                while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1055
                    if(   pktl->pkt.stream_index == next_pkt->stream_index
1056
                       && next_pkt->dts < pktl->pkt.dts
1057
                       && pktl->pkt.pts != pktl->pkt.dts //not b frame
1058
                       /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
1059
                        next_pkt->pts= pktl->pkt.dts;
1060
                    }
1061
                    pktl= pktl->next;
1062
                }
1063
                pktl = s->packet_buffer;
1064
            }
1065

    
1066
            if(   next_pkt->pts != AV_NOPTS_VALUE
1067
               || next_pkt->dts == AV_NOPTS_VALUE
1068
               || !genpts || eof){
1069
                /* read packet from packet buffer, if there is data */
1070
                *pkt = *next_pkt;
1071
                s->packet_buffer = pktl->next;
1072
                av_free(pktl);
1073
                return 0;
1074
            }
1075
        }
1076
        if(genpts){
1077
            int ret= av_read_frame_internal(s, pkt);
1078
            if(ret<0){
1079
                if(pktl && ret != AVERROR(EAGAIN)){
1080
                    eof=1;
1081
                    continue;
1082
                }else
1083
                    return ret;
1084
            }
1085

    
1086
            if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1087
                                           &s->packet_buffer_end)) < 0)
1088
                return AVERROR(ENOMEM);
1089
        }else{
1090
            assert(!s->packet_buffer);
1091
            return av_read_frame_internal(s, pkt);
1092
        }
1093
    }
1094
}
1095

    
1096
/* XXX: suppress the packet queue */
1097
static void flush_packet_queue(AVFormatContext *s)
1098
{
1099
    AVPacketList *pktl;
1100

    
1101
    for(;;) {
1102
        pktl = s->packet_buffer;
1103
        if (!pktl)
1104
            break;
1105
        s->packet_buffer = pktl->next;
1106
        av_free_packet(&pktl->pkt);
1107
        av_free(pktl);
1108
    }
1109
    while(s->raw_packet_buffer){
1110
        pktl = s->raw_packet_buffer;
1111
        s->raw_packet_buffer = pktl->next;
1112
        av_free_packet(&pktl->pkt);
1113
        av_free(pktl);
1114
    }
1115
    s->packet_buffer_end=
1116
    s->raw_packet_buffer_end= NULL;
1117
    s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1118
}
1119

    
1120
/*******************************************************/
1121
/* seek support */
1122

    
1123
int av_find_default_stream_index(AVFormatContext *s)
1124
{
1125
    int first_audio_index = -1;
1126
    int i;
1127
    AVStream *st;
1128

    
1129
    if (s->nb_streams <= 0)
1130
        return -1;
1131
    for(i = 0; i < s->nb_streams; i++) {
1132
        st = s->streams[i];
1133
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1134
            return i;
1135
        }
1136
        if (first_audio_index < 0 && st->codec->codec_type == CODEC_TYPE_AUDIO)
1137
            first_audio_index = i;
1138
    }
1139
    return first_audio_index >= 0 ? first_audio_index : 0;
1140
}
1141

    
1142
/**
1143
 * Flush the frame reader.
1144
 */
1145
void av_read_frame_flush(AVFormatContext *s)
1146
{
1147
    AVStream *st;
1148
    int i;
1149

    
1150
    flush_packet_queue(s);
1151

    
1152
    s->cur_st = NULL;
1153

    
1154
    /* for each stream, reset read state */
1155
    for(i = 0; i < s->nb_streams; i++) {
1156
        st = s->streams[i];
1157

    
1158
        if (st->parser) {
1159
            av_parser_close(st->parser);
1160
            st->parser = NULL;
1161
            av_free_packet(&st->cur_pkt);
1162
        }
1163
        st->last_IP_pts = AV_NOPTS_VALUE;
1164
        st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1165
        st->reference_dts = AV_NOPTS_VALUE;
1166
        /* fail safe */
1167
        st->cur_ptr = NULL;
1168
        st->cur_len = 0;
1169

    
1170
        st->probe_packets = MAX_PROBE_PACKETS;
1171
    }
1172
}
1173

    
1174
void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1175
    int i;
1176

    
1177
    for(i = 0; i < s->nb_streams; i++) {
1178
        AVStream *st = s->streams[i];
1179

    
1180
        st->cur_dts = av_rescale(timestamp,
1181
                                 st->time_base.den * (int64_t)ref_st->time_base.num,
1182
                                 st->time_base.num * (int64_t)ref_st->time_base.den);
1183
    }
1184
}
1185

    
1186
void ff_reduce_index(AVFormatContext *s, int stream_index)
1187
{
1188
    AVStream *st= s->streams[stream_index];
1189
    unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1190

    
1191
    if((unsigned)st->nb_index_entries >= max_entries){
1192
        int i;
1193
        for(i=0; 2*i<st->nb_index_entries; i++)
1194
            st->index_entries[i]= st->index_entries[2*i];
1195
        st->nb_index_entries= i;
1196
    }
1197
}
1198

    
1199
int av_add_index_entry(AVStream *st,
1200
                            int64_t pos, int64_t timestamp, int size, int distance, int flags)
1201
{
1202
    AVIndexEntry *entries, *ie;
1203
    int index;
1204

    
1205
    if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1206
        return -1;
1207

    
1208
    entries = av_fast_realloc(st->index_entries,
1209
                              &st->index_entries_allocated_size,
1210
                              (st->nb_index_entries + 1) *
1211
                              sizeof(AVIndexEntry));
1212
    if(!entries)
1213
        return -1;
1214

    
1215
    st->index_entries= entries;
1216

    
1217
    index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
1218

    
1219
    if(index<0){
1220
        index= st->nb_index_entries++;
1221
        ie= &entries[index];
1222
        assert(index==0 || ie[-1].timestamp < timestamp);
1223
    }else{
1224
        ie= &entries[index];
1225
        if(ie->timestamp != timestamp){
1226
            if(ie->timestamp <= timestamp)
1227
                return -1;
1228
            memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
1229
            st->nb_index_entries++;
1230
        }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1231
            distance= ie->min_distance;
1232
    }
1233

    
1234
    ie->pos = pos;
1235
    ie->timestamp = timestamp;
1236
    ie->min_distance= distance;
1237
    ie->size= size;
1238
    ie->flags = flags;
1239

    
1240
    return index;
1241
}
1242

    
1243
int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1244
                              int flags)
1245
{
1246
    AVIndexEntry *entries= st->index_entries;
1247
    int nb_entries= st->nb_index_entries;
1248
    int a, b, m;
1249
    int64_t timestamp;
1250

    
1251
    a = - 1;
1252
    b = nb_entries;
1253

    
1254
    while (b - a > 1) {
1255
        m = (a + b) >> 1;
1256
        timestamp = entries[m].timestamp;
1257
        if(timestamp >= wanted_timestamp)
1258
            b = m;
1259
        if(timestamp <= wanted_timestamp)
1260
            a = m;
1261
    }
1262
    m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1263

    
1264
    if(!(flags & AVSEEK_FLAG_ANY)){
1265
        while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1266
            m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1267
        }
1268
    }
1269

    
1270
    if(m == nb_entries)
1271
        return -1;
1272
    return  m;
1273
}
1274

    
1275
#define DEBUG_SEEK
1276

    
1277
int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1278
    AVInputFormat *avif= s->iformat;
1279
    int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1280
    int64_t ts_min, ts_max, ts;
1281
    int index;
1282
    AVStream *st;
1283

    
1284
    if (stream_index < 0)
1285
        return -1;
1286

    
1287
#ifdef DEBUG_SEEK
1288
    av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1289
#endif
1290

    
1291
    ts_max=
1292
    ts_min= AV_NOPTS_VALUE;
1293
    pos_limit= -1; //gcc falsely says it may be uninitialized
1294

    
1295
    st= s->streams[stream_index];
1296
    if(st->index_entries){
1297
        AVIndexEntry *e;
1298

    
1299
        index= av_index_search_timestamp(st, target_ts, flags | AVSEEK_FLAG_BACKWARD); //FIXME whole func must be checked for non-keyframe entries in index case, especially read_timestamp()
1300
        index= FFMAX(index, 0);
1301
        e= &st->index_entries[index];
1302

    
1303
        if(e->timestamp <= target_ts || e->pos == e->min_distance){
1304
            pos_min= e->pos;
1305
            ts_min= e->timestamp;
1306
#ifdef DEBUG_SEEK
1307
            av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1308
                   pos_min,ts_min);
1309
#endif
1310
        }else{
1311
            assert(index==0);
1312
        }
1313

    
1314
        index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1315
        assert(index < st->nb_index_entries);
1316
        if(index >= 0){
1317
            e= &st->index_entries[index];
1318
            assert(e->timestamp >= target_ts);
1319
            pos_max= e->pos;
1320
            ts_max= e->timestamp;
1321
            pos_limit= pos_max - e->min_distance;
1322
#ifdef DEBUG_SEEK
1323
            av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1324
                   pos_max,pos_limit, ts_max);
1325
#endif
1326
        }
1327
    }
1328

    
1329
    pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1330
    if(pos<0)
1331
        return -1;
1332

    
1333
    /* do the seek */
1334
    url_fseek(s->pb, pos, SEEK_SET);
1335

    
1336
    av_update_cur_dts(s, st, ts);
1337

    
1338
    return 0;
1339
}
1340

    
1341
int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, int64_t pos_min, int64_t pos_max, int64_t pos_limit, int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret, int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t )){
1342
    int64_t pos, ts;
1343
    int64_t start_pos, filesize;
1344
    int no_change;
1345

    
1346
#ifdef DEBUG_SEEK
1347
    av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1348
#endif
1349

    
1350
    if(ts_min == AV_NOPTS_VALUE){
1351
        pos_min = s->data_offset;
1352
        ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1353
        if (ts_min == AV_NOPTS_VALUE)
1354
            return -1;
1355
    }
1356

    
1357
    if(ts_max == AV_NOPTS_VALUE){
1358
        int step= 1024;
1359
        filesize = url_fsize(s->pb);
1360
        pos_max = filesize - 1;
1361
        do{
1362
            pos_max -= step;
1363
            ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1364
            step += step;
1365
        }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1366
        if (ts_max == AV_NOPTS_VALUE)
1367
            return -1;
1368

    
1369
        for(;;){
1370
            int64_t tmp_pos= pos_max + 1;
1371
            int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1372
            if(tmp_ts == AV_NOPTS_VALUE)
1373
                break;
1374
            ts_max= tmp_ts;
1375
            pos_max= tmp_pos;
1376
            if(tmp_pos >= filesize)
1377
                break;
1378
        }
1379
        pos_limit= pos_max;
1380
    }
1381

    
1382
    if(ts_min > ts_max){
1383
        return -1;
1384
    }else if(ts_min == ts_max){
1385
        pos_limit= pos_min;
1386
    }
1387

    
1388
    no_change=0;
1389
    while (pos_min < pos_limit) {
1390
#ifdef DEBUG_SEEK
1391
        av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1392
               pos_min, pos_max,
1393
               ts_min, ts_max);
1394
#endif
1395
        assert(pos_limit <= pos_max);
1396

    
1397
        if(no_change==0){
1398
            int64_t approximate_keyframe_distance= pos_max - pos_limit;
1399
            // interpolate position (better than dichotomy)
1400
            pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1401
                + pos_min - approximate_keyframe_distance;
1402
        }else if(no_change==1){
1403
            // bisection, if interpolation failed to change min or max pos last time
1404
            pos = (pos_min + pos_limit)>>1;
1405
        }else{
1406
            /* linear search if bisection failed, can only happen if there
1407
               are very few or no keyframes between min/max */
1408
            pos=pos_min;
1409
        }
1410
        if(pos <= pos_min)
1411
            pos= pos_min + 1;
1412
        else if(pos > pos_limit)
1413
            pos= pos_limit;
1414
        start_pos= pos;
1415

    
1416
        ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1417
        if(pos == pos_max)
1418
            no_change++;
1419
        else
1420
            no_change=0;
1421
#ifdef DEBUG_SEEK
1422
        av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1423
               pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit,
1424
               start_pos, no_change);
1425
#endif
1426
        if(ts == AV_NOPTS_VALUE){
1427
            av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1428
            return -1;
1429
        }
1430
        assert(ts != AV_NOPTS_VALUE);
1431
        if (target_ts <= ts) {
1432
            pos_limit = start_pos - 1;
1433
            pos_max = pos;
1434
            ts_max = ts;
1435
        }
1436
        if (target_ts >= ts) {
1437
            pos_min = pos;
1438
            ts_min = ts;
1439
        }
1440
    }
1441

    
1442
    pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1443
    ts  = (flags & AVSEEK_FLAG_BACKWARD) ?  ts_min :  ts_max;
1444
#ifdef DEBUG_SEEK
1445
    pos_min = pos;
1446
    ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1447
    pos_min++;
1448
    ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1449
    av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1450
           pos, ts_min, target_ts, ts_max);
1451
#endif
1452
    *ts_ret= ts;
1453
    return pos;
1454
}
1455

    
1456
static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1457
    int64_t pos_min, pos_max;
1458
#if 0
1459
    AVStream *st;
1460

1461
    if (stream_index < 0)
1462
        return -1;
1463

1464
    st= s->streams[stream_index];
1465
#endif
1466

    
1467
    pos_min = s->data_offset;
1468
    pos_max = url_fsize(s->pb) - 1;
1469

    
1470
    if     (pos < pos_min) pos= pos_min;
1471
    else if(pos > pos_max) pos= pos_max;
1472

    
1473
    url_fseek(s->pb, pos, SEEK_SET);
1474

    
1475
#if 0
1476
    av_update_cur_dts(s, st, ts);
1477
#endif
1478
    return 0;
1479
}
1480

    
1481
static int av_seek_frame_generic(AVFormatContext *s,
1482
                                 int stream_index, int64_t timestamp, int flags)
1483
{
1484
    int index, ret;
1485
    AVStream *st;
1486
    AVIndexEntry *ie;
1487

    
1488
    st = s->streams[stream_index];
1489

    
1490
    index = av_index_search_timestamp(st, timestamp, flags);
1491

    
1492
    if(index < 0 || index==st->nb_index_entries-1){
1493
        int i;
1494
        AVPacket pkt;
1495

    
1496
        if(st->nb_index_entries){
1497
            assert(st->index_entries);
1498
            ie= &st->index_entries[st->nb_index_entries-1];
1499
            if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
1500
                return ret;
1501
            av_update_cur_dts(s, st, ie->timestamp);
1502
        }else{
1503
            if ((ret = url_fseek(s->pb, s->data_offset, SEEK_SET)) < 0)
1504
                return ret;
1505
        }
1506
        for(i=0;; i++) {
1507
            int ret;
1508
            do{
1509
                ret = av_read_frame(s, &pkt);
1510
            }while(ret == AVERROR(EAGAIN));
1511
            if(ret<0)
1512
                break;
1513
            av_free_packet(&pkt);
1514
            if(stream_index == pkt.stream_index){
1515
                if((pkt.flags & PKT_FLAG_KEY) && pkt.dts > timestamp)
1516
                    break;
1517
            }
1518
        }
1519
        index = av_index_search_timestamp(st, timestamp, flags);
1520
    }
1521
    if (index < 0)
1522
        return -1;
1523

    
1524
    av_read_frame_flush(s);
1525
    if (s->iformat->read_seek){
1526
        if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1527
            return 0;
1528
    }
1529
    ie = &st->index_entries[index];
1530
    if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
1531
        return ret;
1532
    av_update_cur_dts(s, st, ie->timestamp);
1533

    
1534
    return 0;
1535
}
1536

    
1537
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1538
{
1539
    int ret;
1540
    AVStream *st;
1541

    
1542
    av_read_frame_flush(s);
1543

    
1544
    if(flags & AVSEEK_FLAG_BYTE)
1545
        return av_seek_frame_byte(s, stream_index, timestamp, flags);
1546

    
1547
    if(stream_index < 0){
1548
        stream_index= av_find_default_stream_index(s);
1549
        if(stream_index < 0)
1550
            return -1;
1551

    
1552
        st= s->streams[stream_index];
1553
       /* timestamp for default must be expressed in AV_TIME_BASE units */
1554
        timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1555
    }
1556

    
1557
    /* first, we try the format specific seek */
1558
    if (s->iformat->read_seek)
1559
        ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1560
    else
1561
        ret = -1;
1562
    if (ret >= 0) {
1563
        return 0;
1564
    }
1565

    
1566
    if(s->iformat->read_timestamp)
1567
        return av_seek_frame_binary(s, stream_index, timestamp, flags);
1568
    else
1569
        return av_seek_frame_generic(s, stream_index, timestamp, flags);
1570
}
1571

    
1572
int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1573
{
1574
    if(min_ts > ts || max_ts < ts)
1575
        return -1;
1576

    
1577
    av_read_frame_flush(s);
1578

    
1579
    if (s->iformat->read_seek2)
1580
        return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1581

    
1582
    if(s->iformat->read_timestamp){
1583
        //try to seek via read_timestamp()
1584
    }
1585

    
1586
    //Fallback to old API if new is not implemented but old is
1587
    //Note the old has somewat different sematics
1588
    if(s->iformat->read_seek || 1)
1589
        return av_seek_frame(s, stream_index, ts, flags | (ts - min_ts > (uint64_t)(max_ts - ts) ? AVSEEK_FLAG_BACKWARD : 0));
1590

    
1591
    // try some generic seek like av_seek_frame_generic() but with new ts semantics
1592
}
1593

    
1594
/*******************************************************/
1595

    
1596
/**
1597
 * Returns TRUE if the stream has accurate duration in any stream.
1598
 *
1599
 * @return TRUE if the stream has accurate duration for at least one component.
1600
 */
1601
static int av_has_duration(AVFormatContext *ic)
1602
{
1603
    int i;
1604
    AVStream *st;
1605

    
1606
    for(i = 0;i < ic->nb_streams; i++) {
1607
        st = ic->streams[i];
1608
        if (st->duration != AV_NOPTS_VALUE)
1609
            return 1;
1610
    }
1611
    return 0;
1612
}
1613

    
1614
/**
1615
 * Estimate the stream timings from the one of each components.
1616
 *
1617
 * Also computes the global bitrate if possible.
1618
 */
1619
static void av_update_stream_timings(AVFormatContext *ic)
1620
{
1621
    int64_t start_time, start_time1, end_time, end_time1;
1622
    int64_t duration, duration1;
1623
    int i;
1624
    AVStream *st;
1625

    
1626
    start_time = INT64_MAX;
1627
    end_time = INT64_MIN;
1628
    duration = INT64_MIN;
1629
    for(i = 0;i < ic->nb_streams; i++) {
1630
        st = ic->streams[i];
1631
        if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1632
            start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1633
            if (start_time1 < start_time)
1634
                start_time = start_time1;
1635
            if (st->duration != AV_NOPTS_VALUE) {
1636
                end_time1 = start_time1
1637
                          + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1638
                if (end_time1 > end_time)
1639
                    end_time = end_time1;
1640
            }
1641
        }
1642
        if (st->duration != AV_NOPTS_VALUE) {
1643
            duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1644
            if (duration1 > duration)
1645
                duration = duration1;
1646
        }
1647
    }
1648
    if (start_time != INT64_MAX) {
1649
        ic->start_time = start_time;
1650
        if (end_time != INT64_MIN) {
1651
            if (end_time - start_time > duration)
1652
                duration = end_time - start_time;
1653
        }
1654
    }
1655
    if (duration != INT64_MIN) {
1656
        ic->duration = duration;
1657
        if (ic->file_size > 0) {
1658
            /* compute the bitrate */
1659
            ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1660
                (double)ic->duration;
1661
        }
1662
    }
1663
}
1664

    
1665
static void fill_all_stream_timings(AVFormatContext *ic)
1666
{
1667
    int i;
1668
    AVStream *st;
1669

    
1670
    av_update_stream_timings(ic);
1671
    for(i = 0;i < ic->nb_streams; i++) {
1672
        st = ic->streams[i];
1673
        if (st->start_time == AV_NOPTS_VALUE) {
1674
            if(ic->start_time != AV_NOPTS_VALUE)
1675
                st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1676
            if(ic->duration != AV_NOPTS_VALUE)
1677
                st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1678
        }
1679
    }
1680
}
1681

    
1682
static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1683
{
1684
    int64_t filesize, duration;
1685
    int bit_rate, i;
1686
    AVStream *st;
1687

    
1688
    /* if bit_rate is already set, we believe it */
1689
    if (ic->bit_rate == 0) {
1690
        bit_rate = 0;
1691
        for(i=0;i<ic->nb_streams;i++) {
1692
            st = ic->streams[i];
1693
            bit_rate += st->codec->bit_rate;
1694
        }
1695
        ic->bit_rate = bit_rate;
1696
    }
1697

    
1698
    /* if duration is already set, we believe it */
1699
    if (ic->duration == AV_NOPTS_VALUE &&
1700
        ic->bit_rate != 0 &&
1701
        ic->file_size != 0)  {
1702
        filesize = ic->file_size;
1703
        if (filesize > 0) {
1704
            for(i = 0; i < ic->nb_streams; i++) {
1705
                st = ic->streams[i];
1706
                duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1707
                if (st->duration == AV_NOPTS_VALUE)
1708
                    st->duration = duration;
1709
            }
1710
        }
1711
    }
1712
}
1713

    
1714
#define DURATION_MAX_READ_SIZE 250000
1715

    
1716
/* only usable for MPEG-PS streams */
1717
static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1718
{
1719
    AVPacket pkt1, *pkt = &pkt1;
1720
    AVStream *st;
1721
    int read_size, i, ret;
1722
    int64_t end_time;
1723
    int64_t filesize, offset, duration;
1724

    
1725
    ic->cur_st = NULL;
1726

    
1727
    /* flush packet queue */
1728
    flush_packet_queue(ic);
1729

    
1730
    for(i=0;i<ic->nb_streams;i++) {
1731
        st = ic->streams[i];
1732
        if (st->parser) {
1733
            av_parser_close(st->parser);
1734
            st->parser= NULL;
1735
            av_free_packet(&st->cur_pkt);
1736
        }
1737
    }
1738

    
1739
    /* we read the first packets to get the first PTS (not fully
1740
       accurate, but it is enough now) */
1741
    url_fseek(ic->pb, 0, SEEK_SET);
1742
    read_size = 0;
1743
    for(;;) {
1744
        if (read_size >= DURATION_MAX_READ_SIZE)
1745
            break;
1746
        /* if all info is available, we can stop */
1747
        for(i = 0;i < ic->nb_streams; i++) {
1748
            st = ic->streams[i];
1749
            if (st->start_time == AV_NOPTS_VALUE)
1750
                break;
1751
        }
1752
        if (i == ic->nb_streams)
1753
            break;
1754

    
1755
        do{
1756
            ret = av_read_packet(ic, pkt);
1757
        }while(ret == AVERROR(EAGAIN));
1758
        if (ret != 0)
1759
            break;
1760
        read_size += pkt->size;
1761
        st = ic->streams[pkt->stream_index];
1762
        if (pkt->pts != AV_NOPTS_VALUE) {
1763
            if (st->start_time == AV_NOPTS_VALUE)
1764
                st->start_time = pkt->pts;
1765
        }
1766
        av_free_packet(pkt);
1767
    }
1768

    
1769
    /* estimate the end time (duration) */
1770
    /* XXX: may need to support wrapping */
1771
    filesize = ic->file_size;
1772
    offset = filesize - DURATION_MAX_READ_SIZE;
1773
    if (offset < 0)
1774
        offset = 0;
1775

    
1776
    url_fseek(ic->pb, offset, SEEK_SET);
1777
    read_size = 0;
1778
    for(;;) {
1779
        if (read_size >= DURATION_MAX_READ_SIZE)
1780
            break;
1781

    
1782
        do{
1783
            ret = av_read_packet(ic, pkt);
1784
        }while(ret == AVERROR(EAGAIN));
1785
        if (ret != 0)
1786
            break;
1787
        read_size += pkt->size;
1788
        st = ic->streams[pkt->stream_index];
1789
        if (pkt->pts != AV_NOPTS_VALUE &&
1790
            st->start_time != AV_NOPTS_VALUE) {
1791
            end_time = pkt->pts;
1792
            duration = end_time - st->start_time;
1793
            if (duration > 0) {
1794
                if (st->duration == AV_NOPTS_VALUE ||
1795
                    st->duration < duration)
1796
                    st->duration = duration;
1797
            }
1798
        }
1799
        av_free_packet(pkt);
1800
    }
1801

    
1802
    fill_all_stream_timings(ic);
1803

    
1804
    url_fseek(ic->pb, old_offset, SEEK_SET);
1805
    for(i=0; i<ic->nb_streams; i++){
1806
        st= ic->streams[i];
1807
        st->cur_dts= st->first_dts;
1808
        st->last_IP_pts = AV_NOPTS_VALUE;
1809
    }
1810
}
1811

    
1812
static void av_estimate_timings(AVFormatContext *ic, int64_t old_offset)
1813
{
1814
    int64_t file_size;
1815

    
1816
    /* get the file size, if possible */
1817
    if (ic->iformat->flags & AVFMT_NOFILE) {
1818
        file_size = 0;
1819
    } else {
1820
        file_size = url_fsize(ic->pb);
1821
        if (file_size < 0)
1822
            file_size = 0;
1823
    }
1824
    ic->file_size = file_size;
1825

    
1826
    if ((!strcmp(ic->iformat->name, "mpeg") ||
1827
         !strcmp(ic->iformat->name, "mpegts")) &&
1828
        file_size && !url_is_streamed(ic->pb)) {
1829
        /* get accurate estimate from the PTSes */
1830
        av_estimate_timings_from_pts(ic, old_offset);
1831
    } else if (av_has_duration(ic)) {
1832
        /* at least one component has timings - we use them for all
1833
           the components */
1834
        fill_all_stream_timings(ic);
1835
    } else {
1836
        /* less precise: use bitrate info */
1837
        av_estimate_timings_from_bit_rate(ic);
1838
    }
1839
    av_update_stream_timings(ic);
1840

    
1841
#if 0
1842
    {
1843
        int i;
1844
        AVStream *st;
1845
        for(i = 0;i < ic->nb_streams; i++) {
1846
            st = ic->streams[i];
1847
        printf("%d: start_time: %0.3f duration: %0.3f\n",
1848
               i, (double)st->start_time / AV_TIME_BASE,
1849
               (double)st->duration / AV_TIME_BASE);
1850
        }
1851
        printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1852
               (double)ic->start_time / AV_TIME_BASE,
1853
               (double)ic->duration / AV_TIME_BASE,
1854
               ic->bit_rate / 1000);
1855
    }
1856
#endif
1857
}
1858

    
1859
static int has_codec_parameters(AVCodecContext *enc)
1860
{
1861
    int val;
1862
    switch(enc->codec_type) {
1863
    case CODEC_TYPE_AUDIO:
1864
        val = enc->sample_rate && enc->channels && enc->sample_fmt != SAMPLE_FMT_NONE;
1865
        if(!enc->frame_size &&
1866
           (enc->codec_id == CODEC_ID_VORBIS ||
1867
            enc->codec_id == CODEC_ID_AAC ||
1868
            enc->codec_id == CODEC_ID_SPEEX))
1869
            return 0;
1870
        break;
1871
    case CODEC_TYPE_VIDEO:
1872
        val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
1873
        break;
1874
    default:
1875
        val = 1;
1876
        break;
1877
    }
1878
    return enc->codec_id != CODEC_ID_NONE && val != 0;
1879
}
1880

    
1881
static int try_decode_frame(AVStream *st, AVPacket *avpkt)
1882
{
1883
    int16_t *samples;
1884
    AVCodec *codec;
1885
    int got_picture, data_size, ret=0;
1886
    AVFrame picture;
1887

    
1888
    if(!st->codec->codec){
1889
        codec = avcodec_find_decoder(st->codec->codec_id);
1890
        if (!codec)
1891
            return -1;
1892
        ret = avcodec_open(st->codec, codec);
1893
        if (ret < 0)
1894
            return ret;
1895
    }
1896

    
1897
    if(!has_codec_parameters(st->codec)){
1898
        switch(st->codec->codec_type) {
1899
        case CODEC_TYPE_VIDEO:
1900
            avcodec_get_frame_defaults(&picture);
1901
            ret = avcodec_decode_video2(st->codec, &picture,
1902
                                        &got_picture, avpkt);
1903
            break;
1904
        case CODEC_TYPE_AUDIO:
1905
            data_size = FFMAX(avpkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
1906
            samples = av_malloc(data_size);
1907
            if (!samples)
1908
                goto fail;
1909
            ret = avcodec_decode_audio3(st->codec, samples,
1910
                                        &data_size, avpkt);
1911
            av_free(samples);
1912
            break;
1913
        default:
1914
            break;
1915
        }
1916
    }
1917
 fail:
1918
    return ret;
1919
}
1920

    
1921
unsigned int ff_codec_get_tag(const AVCodecTag *tags, int id)
1922
{
1923
    while (tags->id != CODEC_ID_NONE) {
1924
        if (tags->id == id)
1925
            return tags->tag;
1926
        tags++;
1927
    }
1928
    return 0;
1929
}
1930

    
1931
enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
1932
{
1933
    int i;
1934
    for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
1935
        if(tag == tags[i].tag)
1936
            return tags[i].id;
1937
    }
1938
    for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
1939
        if(   toupper((tag >> 0)&0xFF) == toupper((tags[i].tag >> 0)&0xFF)
1940
           && toupper((tag >> 8)&0xFF) == toupper((tags[i].tag >> 8)&0xFF)
1941
           && toupper((tag >>16)&0xFF) == toupper((tags[i].tag >>16)&0xFF)
1942
           && toupper((tag >>24)&0xFF) == toupper((tags[i].tag >>24)&0xFF))
1943
            return tags[i].id;
1944
    }
1945
    return CODEC_ID_NONE;
1946
}
1947

    
1948
unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
1949
{
1950
    int i;
1951
    for(i=0; tags && tags[i]; i++){
1952
        int tag= ff_codec_get_tag(tags[i], id);
1953
        if(tag) return tag;
1954
    }
1955
    return 0;
1956
}
1957

    
1958
enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
1959
{
1960
    int i;
1961
    for(i=0; tags && tags[i]; i++){
1962
        enum CodecID id= ff_codec_get_id(tags[i], tag);
1963
        if(id!=CODEC_ID_NONE) return id;
1964
    }
1965
    return CODEC_ID_NONE;
1966
}
1967

    
1968
static void compute_chapters_end(AVFormatContext *s)
1969
{
1970
    unsigned int i;
1971

    
1972
    for (i=0; i+1<s->nb_chapters; i++)
1973
        if (s->chapters[i]->end == AV_NOPTS_VALUE) {
1974
            assert(s->chapters[i]->start <= s->chapters[i+1]->start);
1975
            assert(!av_cmp_q(s->chapters[i]->time_base, s->chapters[i+1]->time_base));
1976
            s->chapters[i]->end = s->chapters[i+1]->start;
1977
        }
1978

    
1979
    if (s->nb_chapters && s->chapters[i]->end == AV_NOPTS_VALUE) {
1980
        assert(s->start_time != AV_NOPTS_VALUE);
1981
        assert(s->duration > 0);
1982
        s->chapters[i]->end = av_rescale_q(s->start_time + s->duration,
1983
                                           AV_TIME_BASE_Q,
1984
                                           s->chapters[i]->time_base);
1985
    }
1986
}
1987

    
1988
#define MAX_STD_TIMEBASES (60*12+5)
1989
static int get_std_framerate(int i){
1990
    if(i<60*12) return i*1001;
1991
    else        return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
1992
}
1993

    
1994
/*
1995
 * Is the time base unreliable.
1996
 * This is a heuristic to balance between quick acceptance of the values in
1997
 * the headers vs. some extra checks.
1998
 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
1999
 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2000
 * And there are "variable" fps files this needs to detect as well.
2001
 */
2002
static int tb_unreliable(AVCodecContext *c){
2003
    if(   c->time_base.den >= 101L*c->time_base.num
2004
       || c->time_base.den <    5L*c->time_base.num
2005
/*       || c->codec_tag == AV_RL32("DIVX")
2006
       || c->codec_tag == AV_RL32("XVID")*/
2007
       || c->codec_id == CODEC_ID_MPEG2VIDEO
2008
       || c->codec_id == CODEC_ID_H264
2009
       )
2010
        return 1;
2011
    return 0;
2012
}
2013

    
2014
int av_find_stream_info(AVFormatContext *ic)
2015
{
2016
    int i, count, ret, read_size, j;
2017
    AVStream *st;
2018
    AVPacket pkt1, *pkt;
2019
    int64_t last_dts[MAX_STREAMS];
2020
    int64_t duration_gcd[MAX_STREAMS]={0};
2021
    int duration_count[MAX_STREAMS]={0};
2022
    double (*duration_error)[MAX_STD_TIMEBASES];
2023
    int64_t old_offset = url_ftell(ic->pb);
2024
    int64_t codec_info_duration[MAX_STREAMS]={0};
2025
    int codec_info_nb_frames[MAX_STREAMS]={0};
2026

    
2027
    duration_error = av_mallocz(MAX_STREAMS * sizeof(*duration_error));
2028
    if (!duration_error) return AVERROR(ENOMEM);
2029

    
2030
    for(i=0;i<ic->nb_streams;i++) {
2031
        st = ic->streams[i];
2032
        if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2033
/*            if(!st->time_base.num)
2034
                st->time_base= */
2035
            if(!st->codec->time_base.num)
2036
                st->codec->time_base= st->time_base;
2037
        }
2038
        //only for the split stuff
2039
        if (!st->parser) {
2040
            st->parser = av_parser_init(st->codec->codec_id);
2041
            if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2042
                st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2043
            }
2044
        }
2045
    }
2046

    
2047
    for(i=0;i<MAX_STREAMS;i++){
2048
        last_dts[i]= AV_NOPTS_VALUE;
2049
    }
2050

    
2051
    count = 0;
2052
    read_size = 0;
2053
    for(;;) {
2054
        if(url_interrupt_cb()){
2055
            ret= AVERROR(EINTR);
2056
            av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2057
            break;
2058
        }
2059

    
2060
        /* check if one codec still needs to be handled */
2061
        for(i=0;i<ic->nb_streams;i++) {
2062
            st = ic->streams[i];
2063
            if (!has_codec_parameters(st->codec))
2064
                break;
2065
            /* variable fps and no guess at the real fps */
2066
            if(   tb_unreliable(st->codec)
2067
               && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)
2068
                break;
2069
            if(st->parser && st->parser->parser->split && !st->codec->extradata)
2070
                break;
2071
            if(st->first_dts == AV_NOPTS_VALUE)
2072
                break;
2073
        }
2074
        if (i == ic->nb_streams) {
2075
            /* NOTE: if the format has no header, then we need to read
2076
               some packets to get most of the streams, so we cannot
2077
               stop here */
2078
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2079
                /* if we found the info for all the codecs, we can stop */
2080
                ret = count;
2081
                av_log(ic, AV_LOG_DEBUG, "All info found\n");
2082
                break;
2083
            }
2084
        }
2085
        /* we did not get all the codec info, but we read too much data */
2086
        if (read_size >= ic->probesize) {
2087
            ret = count;
2088
            av_log(ic, AV_LOG_WARNING, "MAX_READ_SIZE:%d reached\n", ic->probesize);
2089
            break;
2090
        }
2091

    
2092
        /* NOTE: a new stream can be added there if no header in file
2093
           (AVFMTCTX_NOHEADER) */
2094
        ret = av_read_frame_internal(ic, &pkt1);
2095
        if(ret == AVERROR(EAGAIN))
2096
            continue;
2097
        if (ret < 0) {
2098
            /* EOF or error */
2099
            ret = -1; /* we could not have all the codec parameters before EOF */
2100
            for(i=0;i<ic->nb_streams;i++) {
2101
                st = ic->streams[i];
2102
                if (!has_codec_parameters(st->codec)){
2103
                    char buf[256];
2104
                    avcodec_string(buf, sizeof(buf), st->codec, 0);
2105
                    av_log(ic, AV_LOG_WARNING, "Could not find codec parameters (%s)\n", buf);
2106
                } else {
2107
                    ret = 0;
2108
                }
2109
            }
2110
            break;
2111
        }
2112

    
2113
        pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
2114
        if(av_dup_packet(pkt) < 0) {
2115
            av_free(duration_error);
2116
            return AVERROR(ENOMEM);
2117
        }
2118

    
2119
        read_size += pkt->size;
2120

    
2121
        st = ic->streams[pkt->stream_index];
2122
        if(codec_info_nb_frames[st->index]>1) {
2123
            if (st->time_base.den > 0 && av_rescale_q(codec_info_duration[st->index], st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration){
2124
                av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2125
                break;
2126
            }
2127
            codec_info_duration[st->index] += pkt->duration;
2128
        }
2129
        if (pkt->duration != 0)
2130
            codec_info_nb_frames[st->index]++;
2131

    
2132
        {
2133
            int index= pkt->stream_index;
2134
            int64_t last= last_dts[index];
2135
            int64_t duration= pkt->dts - last;
2136

    
2137
            if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
2138
                double dur= duration * av_q2d(st->time_base);
2139

    
2140
//                if(st->codec->codec_type == CODEC_TYPE_VIDEO)
2141
//                    av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
2142
                if(duration_count[index] < 2)
2143
                    memset(duration_error[index], 0, sizeof(*duration_error));
2144
                for(i=1; i<MAX_STD_TIMEBASES; i++){
2145
                    int framerate= get_std_framerate(i);
2146
                    int ticks= lrintf(dur*framerate/(1001*12));
2147
                    double error= dur - ticks*1001*12/(double)framerate;
2148
                    duration_error[index][i] += error*error;
2149
                }
2150
                duration_count[index]++;
2151
                // ignore the first 4 values, they might have some random jitter
2152
                if (duration_count[index] > 3)
2153
                    duration_gcd[index] = av_gcd(duration_gcd[index], duration);
2154
            }
2155
            if(last == AV_NOPTS_VALUE || duration_count[index]<=1)
2156
                last_dts[pkt->stream_index]= pkt->dts;
2157
        }
2158
        if(st->parser && st->parser->parser->split && !st->codec->extradata){
2159
            int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2160
            if(i){
2161
                st->codec->extradata_size= i;
2162
                st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2163
                memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2164
                memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2165
            }
2166
        }
2167

    
2168
        /* if still no information, we try to open the codec and to
2169
           decompress the frame. We try to avoid that in most cases as
2170
           it takes longer and uses more memory. For MPEG-4, we need to
2171
           decompress for QuickTime. */
2172
        if (!has_codec_parameters(st->codec) /*&&
2173
            (st->codec->codec_id == CODEC_ID_FLV1 ||
2174
             st->codec->codec_id == CODEC_ID_H264 ||
2175
             st->codec->codec_id == CODEC_ID_H263 ||
2176
             st->codec->codec_id == CODEC_ID_H261 ||
2177
             st->codec->codec_id == CODEC_ID_VORBIS ||
2178
             st->codec->codec_id == CODEC_ID_MJPEG ||
2179
             st->codec->codec_id == CODEC_ID_PNG ||
2180
             st->codec->codec_id == CODEC_ID_PAM ||
2181
             st->codec->codec_id == CODEC_ID_PGM ||
2182
             st->codec->codec_id == CODEC_ID_PGMYUV ||
2183
             st->codec->codec_id == CODEC_ID_PBM ||
2184
             st->codec->codec_id == CODEC_ID_PPM ||
2185
             st->codec->codec_id == CODEC_ID_SHORTEN ||
2186
             (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
2187
            try_decode_frame(st, pkt);
2188

    
2189
        count++;
2190
    }
2191

    
2192
    // close codecs which were opened in try_decode_frame()
2193
    for(i=0;i<ic->nb_streams;i++) {
2194
        st = ic->streams[i];
2195
        if(st->codec->codec)
2196
            avcodec_close(st->codec);
2197
    }
2198
    for(i=0;i<ic->nb_streams;i++) {
2199
        st = ic->streams[i];
2200
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2201
            if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample)
2202
                st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2203

    
2204
            // the check for tb_unreliable() is not completely correct, since this is not about handling
2205
            // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2206
            // ipmovie.c produces.
2207
            if (tb_unreliable(st->codec) && duration_count[i] > 15 && duration_gcd[i] > 1)
2208
                av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * duration_gcd[i], INT_MAX);
2209
            if(duration_count[i]
2210
               && tb_unreliable(st->codec) /*&&
2211
               //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2212
               st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den*/){
2213
                int num = 0;
2214
                double best_error= 2*av_q2d(st->time_base);
2215
                best_error= best_error*best_error*duration_count[i]*1000*12*30;
2216

    
2217
                for(j=1; j<MAX_STD_TIMEBASES; j++){
2218
                    double error= duration_error[i][j] * get_std_framerate(j);
2219
//                    if(st->codec->codec_type == CODEC_TYPE_VIDEO)
2220
//                        av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
2221
                    if(error < best_error){
2222
                        best_error= error;
2223
                        num = get_std_framerate(j);
2224
                    }
2225
                }
2226
                // do not increase frame rate by more than 1 % in order to match a standard rate.
2227
                if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
2228
                    av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2229
            }
2230

    
2231
            if (!st->r_frame_rate.num){
2232
                if(    st->codec->time_base.den * (int64_t)st->time_base.num
2233
                    <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){
2234
                    st->r_frame_rate.num = st->codec->time_base.den;
2235
                    st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
2236
                }else{
2237
                    st->r_frame_rate.num = st->time_base.den;
2238
                    st->r_frame_rate.den = st->time_base.num;
2239
                }
2240
            }
2241
        }else if(st->codec->codec_type == CODEC_TYPE_AUDIO) {
2242
            if(!st->codec->bits_per_coded_sample)
2243
                st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2244
        }
2245
    }
2246

    
2247
    av_estimate_timings(ic, old_offset);
2248

    
2249
    compute_chapters_end(ic);
2250

    
2251
#if 0
2252
    /* correct DTS for B-frame streams with no timestamps */
2253
    for(i=0;i<ic->nb_streams;i++) {
2254
        st = ic->streams[i];
2255
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2256
            if(b-frames){
2257
                ppktl = &ic->packet_buffer;
2258
                while(ppkt1){
2259
                    if(ppkt1->stream_index != i)
2260
                        continue;
2261
                    if(ppkt1->pkt->dts < 0)
2262
                        break;
2263
                    if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2264
                        break;
2265
                    ppkt1->pkt->dts -= delta;
2266
                    ppkt1= ppkt1->next;
2267
                }
2268
                if(ppkt1)
2269
                    continue;
2270
                st->cur_dts -= delta;
2271
            }
2272
        }
2273
    }
2274
#endif
2275

    
2276
    av_free(duration_error);
2277

    
2278
    return ret;
2279
}
2280

    
2281
/*******************************************************/
2282

    
2283
int av_read_play(AVFormatContext *s)
2284
{
2285
    if (s->iformat->read_play)
2286
        return s->iformat->read_play(s);
2287
    if (s->pb)
2288
        return av_url_read_fpause(s->pb, 0);
2289
    return AVERROR(ENOSYS);
2290
}
2291

    
2292
int av_read_pause(AVFormatContext *s)
2293
{
2294
    if (s->iformat->read_pause)
2295
        return s->iformat->read_pause(s);
2296
    if (s->pb)
2297
        return av_url_read_fpause(s->pb, 1);
2298
    return AVERROR(ENOSYS);
2299
}
2300

    
2301
void av_close_input_stream(AVFormatContext *s)
2302
{
2303
    int i;
2304
    AVStream *st;
2305

    
2306
    if (s->iformat->read_close)
2307
        s->iformat->read_close(s);
2308
    for(i=0;i<s->nb_streams;i++) {
2309
        /* free all data in a stream component */
2310
        st = s->streams[i];
2311
        if (st->parser) {
2312
            av_parser_close(st->parser);
2313
            av_free_packet(&st->cur_pkt);
2314
        }
2315
        av_metadata_free(&st->metadata);
2316
        av_free(st->index_entries);
2317
        av_free(st->codec->extradata);
2318
        av_free(st->codec);
2319
#if LIBAVFORMAT_VERSION_INT < (53<<16)
2320
        av_free(st->filename);
2321
#endif
2322
        av_free(st->priv_data);
2323
        av_free(st);
2324
    }
2325
    for(i=s->nb_programs-1; i>=0; i--) {
2326
#if LIBAVFORMAT_VERSION_INT < (53<<16)
2327
        av_freep(&s->programs[i]->provider_name);
2328
        av_freep(&s->programs[i]->name);
2329
#endif
2330
        av_metadata_free(&s->programs[i]->metadata);
2331
        av_freep(&s->programs[i]->stream_index);
2332
        av_freep(&s->programs[i]);
2333
    }
2334
    av_freep(&s->programs);
2335
    flush_packet_queue(s);
2336
    av_freep(&s->priv_data);
2337
    while(s->nb_chapters--) {
2338
#if LIBAVFORMAT_VERSION_INT < (53<<16)
2339
        av_free(s->chapters[s->nb_chapters]->title);
2340
#endif
2341
        av_metadata_free(&s->chapters[s->nb_chapters]->metadata);
2342
        av_free(s->chapters[s->nb_chapters]);
2343
    }
2344
    av_freep(&s->chapters);
2345
    av_metadata_free(&s->metadata);
2346
    av_free(s);
2347
}
2348

    
2349
void av_close_input_file(AVFormatContext *s)
2350
{
2351
    ByteIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
2352
    av_close_input_stream(s);
2353
    if (pb)
2354
        url_fclose(pb);
2355
}
2356

    
2357
AVStream *av_new_stream(AVFormatContext *s, int id)
2358
{
2359
    AVStream *st;
2360
    int i;
2361

    
2362
    if (s->nb_streams >= MAX_STREAMS)
2363
        return NULL;
2364

    
2365
    st = av_mallocz(sizeof(AVStream));
2366
    if (!st)
2367
        return NULL;
2368

    
2369
    st->codec= avcodec_alloc_context();
2370
    if (s->iformat) {
2371
        /* no default bitrate if decoding */
2372
        st->codec->bit_rate = 0;
2373
    }
2374
    st->index = s->nb_streams;
2375
    st->id = id;
2376
    st->start_time = AV_NOPTS_VALUE;
2377
    st->duration = AV_NOPTS_VALUE;
2378
        /* we set the current DTS to 0 so that formats without any timestamps
2379
           but durations get some timestamps, formats with some unknown
2380
           timestamps have their first few packets buffered and the
2381
           timestamps corrected before they are returned to the user */
2382
    st->cur_dts = 0;
2383
    st->first_dts = AV_NOPTS_VALUE;
2384
    st->probe_packets = MAX_PROBE_PACKETS;
2385

    
2386
    /* default pts setting is MPEG-like */
2387
    av_set_pts_info(st, 33, 1, 90000);
2388
    st->last_IP_pts = AV_NOPTS_VALUE;
2389
    for(i=0; i<MAX_REORDER_DELAY+1; i++)
2390
        st->pts_buffer[i]= AV_NOPTS_VALUE;
2391
    st->reference_dts = AV_NOPTS_VALUE;
2392

    
2393
    st->sample_aspect_ratio = (AVRational){0,1};
2394

    
2395
    s->streams[s->nb_streams++] = st;
2396
    return st;
2397
}
2398

    
2399
AVProgram *av_new_program(AVFormatContext *ac, int id)
2400
{
2401
    AVProgram *program=NULL;
2402
    int i;
2403

    
2404
#ifdef DEBUG_SI
2405
    av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id);
2406
#endif
2407

    
2408
    for(i=0; i<ac->nb_programs; i++)
2409
        if(ac->programs[i]->id == id)
2410
            program = ac->programs[i];
2411

    
2412
    if(!program){
2413
        program = av_mallocz(sizeof(AVProgram));
2414
        if (!program)
2415
            return NULL;
2416
        dynarray_add(&ac->programs, &ac->nb_programs, program);
2417
        program->discard = AVDISCARD_NONE;
2418
    }
2419
    program->id = id;
2420

    
2421
    return program;
2422
}
2423

    
2424
AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2425
{
2426
    AVChapter *chapter = NULL;
2427
    int i;
2428

    
2429
    for(i=0; i<s->nb_chapters; i++)
2430
        if(s->chapters[i]->id == id)
2431
            chapter = s->chapters[i];
2432

    
2433
    if(!chapter){
2434
        chapter= av_mallocz(sizeof(AVChapter));
2435
        if(!chapter)
2436
            return NULL;
2437
        dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2438
    }
2439
#if LIBAVFORMAT_VERSION_INT < (53<<16)
2440
    av_free(chapter->title);
2441
#endif
2442
    av_metadata_set(&chapter->metadata, "title", title);
2443
    chapter->id    = id;
2444
    chapter->time_base= time_base;
2445
    chapter->start = start;
2446
    chapter->end   = end;
2447

    
2448
    return chapter;
2449
}
2450

    
2451
/************************************************************/
2452
/* output media file */
2453

    
2454
int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2455
{
2456
    int ret;
2457

    
2458
    if (s->oformat->priv_data_size > 0) {
2459
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
2460
        if (!s->priv_data)
2461
            return AVERROR(ENOMEM);
2462
    } else
2463
        s->priv_data = NULL;
2464

    
2465
    if (s->oformat->set_parameters) {
2466
        ret = s->oformat->set_parameters(s, ap);
2467
        if (ret < 0)
2468
            return ret;
2469
    }
2470
    return 0;
2471
}
2472

    
2473
int av_write_header(AVFormatContext *s)
2474
{
2475
    int ret, i;
2476
    AVStream *st;
2477

    
2478
    // some sanity checks
2479
    for(i=0;i<s->nb_streams;i++) {
2480
        st = s->streams[i];
2481

    
2482
        switch (st->codec->codec_type) {
2483
        case CODEC_TYPE_AUDIO:
2484
            if(st->codec->sample_rate<=0){
2485
                av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2486
                return -1;
2487
            }
2488
            if(!st->codec->block_align)
2489
                st->codec->block_align = st->codec->channels *
2490
                    av_get_bits_per_sample(st->codec->codec_id) >> 3;
2491
            break;
2492
        case CODEC_TYPE_VIDEO:
2493
            if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2494
                av_log(s, AV_LOG_ERROR, "time base not set\n");
2495
                return -1;
2496
            }
2497
            if(st->codec->width<=0 || st->codec->height<=0){
2498
                av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2499
                return -1;
2500
            }
2501
            if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)){
2502
                av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");
2503
                return -1;
2504
            }
2505
            break;
2506
        }
2507

    
2508
        if(s->oformat->codec_tag){
2509
            if(st->codec->codec_tag){
2510
                //FIXME
2511
                //check that tag + id is in the table
2512
                //if neither is in the table -> OK
2513
                //if tag is in the table with another id -> FAIL
2514
                //if id is in the table with another tag -> FAIL unless strict < ?
2515
            }else
2516
                st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
2517
        }
2518

    
2519
        if(s->oformat->flags & AVFMT_GLOBALHEADER &&
2520
            !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))
2521
          av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);
2522
    }
2523

    
2524
    if (!s->priv_data && s->oformat->priv_data_size > 0) {
2525
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
2526
        if (!s->priv_data)
2527
            return AVERROR(ENOMEM);
2528
    }
2529

    
2530
#if LIBAVFORMAT_VERSION_MAJOR < 53
2531
    ff_metadata_mux_compat(s);
2532
#endif
2533

    
2534
    if(s->oformat->write_header){
2535
        ret = s->oformat->write_header(s);
2536
        if (ret < 0)
2537
            return ret;
2538
    }
2539

    
2540
    /* init PTS generation */
2541
    for(i=0;i<s->nb_streams;i++) {
2542
        int64_t den = AV_NOPTS_VALUE;
2543
        st = s->streams[i];
2544

    
2545
        switch (st->codec->codec_type) {
2546
        case CODEC_TYPE_AUDIO:
2547
            den = (int64_t)st->time_base.num * st->codec->sample_rate;
2548
            break;
2549
        case CODEC_TYPE_VIDEO:
2550
            den = (int64_t)st->time_base.num * st->codec->time_base.den;
2551
            break;
2552
        default:
2553
            break;
2554
        }
2555
        if (den != AV_NOPTS_VALUE) {
2556
            if (den <= 0)
2557
                return AVERROR_INVALIDDATA;
2558
            av_frac_init(&st->pts, 0, 0, den);
2559
        }
2560
    }
2561
    return 0;
2562
}
2563

    
2564
//FIXME merge with compute_pkt_fields
2565
static int compute_pkt_fields2(AVStream *st, AVPacket *pkt){
2566
    int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
2567
    int num, den, frame_size, i;
2568

    
2569
//    av_log(st->codec, AV_LOG_DEBUG, "av_write_frame: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
2570

    
2571
/*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2572
        return -1;*/
2573

    
2574
    /* duration field */
2575
    if (pkt->duration == 0) {
2576
        compute_frame_duration(&num, &den, st, NULL, pkt);
2577
        if (den && num) {
2578
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
2579
        }
2580
    }
2581

    
2582
    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
2583
        pkt->pts= pkt->dts;
2584

    
2585
    //XXX/FIXME this is a temporary hack until all encoders output pts
2586
    if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
2587
        pkt->dts=
2588
//        pkt->pts= st->cur_dts;
2589
        pkt->pts= st->pts.val;
2590
    }
2591

    
2592
    //calculate dts from pts
2593
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
2594
        st->pts_buffer[0]= pkt->pts;
2595
        for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
2596
            st->pts_buffer[i]= (i-delay-1) * pkt->duration;
2597
        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
2598
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
2599

    
2600
        pkt->dts= st->pts_buffer[0];
2601
    }
2602

    
2603
    if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2604
        av_log(st->codec, AV_LOG_ERROR, "error, non monotone timestamps %"PRId64" >= %"PRId64"\n", st->cur_dts, pkt->dts);
2605
        return -1;
2606
    }
2607
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2608
        av_log(st->codec, AV_LOG_ERROR, "error, pts < dts\n");
2609
        return -1;
2610
    }
2611

    
2612
//    av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
2613
    st->cur_dts= pkt->dts;
2614
    st->pts.val= pkt->dts;
2615

    
2616
    /* update pts */
2617
    switch (st->codec->codec_type) {
2618
    case CODEC_TYPE_AUDIO:
2619
        frame_size = get_audio_frame_size(st->codec, pkt->size);
2620

    
2621
        /* HACK/FIXME, we skip the initial 0 size packets as they are most
2622
           likely equal to the encoder delay, but it would be better if we
2623
           had the real timestamps from the encoder */
2624
        if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2625
            av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2626
        }
2627
        break;
2628
    case CODEC_TYPE_VIDEO:
2629
        av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
2630
        break;
2631
    default:
2632
        break;
2633
    }
2634
    return 0;
2635
}
2636

    
2637
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2638
{
2639
    int ret = compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
2640

    
2641
    if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2642
        return ret;
2643

    
2644
    ret= s->oformat->write_packet(s, pkt);
2645
    if(!ret)
2646
        ret= url_ferror(s->pb);
2647
    return ret;
2648
}
2649

    
2650
void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
2651
                              int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
2652
{
2653
    AVPacketList **next_point, *this_pktl;
2654

    
2655
    this_pktl = av_mallocz(sizeof(AVPacketList));
2656
    this_pktl->pkt= *pkt;
2657
    pkt->destruct= NULL;             // do not free original but only the copy
2658
    av_dup_packet(&this_pktl->pkt);  // duplicate the packet if it uses non-alloced memory
2659

    
2660
    if(s->streams[pkt->stream_index]->last_in_packet_buffer){
2661
        next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
2662
    }else
2663
        next_point = &s->packet_buffer;
2664

    
2665
    if(*next_point){
2666
        if(compare(s, &s->packet_buffer_end->pkt, pkt)){
2667
            while(!compare(s, &(*next_point)->pkt, pkt)){
2668
                next_point= &(*next_point)->next;
2669
            }
2670
            goto next_non_null;
2671
        }else{
2672
            next_point = &(s->packet_buffer_end->next);
2673
        }
2674
    }
2675
    assert(!*next_point);
2676

    
2677
    s->packet_buffer_end= this_pktl;
2678
next_non_null:
2679

    
2680
    this_pktl->next= *next_point;
2681

    
2682
    s->streams[pkt->stream_index]->last_in_packet_buffer=
2683
    *next_point= this_pktl;
2684
}
2685

    
2686
int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
2687
{
2688
    AVStream *st = s->streams[ pkt ->stream_index];
2689
    AVStream *st2= s->streams[ next->stream_index];
2690
    int64_t left = st2->time_base.num * (int64_t)st ->time_base.den;
2691
    int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2692

    
2693
    if (pkt->dts == AV_NOPTS_VALUE)
2694
        return 0;
2695

    
2696
    return next->dts * left > pkt->dts * right; //FIXME this can overflow
2697
}
2698

    
2699
int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2700
    AVPacketList *pktl;
2701
    int stream_count=0;
2702
    int i;
2703

    
2704
    if(pkt){
2705
        ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
2706
    }
2707

    
2708
    for(i=0; i < s->nb_streams; i++)
2709
        stream_count+= !!s->streams[i]->last_in_packet_buffer;
2710

    
2711
    if(stream_count && (s->nb_streams == stream_count || flush)){
2712
        pktl= s->packet_buffer;
2713
        *out= pktl->pkt;
2714

    
2715
        s->packet_buffer= pktl->next;
2716
        if(!s->packet_buffer)
2717
            s->packet_buffer_end= NULL;
2718

    
2719
        if(s->streams[out->stream_index]->last_in_packet_buffer == pktl)
2720
            s->streams[out->stream_index]->last_in_packet_buffer= NULL;
2721
        av_freep(&pktl);
2722
        return 1;
2723
    }else{
2724
        av_init_packet(out);
2725
        return 0;
2726
    }
2727
}
2728

    
2729
/**
2730
 * Interleaves an AVPacket correctly so it can be muxed.
2731
 * @param out the interleaved packet will be output here
2732
 * @param in the input packet
2733
 * @param flush 1 if no further packets are available as input and all
2734
 *              remaining packets should be output
2735
 * @return 1 if a packet was output, 0 if no packet could be output,
2736
 *         < 0 if an error occurred
2737
 */
2738
static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2739
    if(s->oformat->interleave_packet)
2740
        return s->oformat->interleave_packet(s, out, in, flush);
2741
    else
2742
        return av_interleave_packet_per_dts(s, out, in, flush);
2743
}
2744

    
2745
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2746
    AVStream *st= s->streams[ pkt->stream_index];
2747

    
2748
    //FIXME/XXX/HACK drop zero sized packets
2749
    if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
2750
        return 0;
2751

    
2752
//av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %"PRId64" %"PRId64"\n", pkt->size, pkt->dts, pkt->pts);
2753
    if(compute_pkt_fields2(st, pkt) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2754
        return -1;
2755

    
2756
    if(pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2757
        return -1;
2758

    
2759
    for(;;){
2760
        AVPacket opkt;
2761
        int ret= av_interleave_packet(s, &opkt, pkt, 0);
2762
        if(ret<=0) //FIXME cleanup needed for ret<0 ?
2763
            return ret;
2764

    
2765
        ret= s->oformat->write_packet(s, &opkt);
2766

    
2767
        av_free_packet(&opkt);
2768
        pkt= NULL;
2769

    
2770
        if(ret<0)
2771
            return ret;
2772
        if(url_ferror(s->pb))
2773
            return url_ferror(s->pb);
2774
    }
2775
}
2776

    
2777
int av_write_trailer(AVFormatContext *s)
2778
{
2779
    int ret, i;
2780

    
2781
    for(;;){
2782
        AVPacket pkt;
2783
        ret= av_interleave_packet(s, &pkt, NULL, 1);
2784
        if(ret<0) //FIXME cleanup needed for ret<0 ?
2785
            goto fail;
2786
        if(!ret)
2787
            break;
2788

    
2789
        ret= s->oformat->write_packet(s, &pkt);
2790

    
2791
        av_free_packet(&pkt);
2792

    
2793
        if(ret<0)
2794
            goto fail;
2795
        if(url_ferror(s->pb))
2796
            goto fail;
2797
    }
2798

    
2799
    if(s->oformat->write_trailer)
2800
        ret = s->oformat->write_trailer(s);
2801
fail:
2802
    if(ret == 0)
2803
       ret=url_ferror(s->pb);
2804
    for(i=0;i<s->nb_streams;i++)
2805
        av_freep(&s->streams[i]->priv_data);
2806
    av_freep(&s->priv_data);
2807
    return ret;
2808
}
2809

    
2810
void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
2811
{
2812
    int i, j;
2813
    AVProgram *program=NULL;
2814
    void *tmp;
2815

    
2816
    for(i=0; i<ac->nb_programs; i++){
2817
        if(ac->programs[i]->id != progid)
2818
            continue;
2819
        program = ac->programs[i];
2820
        for(j=0; j<program->nb_stream_indexes; j++)
2821
            if(program->stream_index[j] == idx)
2822
                return;
2823

    
2824
        tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
2825
        if(!tmp)
2826
            return;
2827
        program->stream_index = tmp;
2828
        program->stream_index[program->nb_stream_indexes++] = idx;
2829
        return;
2830
    }
2831
}
2832

    
2833
static void print_fps(double d, const char *postfix){
2834
    uint64_t v= lrintf(d*100);
2835
    if     (v% 100      ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
2836
    else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
2837
    else                  av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
2838
}
2839

    
2840
/* "user interface" functions */
2841
static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
2842
{
2843
    char buf[256];
2844
    int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
2845
    AVStream *st = ic->streams[i];
2846
    int g = av_gcd(st->time_base.num, st->time_base.den);
2847
    AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL, 0);
2848
    avcodec_string(buf, sizeof(buf), st->codec, is_output);
2849
    av_log(NULL, AV_LOG_INFO, "    Stream #%d.%d", index, i);
2850
    /* the pid is an important information, so we display it */
2851
    /* XXX: add a generic system */
2852
    if (flags & AVFMT_SHOW_IDS)
2853
        av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2854
    if (lang)
2855
        av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
2856
    av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);
2857
    av_log(NULL, AV_LOG_INFO, ": %s", buf);
2858
    if (st->sample_aspect_ratio.num && // default
2859
        av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
2860
        AVRational display_aspect_ratio;
2861
        av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2862
                  st->codec->width*st->sample_aspect_ratio.num,
2863
                  st->codec->height*st->sample_aspect_ratio.den,
2864
                  1024*1024);
2865
        av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
2866
                 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
2867
                 display_aspect_ratio.num, display_aspect_ratio.den);
2868
    }
2869
    if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2870
        if(st->r_frame_rate.den && st->r_frame_rate.num)
2871
            print_fps(av_q2d(st->r_frame_rate), "tbr");
2872
        if(st->time_base.den && st->time_base.num)
2873
            print_fps(1/av_q2d(st->time_base), "tbn");
2874
        if(st->codec->time_base.den && st->codec->time_base.num)
2875
            print_fps(1/av_q2d(st->codec->time_base), "tbc");
2876
    }
2877
    av_log(NULL, AV_LOG_INFO, "\n");
2878
}
2879

    
2880
void dump_format(AVFormatContext *ic,
2881
                 int index,
2882
                 const char *url,
2883
                 int is_output)
2884
{
2885
    int i;
2886

    
2887
    av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2888
            is_output ? "Output" : "Input",
2889
            index,
2890
            is_output ? ic->oformat->name : ic->iformat->name,
2891
            is_output ? "to" : "from", url);
2892
    if (!is_output) {
2893
        av_log(NULL, AV_LOG_INFO, "  Duration: ");
2894
        if (ic->duration != AV_NOPTS_VALUE) {
2895
            int hours, mins, secs, us;
2896
            secs = ic->duration / AV_TIME_BASE;
2897
            us = ic->duration % AV_TIME_BASE;
2898
            mins = secs / 60;
2899
            secs %= 60;
2900
            hours = mins / 60;
2901
            mins %= 60;
2902
            av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
2903
                   (100 * us) / AV_TIME_BASE);
2904
        } else {
2905
            av_log(NULL, AV_LOG_INFO, "N/A");
2906
        }
2907
        if (ic->start_time != AV_NOPTS_VALUE) {
2908
            int secs, us;
2909
            av_log(NULL, AV_LOG_INFO, ", start: ");
2910
            secs = ic->start_time / AV_TIME_BASE;
2911
            us = ic->start_time % AV_TIME_BASE;
2912
            av_log(NULL, AV_LOG_INFO, "%d.%06d",
2913
                   secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2914
        }
2915
        av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2916
        if (ic->bit_rate) {
2917
            av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2918
        } else {
2919
            av_log(NULL, AV_LOG_INFO, "N/A");
2920
        }
2921
        av_log(NULL, AV_LOG_INFO, "\n");
2922
    }
2923
    if(ic->nb_programs) {
2924
        int j, k;
2925
        for(j=0; j<ic->nb_programs; j++) {
2926
            AVMetadataTag *name = av_metadata_get(ic->programs[j]->metadata,
2927
                                                  "name", NULL, 0);
2928
            av_log(NULL, AV_LOG_INFO, "  Program %d %s\n", ic->programs[j]->id,
2929
                   name ? name->value : "");
2930
            for(k=0; k<ic->programs[j]->nb_stream_indexes; k++)
2931
                dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
2932
         }
2933
    } else
2934
    for(i=0;i<ic->nb_streams;i++)
2935
        dump_stream_format(ic, i, index, is_output);
2936
    if (ic->metadata) {
2937
        AVMetadataTag *tag=NULL;
2938
        av_log(NULL, AV_LOG_INFO, "  Metadata\n");
2939
        while((tag=av_metadata_get(ic->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX))) {
2940
            av_log(NULL, AV_LOG_INFO, "    %-16s: %s\n", tag->key, tag->value);
2941
        }
2942
    }
2943

    
2944
}
2945

    
2946
#if LIBAVFORMAT_VERSION_MAJOR < 53
2947
int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2948
{
2949
    return av_parse_video_frame_size(width_ptr, height_ptr, str);
2950
}
2951

    
2952
int parse_frame_rate(int *frame_rate_num, int *frame_rate_den, const char *arg)
2953
{
2954
    AVRational frame_rate;
2955
    int ret = av_parse_video_frame_rate(&frame_rate, arg);
2956
    *frame_rate_num= frame_rate.num;
2957
    *frame_rate_den= frame_rate.den;
2958
    return ret;
2959
}
2960
#endif
2961

    
2962
int64_t av_gettime(void)
2963
{
2964
    struct timeval tv;
2965
    gettimeofday(&tv,NULL);
2966
    return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
2967
}
2968

    
2969
int64_t parse_date(const char *datestr, int duration)
2970
{
2971
    const char *p;
2972
    int64_t t;
2973
    struct tm dt;
2974
    int i;
2975
    static const char * const date_fmt[] = {
2976
        "%Y-%m-%d",
2977
        "%Y%m%d",
2978
    };
2979
    static const char * const time_fmt[] = {
2980
        "%H:%M:%S",
2981
        "%H%M%S",
2982
    };
2983
    const char *q;
2984
    int is_utc, len;
2985
    char lastch;
2986
    int negative = 0;
2987

    
2988
#undef time
2989
    time_t now = time(0);
2990

    
2991
    len = strlen(datestr);
2992
    if (len > 0)
2993
        lastch = datestr[len - 1];
2994
    else
2995
        lastch = '\0';
2996
    is_utc = (lastch == 'z' || lastch == 'Z');
2997

    
2998
    memset(&dt, 0, sizeof(dt));
2999

    
3000
    p = datestr;
3001
    q = NULL;
3002
    if (!duration) {
3003
        if (!strncasecmp(datestr, "now", len))
3004
            return (int64_t) now * 1000000;
3005

    
3006
        /* parse the year-month-day part */
3007
        for (i = 0; i < FF_ARRAY_ELEMS(date_fmt); i++) {
3008
            q = small_strptime(p, date_fmt[i], &dt);
3009
            if (q) {
3010
                break;
3011
            }
3012
        }
3013

    
3014
        /* if the year-month-day part is missing, then take the
3015
         * current year-month-day time */
3016
        if (!q) {
3017
            if (is_utc) {
3018
                dt = *gmtime(&now);
3019
            } else {
3020
                dt = *localtime(&now);
3021
            }
3022
            dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
3023
        } else {
3024
            p = q;
3025
        }
3026

    
3027
        if (*p == 'T' || *p == 't' || *p == ' ')
3028
            p++;
3029

    
3030
        /* parse the hour-minute-second part */
3031
        for (i = 0; i < FF_ARRAY_ELEMS(time_fmt); i++) {
3032
            q = small_strptime(p, time_fmt[i], &dt);
3033
            if (q) {
3034
                break;
3035
            }
3036
        }
3037
    } else {
3038
        /* parse datestr as a duration */
3039
        if (p[0] == '-') {
3040
            negative = 1;
3041
            ++p;
3042
        }
3043
        /* parse datestr as HH:MM:SS */
3044
        q = small_strptime(p, time_fmt[0], &dt);
3045
        if (!q) {
3046
            /* parse datestr as S+ */
3047
            dt.tm_sec = strtol(p, (char **)&q, 10);
3048
            if (q == p)
3049
                /* the parsing didn't succeed */
3050
                return INT64_MIN;
3051
            dt.tm_min = 0;
3052
            dt.tm_hour = 0;
3053
        }
3054
    }
3055

    
3056
    /* Now we have all the fields that we can get */
3057
    if (!q) {
3058
        return INT64_MIN;
3059
    }
3060

    
3061
    if (duration) {
3062
        t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
3063
    } else {
3064
        dt.tm_isdst = -1;       /* unknown */
3065
        if (is_utc) {
3066
            t = mktimegm(&dt);
3067
        } else {
3068
            t = mktime(&dt);
3069
        }
3070
    }
3071

    
3072
    t *= 1000000;
3073

    
3074
    /* parse the .m... part */
3075
    if (*q == '.') {
3076
        int val, n;
3077
        q++;
3078
        for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
3079
            if (!isdigit(*q))
3080
                break;
3081
            val += n * (*q - '0');
3082
        }
3083
        t += val;
3084
    }
3085
    return negative ? -t : t;
3086
}
3087

    
3088
int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
3089
{
3090
    const char *p;
3091
    char tag[128], *q;
3092

    
3093
    p = info;
3094
    if (*p == '?')
3095
        p++;
3096
    for(;;) {
3097
        q = tag;
3098
        while (*p != '\0' && *p != '=' && *p != '&') {
3099
            if ((q - tag) < sizeof(tag) - 1)
3100
                *q++ = *p;
3101
            p++;
3102
        }
3103
        *q = '\0';
3104
        q = arg;
3105
        if (*p == '=') {
3106
            p++;
3107
            while (*p != '&' && *p != '\0') {
3108
                if ((q - arg) < arg_size - 1) {
3109
                    if (*p == '+')
3110
                        *q++ = ' ';
3111
                    else
3112
                        *q++ = *p;
3113
                }
3114
                p++;
3115
            }
3116
            *q = '\0';
3117
        }
3118
        if (!strcmp(tag, tag1))
3119
            return 1;
3120
        if (*p != '&')
3121
            break;
3122
        p++;
3123
    }
3124
    return 0;
3125
}
3126

    
3127
int av_get_frame_filename(char *buf, int buf_size,
3128
                          const char *path, int number)
3129
{
3130
    const char *p;
3131
    char *q, buf1[20], c;
3132
    int nd, len, percentd_found;
3133

    
3134
    q = buf;
3135
    p = path;
3136
    percentd_found = 0;
3137
    for(;;) {
3138
        c = *p++;
3139
        if (c == '\0')
3140
            break;
3141
        if (c == '%') {
3142
            do {
3143
                nd = 0;
3144
                while (isdigit(*p)) {
3145
                    nd = nd * 10 + *p++ - '0';
3146
                }
3147
                c = *p++;
3148
            } while (isdigit(c));
3149

    
3150
            switch(c) {
3151
            case '%':
3152
                goto addchar;
3153
            case 'd':
3154
                if (percentd_found)
3155
                    goto fail;
3156
                percentd_found = 1;
3157
                snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3158
                len = strlen(buf1);
3159
                if ((q - buf + len) > buf_size - 1)
3160
                    goto fail;
3161
                memcpy(q, buf1, len);
3162
                q += len;
3163
                break;
3164
            default:
3165
                goto fail;
3166
            }
3167
        } else {
3168
        addchar:
3169
            if ((q - buf) < buf_size - 1)
3170
                *q++ = c;
3171
        }
3172
    }
3173
    if (!percentd_found)
3174
        goto fail;
3175
    *q = '\0';
3176
    return 0;
3177
 fail:
3178
    *q = '\0';
3179
    return -1;
3180
}
3181

    
3182
static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
3183
{
3184
    int len, i, j, c;
3185
#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3186

    
3187
    for(i=0;i<size;i+=16) {
3188
        len = size - i;
3189
        if (len > 16)
3190
            len = 16;
3191
        PRINT("%08x ", i);
3192
        for(j=0;j<16;j++) {
3193
            if (j < len)
3194
                PRINT(" %02x", buf[i+j]);
3195
            else
3196
                PRINT("   ");
3197
        }
3198
        PRINT(" ");
3199
        for(j=0;j<len;j++) {
3200
            c = buf[i+j];
3201
            if (c < ' ' || c > '~')
3202
                c = '.';
3203
            PRINT("%c", c);
3204
        }
3205
        PRINT("\n");
3206
    }
3207
#undef PRINT
3208
}
3209

    
3210
void av_hex_dump(FILE *f, uint8_t *buf, int size)
3211
{
3212
    hex_dump_internal(NULL, f, 0, buf, size);
3213
}
3214

    
3215
void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
3216
{
3217
    hex_dump_internal(avcl, NULL, level, buf, size);
3218
}
3219

    
3220
 //FIXME needs to know the time_base
3221
static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload)
3222
{
3223
#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3224
    PRINT("stream #%d:\n", pkt->stream_index);
3225
    PRINT("  keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
3226
    PRINT("  duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
3227
    /* DTS is _always_ valid after av_read_frame() */
3228
    PRINT("  dts=");
3229
    if (pkt->dts == AV_NOPTS_VALUE)
3230
        PRINT("N/A");
3231
    else
3232
        PRINT("%0.3f", (double)pkt->dts / AV_TIME_BASE);
3233
    /* PTS may not be known if B-frames are present. */
3234
    PRINT("  pts=");
3235
    if (pkt->pts == AV_NOPTS_VALUE)
3236
        PRINT("N/A");
3237
    else
3238
        PRINT("%0.3f", (double)pkt->pts / AV_TIME_BASE);
3239
    PRINT("\n");
3240
    PRINT("  size=%d\n", pkt->size);
3241
#undef PRINT
3242
    if (dump_payload)
3243
        av_hex_dump(f, pkt->data, pkt->size);
3244
}
3245

    
3246
void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3247
{
3248
    pkt_dump_internal(NULL, f, 0, pkt, dump_payload);
3249
}
3250

    
3251
void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
3252
{
3253
    pkt_dump_internal(avcl, NULL, level, pkt, dump_payload);
3254
}
3255

    
3256
void url_split(char *proto, int proto_size,
3257
               char *authorization, int authorization_size,
3258
               char *hostname, int hostname_size,
3259
               int *port_ptr,
3260
               char *path, int path_size,
3261
               const char *url)
3262
{
3263
    const char *p, *ls, *at, *col, *brk;
3264

    
3265
    if (port_ptr)               *port_ptr = -1;
3266
    if (proto_size > 0)         proto[0] = 0;
3267
    if (authorization_size > 0) authorization[0] = 0;
3268
    if (hostname_size > 0)      hostname[0] = 0;
3269
    if (path_size > 0)          path[0] = 0;
3270

    
3271
    /* parse protocol */
3272
    if ((p = strchr(url, ':'))) {
3273
        av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3274
        p++; /* skip ':' */
3275
        if (*p == '/') p++;
3276
        if (*p == '/') p++;
3277
    } else {
3278
        /* no protocol means plain filename */
3279
        av_strlcpy(path, url, path_size);
3280
        return;
3281
    }
3282

    
3283
    /* separate path from hostname */
3284
    ls = strchr(p, '/');
3285
    if(!ls)
3286
        ls = strchr(p, '?');
3287
    if(ls)
3288
        av_strlcpy(path, ls, path_size);
3289
    else
3290
        ls = &p[strlen(p)]; // XXX
3291

    
3292
    /* the rest is hostname, use that to parse auth/port */
3293
    if (ls != p) {
3294
        /* authorization (user[:pass]@hostname) */
3295
        if ((at = strchr(p, '@')) && at < ls) {
3296
            av_strlcpy(authorization, p,
3297
                       FFMIN(authorization_size, at + 1 - p));
3298
            p = at + 1; /* skip '@' */
3299
        }
3300

    
3301
        if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3302
            /* [host]:port */
3303
            av_strlcpy(hostname, p + 1,
3304
                       FFMIN(hostname_size, brk - p));
3305
            if (brk[1] == ':' && port_ptr)
3306
                *port_ptr = atoi(brk + 2);
3307
        } else if ((col = strchr(p, ':')) && col < ls) {
3308
            av_strlcpy(hostname, p,
3309
                       FFMIN(col + 1 - p, hostname_size));
3310
            if (port_ptr) *port_ptr = atoi(col + 1);
3311
        } else
3312
            av_strlcpy(hostname, p,
3313
                       FFMIN(ls + 1 - p, hostname_size));
3314
    }
3315
}
3316

    
3317
char *ff_data_to_hex(char *buff, const uint8_t *src, int s)
3318
{
3319
    int i;
3320
    static const char hex_table[16] = { '0', '1', '2', '3',
3321
                                        '4', '5', '6', '7',
3322
                                        '8', '9', 'A', 'B',
3323
                                        'C', 'D', 'E', 'F' };
3324

    
3325
    for(i = 0; i < s; i++) {
3326
        buff[i * 2]     = hex_table[src[i] >> 4];
3327
        buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3328
    }
3329

    
3330
    return buff;
3331
}
3332

    
3333
void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3334
                     unsigned int pts_num, unsigned int pts_den)
3335
{
3336
    s->pts_wrap_bits = pts_wrap_bits;
3337

    
3338
    if(av_reduce(&s->time_base.num, &s->time_base.den, pts_num, pts_den, INT_MAX)){
3339
        if(s->time_base.num != pts_num)
3340
            av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/s->time_base.num);
3341
    }else
3342
        av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3343

    
3344
    if(!s->time_base.num || !s->time_base.den)
3345
        s->time_base.num= s->time_base.den= 0;
3346
}