Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ c36823fd

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
            if(fmt)
478
                av_log(*ic_ptr, AV_LOG_DEBUG, "Probe with size=%d detected %s with score=%d\n", probe_size, fmt->name, score);
479
        }
480
        av_freep(&pd->buf);
481
    }
482

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

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

    
509
}
510

    
511
/*******************************************************/
512

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

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

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

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

    
535
    for(;;){
536
        AVPacketList *pktl = s->raw_packet_buffer;
537

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

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

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

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

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

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

    
586
            --st->probe_packets;
587

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

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

    
604
/**********************************************************/
605

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

    
613
    if(enc->codec_id == CODEC_ID_VORBIS)
614
        return -1;
615

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

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

    
635

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

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

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

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

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

    
704
    st->first_dts= dts - st->cur_dts;
705
    st->cur_dts= dts;
706

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
835
//    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);
836
    /* interpolate PTS and DTS if they are not present */
837
    //We skip H264 currently because delay and has_b_frames are not reliably set
838
    if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){
839
        if (presentation_delayed) {
840
            /* DTS = decompression timestamp */
841
            /* PTS = presentation timestamp */
842
            if (pkt->dts == AV_NOPTS_VALUE)
843
                pkt->dts = st->last_IP_pts;
844
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
845
            if (pkt->dts == AV_NOPTS_VALUE)
846
                pkt->dts = st->cur_dts;
847

    
848
            /* this is tricky: the dts must be incremented by the duration
849
            of the frame we are displaying, i.e. the last I- or P-frame */
850
            if (st->last_IP_duration == 0)
851
                st->last_IP_duration = pkt->duration;
852
            if(pkt->dts != AV_NOPTS_VALUE)
853
                st->cur_dts = pkt->dts + st->last_IP_duration;
854
            st->last_IP_duration  = pkt->duration;
855
            st->last_IP_pts= pkt->pts;
856
            /* cannot compute PTS if not present (we can compute it only
857
            by knowing the future */
858
        } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
859
            if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
860
                int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
861
                int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
862
                if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
863
                    pkt->pts += pkt->duration;
864
    //                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);
865
                }
866
            }
867

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

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

    
893
//    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);
894

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

    
910

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

    
916
    av_init_packet(pkt);
917

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

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

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

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

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

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

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

    
1041
    return 0;
1042
}
1043

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

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

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

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

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

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

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

    
1122
/*******************************************************/
1123
/* seek support */
1124

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

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

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

    
1152
    flush_packet_queue(s);
1153

    
1154
    s->cur_st = NULL;
1155

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

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

    
1172
        st->probe_packets = MAX_PROBE_PACKETS;
1173
    }
1174
}
1175

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

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

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

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

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

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

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

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

    
1217
    st->index_entries= entries;
1218

    
1219
    index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
1220

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

    
1236
    ie->pos = pos;
1237
    ie->timestamp = timestamp;
1238
    ie->min_distance= distance;
1239
    ie->size= size;
1240
    ie->flags = flags;
1241

    
1242
    return index;
1243
}
1244

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

    
1253
    a = - 1;
1254
    b = nb_entries;
1255

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

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

    
1272
    if(m == nb_entries)
1273
        return -1;
1274
    return  m;
1275
}
1276

    
1277
#define DEBUG_SEEK
1278

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

    
1286
    if (stream_index < 0)
1287
        return -1;
1288

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

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

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

    
1301
        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()
1302
        index= FFMAX(index, 0);
1303
        e= &st->index_entries[index];
1304

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

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

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

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

    
1338
    av_update_cur_dts(s, st, ts);
1339

    
1340
    return 0;
1341
}
1342

    
1343
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 )){
1344
    int64_t pos, ts;
1345
    int64_t start_pos, filesize;
1346
    int no_change;
1347

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

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

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

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

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

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

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

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

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

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

1463
    if (stream_index < 0)
1464
        return -1;
1465

1466
    st= s->streams[stream_index];
1467
#endif
1468

    
1469
    pos_min = s->data_offset;
1470
    pos_max = url_fsize(s->pb) - 1;
1471

    
1472
    if     (pos < pos_min) pos= pos_min;
1473
    else if(pos > pos_max) pos= pos_max;
1474

    
1475
    url_fseek(s->pb, pos, SEEK_SET);
1476

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

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

    
1490
    st = s->streams[stream_index];
1491

    
1492
    index = av_index_search_timestamp(st, timestamp, flags);
1493

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

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

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

    
1536
    return 0;
1537
}
1538

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

    
1544
    av_read_frame_flush(s);
1545

    
1546
    if(flags & AVSEEK_FLAG_BYTE)
1547
        return av_seek_frame_byte(s, stream_index, timestamp, flags);
1548

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

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

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

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

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

    
1579
    av_read_frame_flush(s);
1580

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

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

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

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

    
1596
/*******************************************************/
1597

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

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

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

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

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

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

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

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

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

    
1716
#define DURATION_MAX_READ_SIZE 250000
1717

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

    
1727
    ic->cur_st = NULL;
1728

    
1729
    /* flush packet queue */
1730
    flush_packet_queue(ic);
1731

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

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

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

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

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

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

    
1804
    fill_all_stream_timings(ic);
1805

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1970
static void compute_chapters_end(AVFormatContext *s)
1971
{
1972
    unsigned int i;
1973

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

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

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

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

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

    
2029
    duration_error = av_mallocz(MAX_STREAMS * sizeof(*duration_error));
2030
    if (!duration_error) return AVERROR(ENOMEM);
2031

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

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

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

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

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

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

    
2121
        read_size += pkt->size;
2122

    
2123
        st = ic->streams[pkt->stream_index];
2124
        if(codec_info_nb_frames[st->index]>1) {
2125
            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){
2126
                av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2127
                break;
2128
            }
2129
            codec_info_duration[st->index] += pkt->duration;
2130
        }
2131
        if (pkt->duration != 0)
2132
            codec_info_nb_frames[st->index]++;
2133

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

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

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

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

    
2191
        count++;
2192
    }
2193

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

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

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

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

    
2249
    av_estimate_timings(ic, old_offset);
2250

    
2251
    compute_chapters_end(ic);
2252

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

    
2278
    av_free(duration_error);
2279

    
2280
    return ret;
2281
}
2282

    
2283
/*******************************************************/
2284

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

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

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

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

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

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

    
2364
    if (s->nb_streams >= MAX_STREAMS)
2365
        return NULL;
2366

    
2367
    st = av_mallocz(sizeof(AVStream));
2368
    if (!st)
2369
        return NULL;
2370

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

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

    
2395
    st->sample_aspect_ratio = (AVRational){0,1};
2396

    
2397
    s->streams[s->nb_streams++] = st;
2398
    return st;
2399
}
2400

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

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

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

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

    
2423
    return program;
2424
}
2425

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

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

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

    
2450
    return chapter;
2451
}
2452

    
2453
/************************************************************/
2454
/* output media file */
2455

    
2456
int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2457
{
2458
    int ret;
2459

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

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

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

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

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

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

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

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

    
2532
#if LIBAVFORMAT_VERSION_MAJOR < 53
2533
    ff_metadata_mux_compat(s);
2534
#endif
2535

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

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

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

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

    
2571
//    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);
2572

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

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

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

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

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

    
2602
        pkt->dts= st->pts_buffer[0];
2603
    }
2604

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

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

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

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

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

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

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

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

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

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

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

    
2679
    s->packet_buffer_end= this_pktl;
2680
next_non_null:
2681

    
2682
    this_pktl->next= *next_point;
2683

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

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

    
2695
    if (pkt->dts == AV_NOPTS_VALUE)
2696
        return 0;
2697

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

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

    
2706
    if(pkt){
2707
        ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
2708
    }
2709

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

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

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

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

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

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

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

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

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

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

    
2767
        ret= s->oformat->write_packet(s, &opkt);
2768

    
2769
        av_free_packet(&opkt);
2770
        pkt= NULL;
2771

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

    
2779
int av_write_trailer(AVFormatContext *s)
2780
{
2781
    int ret, i;
2782

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

    
2791
        ret= s->oformat->write_packet(s, &pkt);
2792

    
2793
        av_free_packet(&pkt);
2794

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

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

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

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

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

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

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

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

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

    
2946
}
2947

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

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

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

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

    
2990
#undef time
2991
    time_t now = time(0);
2992

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

    
3000
    memset(&dt, 0, sizeof(dt));
3001

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

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

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

    
3029
        if (*p == 'T' || *p == 't' || *p == ' ')
3030
            p++;
3031

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

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

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

    
3074
    t *= 1000000;
3075

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3332
    return buff;
3333
}
3334

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

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

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