Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ 67c10de7

History | View | Annotate | Download (110 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 "audiointerleave.h"
28
#include <sys/time.h>
29
#include <time.h>
30
#include <strings.h>
31
#include <stdarg.h>
32
#if CONFIG_NETWORK
33
#include "network.h"
34
#endif
35

    
36
#undef NDEBUG
37
#include <assert.h>
38

    
39
/**
40
 * @file libavformat/utils.c
41
 * various utility functions for use within FFmpeg
42
 */
43

    
44
unsigned avformat_version(void)
45
{
46
    return LIBAVFORMAT_VERSION_INT;
47
}
48

    
49
const char *avformat_configuration(void)
50
{
51
    return FFMPEG_CONFIGURATION;
52
}
53

    
54
const char *avformat_license(void)
55
{
56
#define LICENSE_PREFIX "libavformat license: "
57
    return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
58
}
59

    
60
/* fraction handling */
61

    
62
/**
63
 * f = val + (num / den) + 0.5.
64
 *
65
 * 'num' is normalized so that it is such as 0 <= num < den.
66
 *
67
 * @param f fractional number
68
 * @param val integer value
69
 * @param num must be >= 0
70
 * @param den must be >= 1
71
 */
72
static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
73
{
74
    num += (den >> 1);
75
    if (num >= den) {
76
        val += num / den;
77
        num = num % den;
78
    }
79
    f->val = val;
80
    f->num = num;
81
    f->den = den;
82
}
83

    
84
/**
85
 * Fractional addition to f: f = f + (incr / f->den).
86
 *
87
 * @param f fractional number
88
 * @param incr increment, can be positive or negative
89
 */
90
static void av_frac_add(AVFrac *f, int64_t incr)
91
{
92
    int64_t num, den;
93

    
94
    num = f->num + incr;
95
    den = f->den;
96
    if (num < 0) {
97
        f->val += num / den;
98
        num = num % den;
99
        if (num < 0) {
100
            num += den;
101
            f->val--;
102
        }
103
    } else if (num >= den) {
104
        f->val += num / den;
105
        num = num % den;
106
    }
107
    f->num = num;
108
}
109

    
110
/** head of registered input format linked list */
111
AVInputFormat *first_iformat = NULL;
112
/** head of registered output format linked list */
113
AVOutputFormat *first_oformat = NULL;
114

    
115
AVInputFormat  *av_iformat_next(AVInputFormat  *f)
116
{
117
    if(f) return f->next;
118
    else  return first_iformat;
119
}
120

    
121
AVOutputFormat *av_oformat_next(AVOutputFormat *f)
122
{
123
    if(f) return f->next;
124
    else  return first_oformat;
125
}
126

    
127
void av_register_input_format(AVInputFormat *format)
128
{
129
    AVInputFormat **p;
130
    p = &first_iformat;
131
    while (*p != NULL) p = &(*p)->next;
132
    *p = format;
133
    format->next = NULL;
134
}
135

    
136
void av_register_output_format(AVOutputFormat *format)
137
{
138
    AVOutputFormat **p;
139
    p = &first_oformat;
140
    while (*p != NULL) p = &(*p)->next;
141
    *p = format;
142
    format->next = NULL;
143
}
144

    
145
int av_match_ext(const char *filename, const char *extensions)
146
{
147
    const char *ext, *p;
148
    char ext1[32], *q;
149

    
150
    if(!filename)
151
        return 0;
152

    
153
    ext = strrchr(filename, '.');
154
    if (ext) {
155
        ext++;
156
        p = extensions;
157
        for(;;) {
158
            q = ext1;
159
            while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
160
                *q++ = *p++;
161
            *q = '\0';
162
            if (!strcasecmp(ext1, ext))
163
                return 1;
164
            if (*p == '\0')
165
                break;
166
            p++;
167
        }
168
    }
169
    return 0;
170
}
171

    
172
static int match_format(const char *name, const char *names)
173
{
174
    const char *p;
175
    int len, namelen;
176

    
177
    if (!name || !names)
178
        return 0;
179

    
180
    namelen = strlen(name);
181
    while ((p = strchr(names, ','))) {
182
        len = FFMAX(p - names, namelen);
183
        if (!strncasecmp(name, names, len))
184
            return 1;
185
        names = p+1;
186
    }
187
    return !strcasecmp(name, names);
188
}
189

    
190
#if LIBAVFORMAT_VERSION_MAJOR < 53
191
AVOutputFormat *guess_format(const char *short_name, const char *filename,
192
                             const char *mime_type)
193
{
194
    return av_guess_format(short_name, filename, mime_type);
195
}
196
#endif
197

    
198
AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
199
                                const char *mime_type)
200
{
201
    AVOutputFormat *fmt, *fmt_found;
202
    int score_max, score;
203

    
204
    /* specific test for image sequences */
205
#if CONFIG_IMAGE2_MUXER
206
    if (!short_name && filename &&
207
        av_filename_number_test(filename) &&
208
        av_guess_image2_codec(filename) != CODEC_ID_NONE) {
209
        return av_guess_format("image2", NULL, NULL);
210
    }
211
#endif
212
    /* Find the proper file type. */
213
    fmt_found = NULL;
214
    score_max = 0;
215
    fmt = first_oformat;
216
    while (fmt != NULL) {
217
        score = 0;
218
        if (fmt->name && short_name && !strcmp(fmt->name, short_name))
219
            score += 100;
220
        if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
221
            score += 10;
222
        if (filename && fmt->extensions &&
223
            av_match_ext(filename, fmt->extensions)) {
224
            score += 5;
225
        }
226
        if (score > score_max) {
227
            score_max = score;
228
            fmt_found = fmt;
229
        }
230
        fmt = fmt->next;
231
    }
232
    return fmt_found;
233
}
234

    
235
#if LIBAVFORMAT_VERSION_MAJOR < 53
236
AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
237
                             const char *mime_type)
238
{
239
    AVOutputFormat *fmt = av_guess_format(short_name, filename, mime_type);
240

    
241
    if (fmt) {
242
        AVOutputFormat *stream_fmt;
243
        char stream_format_name[64];
244

    
245
        snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
246
        stream_fmt = av_guess_format(stream_format_name, NULL, NULL);
247

    
248
        if (stream_fmt)
249
            fmt = stream_fmt;
250
    }
251

    
252
    return fmt;
253
}
254
#endif
255

    
256
enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
257
                            const char *filename, const char *mime_type, enum CodecType type){
258
    if(type == CODEC_TYPE_VIDEO){
259
        enum CodecID codec_id= CODEC_ID_NONE;
260

    
261
#if CONFIG_IMAGE2_MUXER
262
        if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
263
            codec_id= av_guess_image2_codec(filename);
264
        }
265
#endif
266
        if(codec_id == CODEC_ID_NONE)
267
            codec_id= fmt->video_codec;
268
        return codec_id;
269
    }else if(type == CODEC_TYPE_AUDIO)
270
        return fmt->audio_codec;
271
    else
272
        return CODEC_ID_NONE;
273
}
274

    
275
AVInputFormat *av_find_input_format(const char *short_name)
276
{
277
    AVInputFormat *fmt;
278
    for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
279
        if (match_format(short_name, fmt->name))
280
            return fmt;
281
    }
282
    return NULL;
283
}
284

    
285
/* memory handling */
286

    
287

    
288
int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
289
{
290
    int ret= av_new_packet(pkt, size);
291

    
292
    if(ret<0)
293
        return ret;
294

    
295
    pkt->pos= url_ftell(s);
296

    
297
    ret= get_buffer(s, pkt->data, size);
298
    if(ret<=0)
299
        av_free_packet(pkt);
300
    else
301
        av_shrink_packet(pkt, ret);
302

    
303
    return ret;
304
}
305

    
306

    
307
int av_filename_number_test(const char *filename)
308
{
309
    char buf[1024];
310
    return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
311
}
312

    
313
static AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
314
{
315
    AVInputFormat *fmt1, *fmt;
316
    int score;
317

    
318
    fmt = NULL;
319
    for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
320
        if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
321
            continue;
322
        score = 0;
323
        if (fmt1->read_probe) {
324
            score = fmt1->read_probe(pd);
325
        } else if (fmt1->extensions) {
326
            if (av_match_ext(pd->filename, fmt1->extensions)) {
327
                score = 50;
328
            }
329
        }
330
        if (score > *score_max) {
331
            *score_max = score;
332
            fmt = fmt1;
333
        }else if (score == *score_max)
334
            fmt = NULL;
335
    }
336
    return fmt;
337
}
338

    
339
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
340
    int score=0;
341
    return av_probe_input_format2(pd, is_opened, &score);
342
}
343

    
344
static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
345
{
346
    AVInputFormat *fmt;
347
    fmt = av_probe_input_format2(pd, 1, &score);
348

    
349
    if (fmt) {
350
        av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
351
               pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
352
        if (!strcmp(fmt->name, "mp3")) {
353
            st->codec->codec_id = CODEC_ID_MP3;
354
            st->codec->codec_type = CODEC_TYPE_AUDIO;
355
        } else if (!strcmp(fmt->name, "ac3")) {
356
            st->codec->codec_id = CODEC_ID_AC3;
357
            st->codec->codec_type = CODEC_TYPE_AUDIO;
358
        } else if (!strcmp(fmt->name, "eac3")) {
359
            st->codec->codec_id = CODEC_ID_EAC3;
360
            st->codec->codec_type = CODEC_TYPE_AUDIO;
361
        } else if (!strcmp(fmt->name, "mpegvideo")) {
362
            st->codec->codec_id = CODEC_ID_MPEG2VIDEO;
363
            st->codec->codec_type = CODEC_TYPE_VIDEO;
364
        } else if (!strcmp(fmt->name, "m4v")) {
365
            st->codec->codec_id = CODEC_ID_MPEG4;
366
            st->codec->codec_type = CODEC_TYPE_VIDEO;
367
        } else if (!strcmp(fmt->name, "h264")) {
368
            st->codec->codec_id = CODEC_ID_H264;
369
            st->codec->codec_type = CODEC_TYPE_VIDEO;
370
        } else if (!strcmp(fmt->name, "dts")) {
371
            st->codec->codec_id = CODEC_ID_DTS;
372
            st->codec->codec_type = CODEC_TYPE_AUDIO;
373
        }
374
    }
375
    return !!fmt;
376
}
377

    
378
/************************************************************/
379
/* input media file */
380

    
381
/**
382
 * Open a media file from an IO stream. 'fmt' must be specified.
383
 */
384
int av_open_input_stream(AVFormatContext **ic_ptr,
385
                         ByteIOContext *pb, const char *filename,
386
                         AVInputFormat *fmt, AVFormatParameters *ap)
387
{
388
    int err;
389
    AVFormatContext *ic;
390
    AVFormatParameters default_ap;
391

    
392
    if(!ap){
393
        ap=&default_ap;
394
        memset(ap, 0, sizeof(default_ap));
395
    }
396

    
397
    if(!ap->prealloced_context)
398
        ic = avformat_alloc_context();
399
    else
400
        ic = *ic_ptr;
401
    if (!ic) {
402
        err = AVERROR(ENOMEM);
403
        goto fail;
404
    }
405
    ic->iformat = fmt;
406
    ic->pb = pb;
407
    ic->duration = AV_NOPTS_VALUE;
408
    ic->start_time = AV_NOPTS_VALUE;
409
    av_strlcpy(ic->filename, filename, sizeof(ic->filename));
410

    
411
    /* allocate private data */
412
    if (fmt->priv_data_size > 0) {
413
        ic->priv_data = av_mallocz(fmt->priv_data_size);
414
        if (!ic->priv_data) {
415
            err = AVERROR(ENOMEM);
416
            goto fail;
417
        }
418
    } else {
419
        ic->priv_data = NULL;
420
    }
421

    
422
    if (ic->iformat->read_header) {
423
        err = ic->iformat->read_header(ic, ap);
424
        if (err < 0)
425
            goto fail;
426
    }
427

    
428
    if (pb && !ic->data_offset)
429
        ic->data_offset = url_ftell(ic->pb);
430

    
431
#if LIBAVFORMAT_VERSION_MAJOR < 53
432
    ff_metadata_demux_compat(ic);
433
#endif
434

    
435
    ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
436

    
437
    *ic_ptr = ic;
438
    return 0;
439
 fail:
440
    if (ic) {
441
        int i;
442
        av_freep(&ic->priv_data);
443
        for(i=0;i<ic->nb_streams;i++) {
444
            AVStream *st = ic->streams[i];
445
            if (st) {
446
                av_free(st->priv_data);
447
                av_free(st->codec->extradata);
448
            }
449
            av_free(st);
450
        }
451
    }
452
    av_free(ic);
453
    *ic_ptr = NULL;
454
    return err;
455
}
456

    
457
/** size of probe buffer, for guessing file type from file contents */
458
#define PROBE_BUF_MIN 2048
459
#define PROBE_BUF_MAX (1<<20)
460

    
461
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
462
                       AVInputFormat *fmt,
463
                       int buf_size,
464
                       AVFormatParameters *ap)
465
{
466
    int err, probe_size;
467
    AVProbeData probe_data, *pd = &probe_data;
468
    ByteIOContext *pb = NULL;
469
    void *logctx= ap && ap->prealloced_context ? *ic_ptr : NULL;
470

    
471
    pd->filename = "";
472
    if (filename)
473
        pd->filename = filename;
474
    pd->buf = NULL;
475
    pd->buf_size = 0;
476

    
477
    if (!fmt) {
478
        /* guess format if no file can be opened */
479
        fmt = av_probe_input_format(pd, 0);
480
    }
481

    
482
    /* Do not open file if the format does not need it. XXX: specific
483
       hack needed to handle RTSP/TCP */
484
    if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
485
        /* if no file needed do not try to open one */
486
        if ((err=url_fopen(&pb, filename, URL_RDONLY)) < 0) {
487
            goto fail;
488
        }
489
        if (buf_size > 0) {
490
            url_setbufsize(pb, buf_size);
491
        }
492

    
493
        for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
494
            int score= probe_size < PROBE_BUF_MAX ? AVPROBE_SCORE_MAX/4 : 0;
495
            /* read probe data */
496
            pd->buf= av_realloc(pd->buf, probe_size + AVPROBE_PADDING_SIZE);
497
            pd->buf_size = get_buffer(pb, pd->buf, probe_size);
498

    
499
            if ((int)pd->buf_size < 0) {
500
                err = pd->buf_size;
501
                goto fail;
502
            }
503

    
504
            memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
505
            if (url_fseek(pb, 0, SEEK_SET) < 0) {
506
                url_fclose(pb);
507
                if (url_fopen(&pb, filename, URL_RDONLY) < 0) {
508
                    pb = NULL;
509
                    err = AVERROR(EIO);
510
                    goto fail;
511
                }
512
            }
513
            /* guess file format */
514
            fmt = av_probe_input_format2(pd, 1, &score);
515
            if(fmt){
516
                if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
517
                    av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);
518
                }else
519
                    av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);
520
            }
521
        }
522
        av_freep(&pd->buf);
523
    }
524

    
525
    /* if still no format found, error */
526
    if (!fmt) {
527
        err = AVERROR_NOFMT;
528
        goto fail;
529
    }
530

    
531
    /* check filename in case an image number is expected */
532
    if (fmt->flags & AVFMT_NEEDNUMBER) {
533
        if (!av_filename_number_test(filename)) {
534
            err = AVERROR_NUMEXPECTED;
535
            goto fail;
536
        }
537
    }
538
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
539
    if (err)
540
        goto fail;
541
    return 0;
542
 fail:
543
    av_freep(&pd->buf);
544
    if (pb)
545
        url_fclose(pb);
546
    if (ap && ap->prealloced_context)
547
        av_free(*ic_ptr);
548
    *ic_ptr = NULL;
549
    return err;
550

    
551
}
552

    
553
/*******************************************************/
554

    
555
static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
556
                               AVPacketList **plast_pktl){
557
    AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
558
    if (!pktl)
559
        return NULL;
560

    
561
    if (*packet_buffer)
562
        (*plast_pktl)->next = pktl;
563
    else
564
        *packet_buffer = pktl;
565

    
566
    /* add the packet in the buffered packet list */
567
    *plast_pktl = pktl;
568
    pktl->pkt= *pkt;
569
    return &pktl->pkt;
570
}
571

    
572
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
573
{
574
    int ret, i;
575
    AVStream *st;
576

    
577
    for(;;){
578
        AVPacketList *pktl = s->raw_packet_buffer;
579

    
580
        if (pktl) {
581
            *pkt = pktl->pkt;
582
            if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||
583
               !s->streams[pkt->stream_index]->probe_packets ||
584
               s->raw_packet_buffer_remaining_size < pkt->size){
585
                AVProbeData *pd = &s->streams[pkt->stream_index]->probe_data;
586
                av_freep(&pd->buf);
587
                pd->buf_size = 0;
588
                s->raw_packet_buffer = pktl->next;
589
                s->raw_packet_buffer_remaining_size += pkt->size;
590
                av_free(pktl);
591
                return 0;
592
            }
593
        }
594

    
595
        av_init_packet(pkt);
596
        ret= s->iformat->read_packet(s, pkt);
597
        if (ret < 0) {
598
            if (!pktl || ret == AVERROR(EAGAIN))
599
                return ret;
600
            for (i = 0; i < s->nb_streams; i++)
601
                s->streams[i]->probe_packets = 0;
602
            continue;
603
        }
604
        st= s->streams[pkt->stream_index];
605

    
606
        switch(st->codec->codec_type){
607
        case CODEC_TYPE_VIDEO:
608
            if(s->video_codec_id)   st->codec->codec_id= s->video_codec_id;
609
            break;
610
        case CODEC_TYPE_AUDIO:
611
            if(s->audio_codec_id)   st->codec->codec_id= s->audio_codec_id;
612
            break;
613
        case CODEC_TYPE_SUBTITLE:
614
            if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
615
            break;
616
        }
617

    
618
        if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
619
                     !st->probe_packets))
620
            return ret;
621

    
622
        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
623
        s->raw_packet_buffer_remaining_size -= pkt->size;
624

    
625
        if(st->codec->codec_id == CODEC_ID_PROBE){
626
            AVProbeData *pd = &st->probe_data;
627
            av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
628
            --st->probe_packets;
629

    
630
            pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
631
            memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
632
            pd->buf_size += pkt->size;
633
            memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
634

    
635
            if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
636
                set_codec_from_probe_data(s, st, pd, 1);
637
                if(st->codec->codec_id != CODEC_ID_PROBE){
638
                    pd->buf_size=0;
639
                    av_freep(&pd->buf);
640
                    av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
641
                }
642
            }
643
        }
644
    }
645
}
646

    
647
/**********************************************************/
648

    
649
/**
650
 * Get the number of samples of an audio frame. Return -1 on error.
651
 */
652
static int get_audio_frame_size(AVCodecContext *enc, int size)
653
{
654
    int frame_size;
655

    
656
    if(enc->codec_id == CODEC_ID_VORBIS)
657
        return -1;
658

    
659
    if (enc->frame_size <= 1) {
660
        int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
661

    
662
        if (bits_per_sample) {
663
            if (enc->channels == 0)
664
                return -1;
665
            frame_size = (size << 3) / (bits_per_sample * enc->channels);
666
        } else {
667
            /* used for example by ADPCM codecs */
668
            if (enc->bit_rate == 0)
669
                return -1;
670
            frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
671
        }
672
    } else {
673
        frame_size = enc->frame_size;
674
    }
675
    return frame_size;
676
}
677

    
678

    
679
/**
680
 * Return the frame duration in seconds. Return 0 if not available.
681
 */
682
static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
683
                                   AVCodecParserContext *pc, AVPacket *pkt)
684
{
685
    int frame_size;
686

    
687
    *pnum = 0;
688
    *pden = 0;
689
    switch(st->codec->codec_type) {
690
    case CODEC_TYPE_VIDEO:
691
        if(st->time_base.num*1000LL > st->time_base.den){
692
            *pnum = st->time_base.num;
693
            *pden = st->time_base.den;
694
        }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
695
            *pnum = st->codec->time_base.num;
696
            *pden = st->codec->time_base.den;
697
            if (pc && pc->repeat_pict) {
698
                *pnum = (*pnum) * (1 + pc->repeat_pict);
699
            }
700
        }
701
        break;
702
    case CODEC_TYPE_AUDIO:
703
        frame_size = get_audio_frame_size(st->codec, pkt->size);
704
        if (frame_size < 0)
705
            break;
706
        *pnum = frame_size;
707
        *pden = st->codec->sample_rate;
708
        break;
709
    default:
710
        break;
711
    }
712
}
713

    
714
static int is_intra_only(AVCodecContext *enc){
715
    if(enc->codec_type == CODEC_TYPE_AUDIO){
716
        return 1;
717
    }else if(enc->codec_type == CODEC_TYPE_VIDEO){
718
        switch(enc->codec_id){
719
        case CODEC_ID_MJPEG:
720
        case CODEC_ID_MJPEGB:
721
        case CODEC_ID_LJPEG:
722
        case CODEC_ID_RAWVIDEO:
723
        case CODEC_ID_DVVIDEO:
724
        case CODEC_ID_HUFFYUV:
725
        case CODEC_ID_FFVHUFF:
726
        case CODEC_ID_ASV1:
727
        case CODEC_ID_ASV2:
728
        case CODEC_ID_VCR1:
729
        case CODEC_ID_DNXHD:
730
        case CODEC_ID_JPEG2000:
731
            return 1;
732
        default: break;
733
        }
734
    }
735
    return 0;
736
}
737

    
738
static void update_initial_timestamps(AVFormatContext *s, int stream_index,
739
                                      int64_t dts, int64_t pts)
740
{
741
    AVStream *st= s->streams[stream_index];
742
    AVPacketList *pktl= s->packet_buffer;
743

    
744
    if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
745
        return;
746

    
747
    st->first_dts= dts - st->cur_dts;
748
    st->cur_dts= dts;
749

    
750
    for(; pktl; pktl= pktl->next){
751
        if(pktl->pkt.stream_index != stream_index)
752
            continue;
753
        //FIXME think more about this check
754
        if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
755
            pktl->pkt.pts += st->first_dts;
756

    
757
        if(pktl->pkt.dts != AV_NOPTS_VALUE)
758
            pktl->pkt.dts += st->first_dts;
759

    
760
        if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
761
            st->start_time= pktl->pkt.pts;
762
    }
763
    if (st->start_time == AV_NOPTS_VALUE)
764
        st->start_time = pts;
765
}
766

    
767
static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
768
{
769
    AVPacketList *pktl= s->packet_buffer;
770
    int64_t cur_dts= 0;
771

    
772
    if(st->first_dts != AV_NOPTS_VALUE){
773
        cur_dts= st->first_dts;
774
        for(; pktl; pktl= pktl->next){
775
            if(pktl->pkt.stream_index == pkt->stream_index){
776
                if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
777
                    break;
778
                cur_dts -= pkt->duration;
779
            }
780
        }
781
        pktl= s->packet_buffer;
782
        st->first_dts = cur_dts;
783
    }else if(st->cur_dts)
784
        return;
785

    
786
    for(; pktl; pktl= pktl->next){
787
        if(pktl->pkt.stream_index != pkt->stream_index)
788
            continue;
789
        if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
790
           && !pktl->pkt.duration){
791
            pktl->pkt.dts= cur_dts;
792
            if(!st->codec->has_b_frames)
793
                pktl->pkt.pts= cur_dts;
794
            cur_dts += pkt->duration;
795
            pktl->pkt.duration= pkt->duration;
796
        }else
797
            break;
798
    }
799
    if(st->first_dts == AV_NOPTS_VALUE)
800
        st->cur_dts= cur_dts;
801
}
802

    
803
static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
804
                               AVCodecParserContext *pc, AVPacket *pkt)
805
{
806
    int num, den, presentation_delayed, delay, i;
807
    int64_t offset;
808

    
809
    if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
810
        pkt->dts= AV_NOPTS_VALUE;
811

    
812
    if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == FF_B_TYPE)
813
        //FIXME Set low_delay = 0 when has_b_frames = 1
814
        st->codec->has_b_frames = 1;
815

    
816
    /* do we have a video B-frame ? */
817
    delay= st->codec->has_b_frames;
818
    presentation_delayed = 0;
819
    /* XXX: need has_b_frame, but cannot get it if the codec is
820
        not initialized */
821
    if (delay &&
822
        pc && pc->pict_type != FF_B_TYPE)
823
        presentation_delayed = 1;
824

    
825
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
826
       /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
827
        pkt->dts -= 1LL<<st->pts_wrap_bits;
828
    }
829

    
830
    // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
831
    // we take the conservative approach and discard both
832
    // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
833
    if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
834
        av_log(s, AV_LOG_WARNING, "invalid dts/pts combination\n");
835
        pkt->dts= pkt->pts= AV_NOPTS_VALUE;
836
    }
837

    
838
    if (pkt->duration == 0) {
839
        compute_frame_duration(&num, &den, st, pc, pkt);
840
        if (den && num) {
841
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
842

    
843
            if(pkt->duration != 0 && s->packet_buffer)
844
                update_initial_durations(s, st, pkt);
845
        }
846
    }
847

    
848
    /* correct timestamps with byte offset if demuxers only have timestamps
849
       on packet boundaries */
850
    if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
851
        /* this will estimate bitrate based on this frame's duration and size */
852
        offset = av_rescale(pc->offset, pkt->duration, pkt->size);
853
        if(pkt->pts != AV_NOPTS_VALUE)
854
            pkt->pts += offset;
855
        if(pkt->dts != AV_NOPTS_VALUE)
856
            pkt->dts += offset;
857
    }
858

    
859
    if (pc && pc->dts_sync_point >= 0) {
860
        // we have synchronization info from the parser
861
        int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
862
        if (den > 0) {
863
            int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
864
            if (pkt->dts != AV_NOPTS_VALUE) {
865
                // got DTS from the stream, update reference timestamp
866
                st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
867
                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
868
            } else if (st->reference_dts != AV_NOPTS_VALUE) {
869
                // compute DTS based on reference timestamp
870
                pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
871
                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
872
            }
873
            if (pc->dts_sync_point > 0)
874
                st->reference_dts = pkt->dts; // new reference
875
        }
876
    }
877

    
878
    /* This may be redundant, but it should not hurt. */
879
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
880
        presentation_delayed = 1;
881

    
882
//    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);
883
    /* interpolate PTS and DTS if they are not present */
884
    //We skip H264 currently because delay and has_b_frames are not reliably set
885
    if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){
886
        if (presentation_delayed) {
887
            /* DTS = decompression timestamp */
888
            /* PTS = presentation timestamp */
889
            if (pkt->dts == AV_NOPTS_VALUE)
890
                pkt->dts = st->last_IP_pts;
891
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
892
            if (pkt->dts == AV_NOPTS_VALUE)
893
                pkt->dts = st->cur_dts;
894

    
895
            /* this is tricky: the dts must be incremented by the duration
896
            of the frame we are displaying, i.e. the last I- or P-frame */
897
            if (st->last_IP_duration == 0)
898
                st->last_IP_duration = pkt->duration;
899
            if(pkt->dts != AV_NOPTS_VALUE)
900
                st->cur_dts = pkt->dts + st->last_IP_duration;
901
            st->last_IP_duration  = pkt->duration;
902
            st->last_IP_pts= pkt->pts;
903
            /* cannot compute PTS if not present (we can compute it only
904
            by knowing the future */
905
        } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
906
            if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
907
                int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
908
                int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
909
                if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
910
                    pkt->pts += pkt->duration;
911
    //                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);
912
                }
913
            }
914

    
915
            /* presentation is not delayed : PTS and DTS are the same */
916
            if(pkt->pts == AV_NOPTS_VALUE)
917
                pkt->pts = pkt->dts;
918
            update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
919
            if(pkt->pts == AV_NOPTS_VALUE)
920
                pkt->pts = st->cur_dts;
921
            pkt->dts = pkt->pts;
922
            if(pkt->pts != AV_NOPTS_VALUE)
923
                st->cur_dts = pkt->pts + pkt->duration;
924
        }
925
    }
926

    
927
    if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
928
        st->pts_buffer[0]= pkt->pts;
929
        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
930
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
931
        if(pkt->dts == AV_NOPTS_VALUE)
932
            pkt->dts= st->pts_buffer[0];
933
        if(st->codec->codec_id == CODEC_ID_H264){ //we skiped it above so we try here
934
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
935
        }
936
        if(pkt->dts > st->cur_dts)
937
            st->cur_dts = pkt->dts;
938
    }
939

    
940
//    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);
941

    
942
    /* update flags */
943
    if(is_intra_only(st->codec))
944
        pkt->flags |= PKT_FLAG_KEY;
945
    else if (pc) {
946
        pkt->flags = 0;
947
        /* keyframe computation */
948
        if (pc->key_frame == 1)
949
            pkt->flags |= PKT_FLAG_KEY;
950
        else if (pc->key_frame == -1 && pc->pict_type == FF_I_TYPE)
951
            pkt->flags |= PKT_FLAG_KEY;
952
    }
953
    if (pc)
954
        pkt->convergence_duration = pc->convergence_duration;
955
}
956

    
957

    
958
static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
959
{
960
    AVStream *st;
961
    int len, ret, i;
962

    
963
    av_init_packet(pkt);
964

    
965
    for(;;) {
966
        /* select current input stream component */
967
        st = s->cur_st;
968
        if (st) {
969
            if (!st->need_parsing || !st->parser) {
970
                /* no parsing needed: we just output the packet as is */
971
                /* raw data support */
972
                *pkt = st->cur_pkt; st->cur_pkt.data= NULL;
973
                compute_pkt_fields(s, st, NULL, pkt);
974
                s->cur_st = NULL;
975
                if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
976
                    (pkt->flags & PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
977
                    ff_reduce_index(s, st->index);
978
                    av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
979
                }
980
                break;
981
            } else if (st->cur_len > 0 && st->discard < AVDISCARD_ALL) {
982
                len = av_parser_parse2(st->parser, st->codec, &pkt->data, &pkt->size,
983
                                       st->cur_ptr, st->cur_len,
984
                                       st->cur_pkt.pts, st->cur_pkt.dts,
985
                                       st->cur_pkt.pos);
986
                st->cur_pkt.pts = AV_NOPTS_VALUE;
987
                st->cur_pkt.dts = AV_NOPTS_VALUE;
988
                /* increment read pointer */
989
                st->cur_ptr += len;
990
                st->cur_len -= len;
991

    
992
                /* return packet if any */
993
                if (pkt->size) {
994
                got_packet:
995
                    pkt->duration = 0;
996
                    pkt->stream_index = st->index;
997
                    pkt->pts = st->parser->pts;
998
                    pkt->dts = st->parser->dts;
999
                    pkt->pos = st->parser->pos;
1000
                    pkt->destruct = NULL;
1001
                    compute_pkt_fields(s, st, st->parser, pkt);
1002

    
1003
                    if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & PKT_FLAG_KEY){
1004
                        ff_reduce_index(s, st->index);
1005
                        av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
1006
                                           0, 0, AVINDEX_KEYFRAME);
1007
                    }
1008

    
1009
                    break;
1010
                }
1011
            } else {
1012
                /* free packet */
1013
                av_free_packet(&st->cur_pkt);
1014
                s->cur_st = NULL;
1015
            }
1016
        } else {
1017
            AVPacket cur_pkt;
1018
            /* read next packet */
1019
            ret = av_read_packet(s, &cur_pkt);
1020
            if (ret < 0) {
1021
                if (ret == AVERROR(EAGAIN))
1022
                    return ret;
1023
                /* return the last frames, if any */
1024
                for(i = 0; i < s->nb_streams; i++) {
1025
                    st = s->streams[i];
1026
                    if (st->parser && st->need_parsing) {
1027
                        av_parser_parse2(st->parser, st->codec,
1028
                                        &pkt->data, &pkt->size,
1029
                                        NULL, 0,
1030
                                        AV_NOPTS_VALUE, AV_NOPTS_VALUE,
1031
                                        AV_NOPTS_VALUE);
1032
                        if (pkt->size)
1033
                            goto got_packet;
1034
                    }
1035
                }
1036
                /* no more packets: really terminate parsing */
1037
                return ret;
1038
            }
1039
            st = s->streams[cur_pkt.stream_index];
1040
            st->cur_pkt= cur_pkt;
1041

    
1042
            if(st->cur_pkt.pts != AV_NOPTS_VALUE &&
1043
               st->cur_pkt.dts != AV_NOPTS_VALUE &&
1044
               st->cur_pkt.pts < st->cur_pkt.dts){
1045
                av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1046
                    st->cur_pkt.stream_index,
1047
                    st->cur_pkt.pts,
1048
                    st->cur_pkt.dts,
1049
                    st->cur_pkt.size);
1050
//                av_free_packet(&st->cur_pkt);
1051
//                return -1;
1052
            }
1053

    
1054
            if(s->debug & FF_FDEBUG_TS)
1055
                av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1056
                    st->cur_pkt.stream_index,
1057
                    st->cur_pkt.pts,
1058
                    st->cur_pkt.dts,
1059
                    st->cur_pkt.size,
1060
                    st->cur_pkt.duration,
1061
                    st->cur_pkt.flags);
1062

    
1063
            s->cur_st = st;
1064
            st->cur_ptr = st->cur_pkt.data;
1065
            st->cur_len = st->cur_pkt.size;
1066
            if (st->need_parsing && !st->parser) {
1067
                st->parser = av_parser_init(st->codec->codec_id);
1068
                if (!st->parser) {
1069
                    /* no parser available: just output the raw packets */
1070
                    st->need_parsing = AVSTREAM_PARSE_NONE;
1071
                }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
1072
                    st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1073
                }
1074
                if(st->parser && (s->iformat->flags & AVFMT_GENERIC_INDEX)){
1075
                    st->parser->next_frame_offset=
1076
                    st->parser->cur_offset= st->cur_pkt.pos;
1077
                }
1078
            }
1079
        }
1080
    }
1081
    if(s->debug & FF_FDEBUG_TS)
1082
        av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1083
            pkt->stream_index,
1084
            pkt->pts,
1085
            pkt->dts,
1086
            pkt->size,
1087
            pkt->duration,
1088
            pkt->flags);
1089

    
1090
    return 0;
1091
}
1092

    
1093
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1094
{
1095
    AVPacketList *pktl;
1096
    int eof=0;
1097
    const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1098

    
1099
    for(;;){
1100
        pktl = s->packet_buffer;
1101
        if (pktl) {
1102
            AVPacket *next_pkt= &pktl->pkt;
1103

    
1104
            if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1105
                while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1106
                    if(   pktl->pkt.stream_index == next_pkt->stream_index
1107
                       && next_pkt->dts < pktl->pkt.dts
1108
                       && pktl->pkt.pts != pktl->pkt.dts //not b frame
1109
                       /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
1110
                        next_pkt->pts= pktl->pkt.dts;
1111
                    }
1112
                    pktl= pktl->next;
1113
                }
1114
                pktl = s->packet_buffer;
1115
            }
1116

    
1117
            if(   next_pkt->pts != AV_NOPTS_VALUE
1118
               || next_pkt->dts == AV_NOPTS_VALUE
1119
               || !genpts || eof){
1120
                /* read packet from packet buffer, if there is data */
1121
                *pkt = *next_pkt;
1122
                s->packet_buffer = pktl->next;
1123
                av_free(pktl);
1124
                return 0;
1125
            }
1126
        }
1127
        if(genpts){
1128
            int ret= av_read_frame_internal(s, pkt);
1129
            if(ret<0){
1130
                if(pktl && ret != AVERROR(EAGAIN)){
1131
                    eof=1;
1132
                    continue;
1133
                }else
1134
                    return ret;
1135
            }
1136

    
1137
            if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1138
                                           &s->packet_buffer_end)) < 0)
1139
                return AVERROR(ENOMEM);
1140
        }else{
1141
            assert(!s->packet_buffer);
1142
            return av_read_frame_internal(s, pkt);
1143
        }
1144
    }
1145
}
1146

    
1147
/* XXX: suppress the packet queue */
1148
static void flush_packet_queue(AVFormatContext *s)
1149
{
1150
    AVPacketList *pktl;
1151

    
1152
    for(;;) {
1153
        pktl = s->packet_buffer;
1154
        if (!pktl)
1155
            break;
1156
        s->packet_buffer = pktl->next;
1157
        av_free_packet(&pktl->pkt);
1158
        av_free(pktl);
1159
    }
1160
    while(s->raw_packet_buffer){
1161
        pktl = s->raw_packet_buffer;
1162
        s->raw_packet_buffer = pktl->next;
1163
        av_free_packet(&pktl->pkt);
1164
        av_free(pktl);
1165
    }
1166
    s->packet_buffer_end=
1167
    s->raw_packet_buffer_end= NULL;
1168
    s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1169
}
1170

    
1171
/*******************************************************/
1172
/* seek support */
1173

    
1174
int av_find_default_stream_index(AVFormatContext *s)
1175
{
1176
    int first_audio_index = -1;
1177
    int i;
1178
    AVStream *st;
1179

    
1180
    if (s->nb_streams <= 0)
1181
        return -1;
1182
    for(i = 0; i < s->nb_streams; i++) {
1183
        st = s->streams[i];
1184
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1185
            return i;
1186
        }
1187
        if (first_audio_index < 0 && st->codec->codec_type == CODEC_TYPE_AUDIO)
1188
            first_audio_index = i;
1189
    }
1190
    return first_audio_index >= 0 ? first_audio_index : 0;
1191
}
1192

    
1193
/**
1194
 * Flush the frame reader.
1195
 */
1196
void av_read_frame_flush(AVFormatContext *s)
1197
{
1198
    AVStream *st;
1199
    int i, j;
1200

    
1201
    flush_packet_queue(s);
1202

    
1203
    s->cur_st = NULL;
1204

    
1205
    /* for each stream, reset read state */
1206
    for(i = 0; i < s->nb_streams; i++) {
1207
        st = s->streams[i];
1208

    
1209
        if (st->parser) {
1210
            av_parser_close(st->parser);
1211
            st->parser = NULL;
1212
            av_free_packet(&st->cur_pkt);
1213
        }
1214
        st->last_IP_pts = AV_NOPTS_VALUE;
1215
        st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1216
        st->reference_dts = AV_NOPTS_VALUE;
1217
        /* fail safe */
1218
        st->cur_ptr = NULL;
1219
        st->cur_len = 0;
1220

    
1221
        st->probe_packets = MAX_PROBE_PACKETS;
1222

    
1223
        for(j=0; j<MAX_REORDER_DELAY+1; j++)
1224
            st->pts_buffer[j]= AV_NOPTS_VALUE;
1225
    }
1226
}
1227

    
1228
void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1229
    int i;
1230

    
1231
    for(i = 0; i < s->nb_streams; i++) {
1232
        AVStream *st = s->streams[i];
1233

    
1234
        st->cur_dts = av_rescale(timestamp,
1235
                                 st->time_base.den * (int64_t)ref_st->time_base.num,
1236
                                 st->time_base.num * (int64_t)ref_st->time_base.den);
1237
    }
1238
}
1239

    
1240
void ff_reduce_index(AVFormatContext *s, int stream_index)
1241
{
1242
    AVStream *st= s->streams[stream_index];
1243
    unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1244

    
1245
    if((unsigned)st->nb_index_entries >= max_entries){
1246
        int i;
1247
        for(i=0; 2*i<st->nb_index_entries; i++)
1248
            st->index_entries[i]= st->index_entries[2*i];
1249
        st->nb_index_entries= i;
1250
    }
1251
}
1252

    
1253
int av_add_index_entry(AVStream *st,
1254
                            int64_t pos, int64_t timestamp, int size, int distance, int flags)
1255
{
1256
    AVIndexEntry *entries, *ie;
1257
    int index;
1258

    
1259
    if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1260
        return -1;
1261

    
1262
    entries = av_fast_realloc(st->index_entries,
1263
                              &st->index_entries_allocated_size,
1264
                              (st->nb_index_entries + 1) *
1265
                              sizeof(AVIndexEntry));
1266
    if(!entries)
1267
        return -1;
1268

    
1269
    st->index_entries= entries;
1270

    
1271
    index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
1272

    
1273
    if(index<0){
1274
        index= st->nb_index_entries++;
1275
        ie= &entries[index];
1276
        assert(index==0 || ie[-1].timestamp < timestamp);
1277
    }else{
1278
        ie= &entries[index];
1279
        if(ie->timestamp != timestamp){
1280
            if(ie->timestamp <= timestamp)
1281
                return -1;
1282
            memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
1283
            st->nb_index_entries++;
1284
        }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1285
            distance= ie->min_distance;
1286
    }
1287

    
1288
    ie->pos = pos;
1289
    ie->timestamp = timestamp;
1290
    ie->min_distance= distance;
1291
    ie->size= size;
1292
    ie->flags = flags;
1293

    
1294
    return index;
1295
}
1296

    
1297
int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1298
                              int flags)
1299
{
1300
    AVIndexEntry *entries= st->index_entries;
1301
    int nb_entries= st->nb_index_entries;
1302
    int a, b, m;
1303
    int64_t timestamp;
1304

    
1305
    a = - 1;
1306
    b = nb_entries;
1307

    
1308
    //optimize appending index entries at the end
1309
    if(b && entries[b-1].timestamp < wanted_timestamp)
1310
        a= b-1;
1311

    
1312
    while (b - a > 1) {
1313
        m = (a + b) >> 1;
1314
        timestamp = entries[m].timestamp;
1315
        if(timestamp >= wanted_timestamp)
1316
            b = m;
1317
        if(timestamp <= wanted_timestamp)
1318
            a = m;
1319
    }
1320
    m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1321

    
1322
    if(!(flags & AVSEEK_FLAG_ANY)){
1323
        while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1324
            m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1325
        }
1326
    }
1327

    
1328
    if(m == nb_entries)
1329
        return -1;
1330
    return  m;
1331
}
1332

    
1333
#define DEBUG_SEEK
1334

    
1335
int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1336
    AVInputFormat *avif= s->iformat;
1337
    int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1338
    int64_t ts_min, ts_max, ts;
1339
    int index;
1340
    int64_t ret;
1341
    AVStream *st;
1342

    
1343
    if (stream_index < 0)
1344
        return -1;
1345

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

    
1350
    ts_max=
1351
    ts_min= AV_NOPTS_VALUE;
1352
    pos_limit= -1; //gcc falsely says it may be uninitialized
1353

    
1354
    st= s->streams[stream_index];
1355
    if(st->index_entries){
1356
        AVIndexEntry *e;
1357

    
1358
        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()
1359
        index= FFMAX(index, 0);
1360
        e= &st->index_entries[index];
1361

    
1362
        if(e->timestamp <= target_ts || e->pos == e->min_distance){
1363
            pos_min= e->pos;
1364
            ts_min= e->timestamp;
1365
#ifdef DEBUG_SEEK
1366
            av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1367
                   pos_min,ts_min);
1368
#endif
1369
        }else{
1370
            assert(index==0);
1371
        }
1372

    
1373
        index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1374
        assert(index < st->nb_index_entries);
1375
        if(index >= 0){
1376
            e= &st->index_entries[index];
1377
            assert(e->timestamp >= target_ts);
1378
            pos_max= e->pos;
1379
            ts_max= e->timestamp;
1380
            pos_limit= pos_max - e->min_distance;
1381
#ifdef DEBUG_SEEK
1382
            av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1383
                   pos_max,pos_limit, ts_max);
1384
#endif
1385
        }
1386
    }
1387

    
1388
    pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1389
    if(pos<0)
1390
        return -1;
1391

    
1392
    /* do the seek */
1393
    if ((ret = url_fseek(s->pb, pos, SEEK_SET)) < 0)
1394
        return ret;
1395

    
1396
    av_update_cur_dts(s, st, ts);
1397

    
1398
    return 0;
1399
}
1400

    
1401
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 )){
1402
    int64_t pos, ts;
1403
    int64_t start_pos, filesize;
1404
    int no_change;
1405

    
1406
#ifdef DEBUG_SEEK
1407
    av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1408
#endif
1409

    
1410
    if(ts_min == AV_NOPTS_VALUE){
1411
        pos_min = s->data_offset;
1412
        ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1413
        if (ts_min == AV_NOPTS_VALUE)
1414
            return -1;
1415
    }
1416

    
1417
    if(ts_max == AV_NOPTS_VALUE){
1418
        int step= 1024;
1419
        filesize = url_fsize(s->pb);
1420
        pos_max = filesize - 1;
1421
        do{
1422
            pos_max -= step;
1423
            ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1424
            step += step;
1425
        }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1426
        if (ts_max == AV_NOPTS_VALUE)
1427
            return -1;
1428

    
1429
        for(;;){
1430
            int64_t tmp_pos= pos_max + 1;
1431
            int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1432
            if(tmp_ts == AV_NOPTS_VALUE)
1433
                break;
1434
            ts_max= tmp_ts;
1435
            pos_max= tmp_pos;
1436
            if(tmp_pos >= filesize)
1437
                break;
1438
        }
1439
        pos_limit= pos_max;
1440
    }
1441

    
1442
    if(ts_min > ts_max){
1443
        return -1;
1444
    }else if(ts_min == ts_max){
1445
        pos_limit= pos_min;
1446
    }
1447

    
1448
    no_change=0;
1449
    while (pos_min < pos_limit) {
1450
#ifdef DEBUG_SEEK
1451
        av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1452
               pos_min, pos_max,
1453
               ts_min, ts_max);
1454
#endif
1455
        assert(pos_limit <= pos_max);
1456

    
1457
        if(no_change==0){
1458
            int64_t approximate_keyframe_distance= pos_max - pos_limit;
1459
            // interpolate position (better than dichotomy)
1460
            pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1461
                + pos_min - approximate_keyframe_distance;
1462
        }else if(no_change==1){
1463
            // bisection, if interpolation failed to change min or max pos last time
1464
            pos = (pos_min + pos_limit)>>1;
1465
        }else{
1466
            /* linear search if bisection failed, can only happen if there
1467
               are very few or no keyframes between min/max */
1468
            pos=pos_min;
1469
        }
1470
        if(pos <= pos_min)
1471
            pos= pos_min + 1;
1472
        else if(pos > pos_limit)
1473
            pos= pos_limit;
1474
        start_pos= pos;
1475

    
1476
        ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1477
        if(pos == pos_max)
1478
            no_change++;
1479
        else
1480
            no_change=0;
1481
#ifdef DEBUG_SEEK
1482
        av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1483
               pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit,
1484
               start_pos, no_change);
1485
#endif
1486
        if(ts == AV_NOPTS_VALUE){
1487
            av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1488
            return -1;
1489
        }
1490
        assert(ts != AV_NOPTS_VALUE);
1491
        if (target_ts <= ts) {
1492
            pos_limit = start_pos - 1;
1493
            pos_max = pos;
1494
            ts_max = ts;
1495
        }
1496
        if (target_ts >= ts) {
1497
            pos_min = pos;
1498
            ts_min = ts;
1499
        }
1500
    }
1501

    
1502
    pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1503
    ts  = (flags & AVSEEK_FLAG_BACKWARD) ?  ts_min :  ts_max;
1504
#ifdef DEBUG_SEEK
1505
    pos_min = pos;
1506
    ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1507
    pos_min++;
1508
    ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1509
    av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1510
           pos, ts_min, target_ts, ts_max);
1511
#endif
1512
    *ts_ret= ts;
1513
    return pos;
1514
}
1515

    
1516
static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1517
    int64_t pos_min, pos_max;
1518
#if 0
1519
    AVStream *st;
1520

1521
    if (stream_index < 0)
1522
        return -1;
1523

1524
    st= s->streams[stream_index];
1525
#endif
1526

    
1527
    pos_min = s->data_offset;
1528
    pos_max = url_fsize(s->pb) - 1;
1529

    
1530
    if     (pos < pos_min) pos= pos_min;
1531
    else if(pos > pos_max) pos= pos_max;
1532

    
1533
    url_fseek(s->pb, pos, SEEK_SET);
1534

    
1535
#if 0
1536
    av_update_cur_dts(s, st, ts);
1537
#endif
1538
    return 0;
1539
}
1540

    
1541
static int av_seek_frame_generic(AVFormatContext *s,
1542
                                 int stream_index, int64_t timestamp, int flags)
1543
{
1544
    int index;
1545
    int64_t ret;
1546
    AVStream *st;
1547
    AVIndexEntry *ie;
1548

    
1549
    st = s->streams[stream_index];
1550

    
1551
    index = av_index_search_timestamp(st, timestamp, flags);
1552

    
1553
    if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1554
        return -1;
1555

    
1556
    if(index < 0 || index==st->nb_index_entries-1){
1557
        int i;
1558
        AVPacket pkt;
1559

    
1560
        if(st->nb_index_entries){
1561
            assert(st->index_entries);
1562
            ie= &st->index_entries[st->nb_index_entries-1];
1563
            if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
1564
                return ret;
1565
            av_update_cur_dts(s, st, ie->timestamp);
1566
        }else{
1567
            if ((ret = url_fseek(s->pb, s->data_offset, SEEK_SET)) < 0)
1568
                return ret;
1569
        }
1570
        for(i=0;; i++) {
1571
            int ret;
1572
            do{
1573
                ret = av_read_frame(s, &pkt);
1574
            }while(ret == AVERROR(EAGAIN));
1575
            if(ret<0)
1576
                break;
1577
            av_free_packet(&pkt);
1578
            if(stream_index == pkt.stream_index){
1579
                if((pkt.flags & PKT_FLAG_KEY) && pkt.dts > timestamp)
1580
                    break;
1581
            }
1582
        }
1583
        index = av_index_search_timestamp(st, timestamp, flags);
1584
    }
1585
    if (index < 0)
1586
        return -1;
1587

    
1588
    av_read_frame_flush(s);
1589
    if (s->iformat->read_seek){
1590
        if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1591
            return 0;
1592
    }
1593
    ie = &st->index_entries[index];
1594
    if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
1595
        return ret;
1596
    av_update_cur_dts(s, st, ie->timestamp);
1597

    
1598
    return 0;
1599
}
1600

    
1601
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1602
{
1603
    int ret;
1604
    AVStream *st;
1605

    
1606
    av_read_frame_flush(s);
1607

    
1608
    if(flags & AVSEEK_FLAG_BYTE)
1609
        return av_seek_frame_byte(s, stream_index, timestamp, flags);
1610

    
1611
    if(stream_index < 0){
1612
        stream_index= av_find_default_stream_index(s);
1613
        if(stream_index < 0)
1614
            return -1;
1615

    
1616
        st= s->streams[stream_index];
1617
       /* timestamp for default must be expressed in AV_TIME_BASE units */
1618
        timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1619
    }
1620

    
1621
    /* first, we try the format specific seek */
1622
    if (s->iformat->read_seek)
1623
        ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1624
    else
1625
        ret = -1;
1626
    if (ret >= 0) {
1627
        return 0;
1628
    }
1629

    
1630
    if(s->iformat->read_timestamp)
1631
        return av_seek_frame_binary(s, stream_index, timestamp, flags);
1632
    else
1633
        return av_seek_frame_generic(s, stream_index, timestamp, flags);
1634
}
1635

    
1636
int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1637
{
1638
    if(min_ts > ts || max_ts < ts)
1639
        return -1;
1640

    
1641
    av_read_frame_flush(s);
1642

    
1643
    if (s->iformat->read_seek2)
1644
        return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1645

    
1646
    if(s->iformat->read_timestamp){
1647
        //try to seek via read_timestamp()
1648
    }
1649

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

    
1655
    // try some generic seek like av_seek_frame_generic() but with new ts semantics
1656
}
1657

    
1658
/*******************************************************/
1659

    
1660
/**
1661
 * Returns TRUE if the stream has accurate duration in any stream.
1662
 *
1663
 * @return TRUE if the stream has accurate duration for at least one component.
1664
 */
1665
static int av_has_duration(AVFormatContext *ic)
1666
{
1667
    int i;
1668
    AVStream *st;
1669

    
1670
    for(i = 0;i < ic->nb_streams; i++) {
1671
        st = ic->streams[i];
1672
        if (st->duration != AV_NOPTS_VALUE)
1673
            return 1;
1674
    }
1675
    return 0;
1676
}
1677

    
1678
/**
1679
 * Estimate the stream timings from the one of each components.
1680
 *
1681
 * Also computes the global bitrate if possible.
1682
 */
1683
static void av_update_stream_timings(AVFormatContext *ic)
1684
{
1685
    int64_t start_time, start_time1, end_time, end_time1;
1686
    int64_t duration, duration1;
1687
    int i;
1688
    AVStream *st;
1689

    
1690
    start_time = INT64_MAX;
1691
    end_time = INT64_MIN;
1692
    duration = INT64_MIN;
1693
    for(i = 0;i < ic->nb_streams; i++) {
1694
        st = ic->streams[i];
1695
        if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1696
            start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1697
            if (start_time1 < start_time)
1698
                start_time = start_time1;
1699
            if (st->duration != AV_NOPTS_VALUE) {
1700
                end_time1 = start_time1
1701
                          + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1702
                if (end_time1 > end_time)
1703
                    end_time = end_time1;
1704
            }
1705
        }
1706
        if (st->duration != AV_NOPTS_VALUE) {
1707
            duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1708
            if (duration1 > duration)
1709
                duration = duration1;
1710
        }
1711
    }
1712
    if (start_time != INT64_MAX) {
1713
        ic->start_time = start_time;
1714
        if (end_time != INT64_MIN) {
1715
            if (end_time - start_time > duration)
1716
                duration = end_time - start_time;
1717
        }
1718
    }
1719
    if (duration != INT64_MIN) {
1720
        ic->duration = duration;
1721
        if (ic->file_size > 0) {
1722
            /* compute the bitrate */
1723
            ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1724
                (double)ic->duration;
1725
        }
1726
    }
1727
}
1728

    
1729
static void fill_all_stream_timings(AVFormatContext *ic)
1730
{
1731
    int i;
1732
    AVStream *st;
1733

    
1734
    av_update_stream_timings(ic);
1735
    for(i = 0;i < ic->nb_streams; i++) {
1736
        st = ic->streams[i];
1737
        if (st->start_time == AV_NOPTS_VALUE) {
1738
            if(ic->start_time != AV_NOPTS_VALUE)
1739
                st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1740
            if(ic->duration != AV_NOPTS_VALUE)
1741
                st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1742
        }
1743
    }
1744
}
1745

    
1746
static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1747
{
1748
    int64_t filesize, duration;
1749
    int bit_rate, i;
1750
    AVStream *st;
1751

    
1752
    /* if bit_rate is already set, we believe it */
1753
    if (ic->bit_rate == 0) {
1754
        bit_rate = 0;
1755
        for(i=0;i<ic->nb_streams;i++) {
1756
            st = ic->streams[i];
1757
            bit_rate += st->codec->bit_rate;
1758
        }
1759
        ic->bit_rate = bit_rate;
1760
    }
1761

    
1762
    /* if duration is already set, we believe it */
1763
    if (ic->duration == AV_NOPTS_VALUE &&
1764
        ic->bit_rate != 0 &&
1765
        ic->file_size != 0)  {
1766
        filesize = ic->file_size;
1767
        if (filesize > 0) {
1768
            for(i = 0; i < ic->nb_streams; i++) {
1769
                st = ic->streams[i];
1770
                duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1771
                if (st->duration == AV_NOPTS_VALUE)
1772
                    st->duration = duration;
1773
            }
1774
        }
1775
    }
1776
}
1777

    
1778
#define DURATION_MAX_READ_SIZE 250000
1779
#define DURATION_MAX_RETRY 3
1780

    
1781
/* only usable for MPEG-PS streams */
1782
static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1783
{
1784
    AVPacket pkt1, *pkt = &pkt1;
1785
    AVStream *st;
1786
    int read_size, i, ret;
1787
    int64_t end_time, start_time[MAX_STREAMS];
1788
    int64_t filesize, offset, duration;
1789
    int retry=0;
1790

    
1791
    ic->cur_st = NULL;
1792

    
1793
    /* flush packet queue */
1794
    flush_packet_queue(ic);
1795

    
1796
    for(i=0;i<ic->nb_streams;i++) {
1797
        st = ic->streams[i];
1798
        if(st->start_time != AV_NOPTS_VALUE){
1799
            start_time[i]= st->start_time;
1800
        }else if(st->first_dts != AV_NOPTS_VALUE){
1801
            start_time[i]= st->first_dts;
1802
        }else
1803
            av_log(st->codec, AV_LOG_WARNING, "start time is not set in av_estimate_timings_from_pts\n");
1804

    
1805
        if (st->parser) {
1806
            av_parser_close(st->parser);
1807
            st->parser= NULL;
1808
            av_free_packet(&st->cur_pkt);
1809
        }
1810
    }
1811

    
1812
    /* estimate the end time (duration) */
1813
    /* XXX: may need to support wrapping */
1814
    filesize = ic->file_size;
1815
    end_time = AV_NOPTS_VALUE;
1816
    do{
1817
    offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
1818
    if (offset < 0)
1819
        offset = 0;
1820

    
1821
    url_fseek(ic->pb, offset, SEEK_SET);
1822
    read_size = 0;
1823
    for(;;) {
1824
        if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
1825
            break;
1826

    
1827
        do{
1828
            ret = av_read_packet(ic, pkt);
1829
        }while(ret == AVERROR(EAGAIN));
1830
        if (ret != 0)
1831
            break;
1832
        read_size += pkt->size;
1833
        st = ic->streams[pkt->stream_index];
1834
        if (pkt->pts != AV_NOPTS_VALUE &&
1835
            start_time[pkt->stream_index] != AV_NOPTS_VALUE) {
1836
            end_time = pkt->pts;
1837
            duration = end_time - start_time[pkt->stream_index];
1838
            if (duration < 0)
1839
                duration += 1LL<<st->pts_wrap_bits;
1840
            if (duration > 0) {
1841
                if (st->duration == AV_NOPTS_VALUE ||
1842
                    st->duration < duration)
1843
                    st->duration = duration;
1844
            }
1845
        }
1846
        av_free_packet(pkt);
1847
    }
1848
    }while(   end_time==AV_NOPTS_VALUE
1849
           && filesize > (DURATION_MAX_READ_SIZE<<retry)
1850
           && ++retry <= DURATION_MAX_RETRY);
1851

    
1852
    fill_all_stream_timings(ic);
1853

    
1854
    url_fseek(ic->pb, old_offset, SEEK_SET);
1855
    for(i=0; i<ic->nb_streams; i++){
1856
        st= ic->streams[i];
1857
        st->cur_dts= st->first_dts;
1858
        st->last_IP_pts = AV_NOPTS_VALUE;
1859
    }
1860
}
1861

    
1862
static void av_estimate_timings(AVFormatContext *ic, int64_t old_offset)
1863
{
1864
    int64_t file_size;
1865

    
1866
    /* get the file size, if possible */
1867
    if (ic->iformat->flags & AVFMT_NOFILE) {
1868
        file_size = 0;
1869
    } else {
1870
        file_size = url_fsize(ic->pb);
1871
        if (file_size < 0)
1872
            file_size = 0;
1873
    }
1874
    ic->file_size = file_size;
1875

    
1876
    if ((!strcmp(ic->iformat->name, "mpeg") ||
1877
         !strcmp(ic->iformat->name, "mpegts")) &&
1878
        file_size && !url_is_streamed(ic->pb)) {
1879
        /* get accurate estimate from the PTSes */
1880
        av_estimate_timings_from_pts(ic, old_offset);
1881
    } else if (av_has_duration(ic)) {
1882
        /* at least one component has timings - we use them for all
1883
           the components */
1884
        fill_all_stream_timings(ic);
1885
    } else {
1886
        av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
1887
        /* less precise: use bitrate info */
1888
        av_estimate_timings_from_bit_rate(ic);
1889
    }
1890
    av_update_stream_timings(ic);
1891

    
1892
#if 0
1893
    {
1894
        int i;
1895
        AVStream *st;
1896
        for(i = 0;i < ic->nb_streams; i++) {
1897
            st = ic->streams[i];
1898
        printf("%d: start_time: %0.3f duration: %0.3f\n",
1899
               i, (double)st->start_time / AV_TIME_BASE,
1900
               (double)st->duration / AV_TIME_BASE);
1901
        }
1902
        printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1903
               (double)ic->start_time / AV_TIME_BASE,
1904
               (double)ic->duration / AV_TIME_BASE,
1905
               ic->bit_rate / 1000);
1906
    }
1907
#endif
1908
}
1909

    
1910
static int has_codec_parameters(AVCodecContext *enc)
1911
{
1912
    int val;
1913
    switch(enc->codec_type) {
1914
    case CODEC_TYPE_AUDIO:
1915
        val = enc->sample_rate && enc->channels && enc->sample_fmt != SAMPLE_FMT_NONE;
1916
        if(!enc->frame_size &&
1917
           (enc->codec_id == CODEC_ID_VORBIS ||
1918
            enc->codec_id == CODEC_ID_AAC ||
1919
            enc->codec_id == CODEC_ID_MP1 ||
1920
            enc->codec_id == CODEC_ID_MP2 ||
1921
            enc->codec_id == CODEC_ID_MP3 ||
1922
            enc->codec_id == CODEC_ID_SPEEX))
1923
            return 0;
1924
        break;
1925
    case CODEC_TYPE_VIDEO:
1926
        val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
1927
        break;
1928
    default:
1929
        val = 1;
1930
        break;
1931
    }
1932
    return enc->codec_id != CODEC_ID_NONE && val != 0;
1933
}
1934

    
1935
static int try_decode_frame(AVStream *st, AVPacket *avpkt)
1936
{
1937
    int16_t *samples;
1938
    AVCodec *codec;
1939
    int got_picture, data_size, ret=0;
1940
    AVFrame picture;
1941

    
1942
    if(!st->codec->codec){
1943
        codec = avcodec_find_decoder(st->codec->codec_id);
1944
        if (!codec)
1945
            return -1;
1946
        ret = avcodec_open(st->codec, codec);
1947
        if (ret < 0)
1948
            return ret;
1949
    }
1950

    
1951
    if(!has_codec_parameters(st->codec)){
1952
        switch(st->codec->codec_type) {
1953
        case CODEC_TYPE_VIDEO:
1954
            avcodec_get_frame_defaults(&picture);
1955
            ret = avcodec_decode_video2(st->codec, &picture,
1956
                                        &got_picture, avpkt);
1957
            break;
1958
        case CODEC_TYPE_AUDIO:
1959
            data_size = FFMAX(avpkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
1960
            samples = av_malloc(data_size);
1961
            if (!samples)
1962
                goto fail;
1963
            ret = avcodec_decode_audio3(st->codec, samples,
1964
                                        &data_size, avpkt);
1965
            av_free(samples);
1966
            break;
1967
        default:
1968
            break;
1969
        }
1970
    }
1971
 fail:
1972
    return ret;
1973
}
1974

    
1975
unsigned int ff_codec_get_tag(const AVCodecTag *tags, int id)
1976
{
1977
    while (tags->id != CODEC_ID_NONE) {
1978
        if (tags->id == id)
1979
            return tags->tag;
1980
        tags++;
1981
    }
1982
    return 0;
1983
}
1984

    
1985
enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
1986
{
1987
    int i;
1988
    for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
1989
        if(tag == tags[i].tag)
1990
            return tags[i].id;
1991
    }
1992
    for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
1993
        if(   toupper((tag >> 0)&0xFF) == toupper((tags[i].tag >> 0)&0xFF)
1994
           && toupper((tag >> 8)&0xFF) == toupper((tags[i].tag >> 8)&0xFF)
1995
           && toupper((tag >>16)&0xFF) == toupper((tags[i].tag >>16)&0xFF)
1996
           && toupper((tag >>24)&0xFF) == toupper((tags[i].tag >>24)&0xFF))
1997
            return tags[i].id;
1998
    }
1999
    return CODEC_ID_NONE;
2000
}
2001

    
2002
unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
2003
{
2004
    int i;
2005
    for(i=0; tags && tags[i]; i++){
2006
        int tag= ff_codec_get_tag(tags[i], id);
2007
        if(tag) return tag;
2008
    }
2009
    return 0;
2010
}
2011

    
2012
enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2013
{
2014
    int i;
2015
    for(i=0; tags && tags[i]; i++){
2016
        enum CodecID id= ff_codec_get_id(tags[i], tag);
2017
        if(id!=CODEC_ID_NONE) return id;
2018
    }
2019
    return CODEC_ID_NONE;
2020
}
2021

    
2022
static void compute_chapters_end(AVFormatContext *s)
2023
{
2024
    unsigned int i;
2025

    
2026
    for (i=0; i+1<s->nb_chapters; i++)
2027
        if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2028
            assert(s->chapters[i]->start <= s->chapters[i+1]->start);
2029
            assert(!av_cmp_q(s->chapters[i]->time_base, s->chapters[i+1]->time_base));
2030
            s->chapters[i]->end = s->chapters[i+1]->start;
2031
        }
2032

    
2033
    if (s->nb_chapters && s->chapters[i]->end == AV_NOPTS_VALUE) {
2034
        assert(s->start_time != AV_NOPTS_VALUE);
2035
        assert(s->duration > 0);
2036
        s->chapters[i]->end = av_rescale_q(s->start_time + s->duration,
2037
                                           AV_TIME_BASE_Q,
2038
                                           s->chapters[i]->time_base);
2039
    }
2040
}
2041

    
2042
#define MAX_STD_TIMEBASES (60*12+5)
2043
static int get_std_framerate(int i){
2044
    if(i<60*12) return i*1001;
2045
    else        return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2046
}
2047

    
2048
/*
2049
 * Is the time base unreliable.
2050
 * This is a heuristic to balance between quick acceptance of the values in
2051
 * the headers vs. some extra checks.
2052
 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2053
 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2054
 * And there are "variable" fps files this needs to detect as well.
2055
 */
2056
static int tb_unreliable(AVCodecContext *c){
2057
    if(   c->time_base.den >= 101L*c->time_base.num
2058
       || c->time_base.den <    5L*c->time_base.num
2059
/*       || c->codec_tag == AV_RL32("DIVX")
2060
       || c->codec_tag == AV_RL32("XVID")*/
2061
       || c->codec_id == CODEC_ID_MPEG2VIDEO
2062
       || c->codec_id == CODEC_ID_H264
2063
       )
2064
        return 1;
2065
    return 0;
2066
}
2067

    
2068
int av_find_stream_info(AVFormatContext *ic)
2069
{
2070
    int i, count, ret, read_size, j;
2071
    AVStream *st;
2072
    AVPacket pkt1, *pkt;
2073
    int64_t last_dts[MAX_STREAMS];
2074
    int64_t duration_gcd[MAX_STREAMS]={0};
2075
    int duration_count[MAX_STREAMS]={0};
2076
    double (*duration_error)[MAX_STD_TIMEBASES];
2077
    int64_t old_offset = url_ftell(ic->pb);
2078
    int64_t codec_info_duration[MAX_STREAMS]={0};
2079

    
2080
    duration_error = av_mallocz(MAX_STREAMS * sizeof(*duration_error));
2081
    if (!duration_error) return AVERROR(ENOMEM);
2082

    
2083
    for(i=0;i<ic->nb_streams;i++) {
2084
        st = ic->streams[i];
2085
        if (st->codec->codec_id == CODEC_ID_AAC) {
2086
            st->codec->sample_rate = 0;
2087
            st->codec->frame_size = 0;
2088
            st->codec->channels = 0;
2089
        }
2090
        if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2091
/*            if(!st->time_base.num)
2092
                st->time_base= */
2093
            if(!st->codec->time_base.num)
2094
                st->codec->time_base= st->time_base;
2095
        }
2096
        //only for the split stuff
2097
        if (!st->parser) {
2098
            st->parser = av_parser_init(st->codec->codec_id);
2099
            if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2100
                st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2101
            }
2102
        }
2103
        assert(!st->codec->codec);
2104
        //try to just open decoders, in case this is enough to get parameters
2105
        if(!has_codec_parameters(st->codec)){
2106
            AVCodec *codec = avcodec_find_decoder(st->codec->codec_id);
2107
            if (codec)
2108
                avcodec_open(st->codec, codec);
2109
        }
2110
    }
2111

    
2112
    for(i=0;i<MAX_STREAMS;i++){
2113
        last_dts[i]= AV_NOPTS_VALUE;
2114
    }
2115

    
2116
    count = 0;
2117
    read_size = 0;
2118
    for(;;) {
2119
        if(url_interrupt_cb()){
2120
            ret= AVERROR(EINTR);
2121
            av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2122
            break;
2123
        }
2124

    
2125
        /* check if one codec still needs to be handled */
2126
        for(i=0;i<ic->nb_streams;i++) {
2127
            st = ic->streams[i];
2128
            if (!has_codec_parameters(st->codec))
2129
                break;
2130
            /* variable fps and no guess at the real fps */
2131
            if(   tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)
2132
               && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)
2133
                break;
2134
            if(st->parser && st->parser->parser->split && !st->codec->extradata)
2135
                break;
2136
            if(st->first_dts == AV_NOPTS_VALUE)
2137
                break;
2138
        }
2139
        if (i == ic->nb_streams) {
2140
            /* NOTE: if the format has no header, then we need to read
2141
               some packets to get most of the streams, so we cannot
2142
               stop here */
2143
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2144
                /* if we found the info for all the codecs, we can stop */
2145
                ret = count;
2146
                av_log(ic, AV_LOG_DEBUG, "All info found\n");
2147
                break;
2148
            }
2149
        }
2150
        /* we did not get all the codec info, but we read too much data */
2151
        if (read_size >= ic->probesize) {
2152
            ret = count;
2153
            av_log(ic, AV_LOG_WARNING, "MAX_READ_SIZE:%d reached\n", ic->probesize);
2154
            break;
2155
        }
2156

    
2157
        /* NOTE: a new stream can be added there if no header in file
2158
           (AVFMTCTX_NOHEADER) */
2159
        ret = av_read_frame_internal(ic, &pkt1);
2160
        if(ret == AVERROR(EAGAIN))
2161
            continue;
2162
        if (ret < 0) {
2163
            /* EOF or error */
2164
            ret = -1; /* we could not have all the codec parameters before EOF */
2165
            for(i=0;i<ic->nb_streams;i++) {
2166
                st = ic->streams[i];
2167
                if (!has_codec_parameters(st->codec)){
2168
                    char buf[256];
2169
                    avcodec_string(buf, sizeof(buf), st->codec, 0);
2170
                    av_log(ic, AV_LOG_WARNING, "Could not find codec parameters (%s)\n", buf);
2171
                } else {
2172
                    ret = 0;
2173
                }
2174
            }
2175
            break;
2176
        }
2177

    
2178
        pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
2179
        if(av_dup_packet(pkt) < 0) {
2180
            av_free(duration_error);
2181
            return AVERROR(ENOMEM);
2182
        }
2183

    
2184
        read_size += pkt->size;
2185

    
2186
        st = ic->streams[pkt->stream_index];
2187
        if(st->codec_info_nb_frames>1) {
2188
            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){
2189
                av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2190
                break;
2191
            }
2192
            codec_info_duration[st->index] += pkt->duration;
2193
        }
2194
            st->codec_info_nb_frames++;
2195

    
2196
        {
2197
            int index= pkt->stream_index;
2198
            int64_t last= last_dts[index];
2199
            int64_t duration= pkt->dts - last;
2200

    
2201
            if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
2202
                double dur= duration * av_q2d(st->time_base);
2203

    
2204
//                if(st->codec->codec_type == CODEC_TYPE_VIDEO)
2205
//                    av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
2206
                if(duration_count[index] < 2)
2207
                    memset(duration_error[index], 0, sizeof(*duration_error));
2208
                for(i=1; i<MAX_STD_TIMEBASES; i++){
2209
                    int framerate= get_std_framerate(i);
2210
                    int ticks= lrintf(dur*framerate/(1001*12));
2211
                    double error= dur - ticks*1001*12/(double)framerate;
2212
                    duration_error[index][i] += error*error;
2213
                }
2214
                duration_count[index]++;
2215
                // ignore the first 4 values, they might have some random jitter
2216
                if (duration_count[index] > 3)
2217
                    duration_gcd[index] = av_gcd(duration_gcd[index], duration);
2218
            }
2219
            if(last == AV_NOPTS_VALUE || duration_count[index]<=1)
2220
                last_dts[pkt->stream_index]= pkt->dts;
2221
        }
2222
        if(st->parser && st->parser->parser->split && !st->codec->extradata){
2223
            int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2224
            if(i){
2225
                st->codec->extradata_size= i;
2226
                st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2227
                memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2228
                memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2229
            }
2230
        }
2231

    
2232
        /* if still no information, we try to open the codec and to
2233
           decompress the frame. We try to avoid that in most cases as
2234
           it takes longer and uses more memory. For MPEG-4, we need to
2235
           decompress for QuickTime. */
2236
        if (!has_codec_parameters(st->codec))
2237
            try_decode_frame(st, pkt);
2238

    
2239
        count++;
2240
    }
2241

    
2242
    // close codecs which were opened in try_decode_frame()
2243
    for(i=0;i<ic->nb_streams;i++) {
2244
        st = ic->streams[i];
2245
        if(st->codec->codec)
2246
            avcodec_close(st->codec);
2247
    }
2248
    for(i=0;i<ic->nb_streams;i++) {
2249
        st = ic->streams[i];
2250
        if(st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && codec_info_duration[i])
2251
            av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2252
                     (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,
2253
                      codec_info_duration[i]    *(int64_t)st->time_base.num, 60000);
2254
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2255
            if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample)
2256
                st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2257

    
2258
            // the check for tb_unreliable() is not completely correct, since this is not about handling
2259
            // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2260
            // ipmovie.c produces.
2261
            if (tb_unreliable(st->codec) && duration_count[i] > 15 && duration_gcd[i] > 1 && !st->r_frame_rate.num)
2262
                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);
2263
            if(duration_count[i] && !st->r_frame_rate.num
2264
               && tb_unreliable(st->codec) /*&&
2265
               //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2266
               st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den*/){
2267
                int num = 0;
2268
                double best_error= 2*av_q2d(st->time_base);
2269
                best_error= best_error*best_error*duration_count[i]*1000*12*30;
2270

    
2271
                for(j=1; j<MAX_STD_TIMEBASES; j++){
2272
                    double error= duration_error[i][j] * get_std_framerate(j);
2273
//                    if(st->codec->codec_type == CODEC_TYPE_VIDEO)
2274
//                        av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
2275
                    if(error < best_error){
2276
                        best_error= error;
2277
                        num = get_std_framerate(j);
2278
                    }
2279
                }
2280
                // do not increase frame rate by more than 1 % in order to match a standard rate.
2281
                if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
2282
                    av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2283
            }
2284

    
2285
            if (!st->r_frame_rate.num){
2286
                if(    st->codec->time_base.den * (int64_t)st->time_base.num
2287
                    <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){
2288
                    st->r_frame_rate.num = st->codec->time_base.den;
2289
                    st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
2290
                }else{
2291
                    st->r_frame_rate.num = st->time_base.den;
2292
                    st->r_frame_rate.den = st->time_base.num;
2293
                }
2294
            }
2295
        }else if(st->codec->codec_type == CODEC_TYPE_AUDIO) {
2296
            if(!st->codec->bits_per_coded_sample)
2297
                st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2298
        }
2299
    }
2300

    
2301
    av_estimate_timings(ic, old_offset);
2302

    
2303
    compute_chapters_end(ic);
2304

    
2305
#if 0
2306
    /* correct DTS for B-frame streams with no timestamps */
2307
    for(i=0;i<ic->nb_streams;i++) {
2308
        st = ic->streams[i];
2309
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2310
            if(b-frames){
2311
                ppktl = &ic->packet_buffer;
2312
                while(ppkt1){
2313
                    if(ppkt1->stream_index != i)
2314
                        continue;
2315
                    if(ppkt1->pkt->dts < 0)
2316
                        break;
2317
                    if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2318
                        break;
2319
                    ppkt1->pkt->dts -= delta;
2320
                    ppkt1= ppkt1->next;
2321
                }
2322
                if(ppkt1)
2323
                    continue;
2324
                st->cur_dts -= delta;
2325
            }
2326
        }
2327
    }
2328
#endif
2329

    
2330
    av_free(duration_error);
2331

    
2332
    return ret;
2333
}
2334

    
2335
/*******************************************************/
2336

    
2337
int av_read_play(AVFormatContext *s)
2338
{
2339
    if (s->iformat->read_play)
2340
        return s->iformat->read_play(s);
2341
    if (s->pb)
2342
        return av_url_read_fpause(s->pb, 0);
2343
    return AVERROR(ENOSYS);
2344
}
2345

    
2346
int av_read_pause(AVFormatContext *s)
2347
{
2348
    if (s->iformat->read_pause)
2349
        return s->iformat->read_pause(s);
2350
    if (s->pb)
2351
        return av_url_read_fpause(s->pb, 1);
2352
    return AVERROR(ENOSYS);
2353
}
2354

    
2355
void av_close_input_stream(AVFormatContext *s)
2356
{
2357
    int i;
2358
    AVStream *st;
2359

    
2360
    if (s->iformat->read_close)
2361
        s->iformat->read_close(s);
2362
    for(i=0;i<s->nb_streams;i++) {
2363
        /* free all data in a stream component */
2364
        st = s->streams[i];
2365
        if (st->parser) {
2366
            av_parser_close(st->parser);
2367
            av_free_packet(&st->cur_pkt);
2368
        }
2369
        av_metadata_free(&st->metadata);
2370
        av_free(st->index_entries);
2371
        av_free(st->codec->extradata);
2372
        av_free(st->codec);
2373
#if LIBAVFORMAT_VERSION_INT < (53<<16)
2374
        av_free(st->filename);
2375
#endif
2376
        av_free(st->priv_data);
2377
        av_free(st);
2378
    }
2379
    for(i=s->nb_programs-1; i>=0; i--) {
2380
#if LIBAVFORMAT_VERSION_INT < (53<<16)
2381
        av_freep(&s->programs[i]->provider_name);
2382
        av_freep(&s->programs[i]->name);
2383
#endif
2384
        av_metadata_free(&s->programs[i]->metadata);
2385
        av_freep(&s->programs[i]->stream_index);
2386
        av_freep(&s->programs[i]);
2387
    }
2388
    av_freep(&s->programs);
2389
    flush_packet_queue(s);
2390
    av_freep(&s->priv_data);
2391
    while(s->nb_chapters--) {
2392
#if LIBAVFORMAT_VERSION_INT < (53<<16)
2393
        av_free(s->chapters[s->nb_chapters]->title);
2394
#endif
2395
        av_metadata_free(&s->chapters[s->nb_chapters]->metadata);
2396
        av_free(s->chapters[s->nb_chapters]);
2397
    }
2398
    av_freep(&s->chapters);
2399
    av_metadata_free(&s->metadata);
2400
    av_free(s);
2401
}
2402

    
2403
void av_close_input_file(AVFormatContext *s)
2404
{
2405
    ByteIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
2406
    av_close_input_stream(s);
2407
    if (pb)
2408
        url_fclose(pb);
2409
}
2410

    
2411
AVStream *av_new_stream(AVFormatContext *s, int id)
2412
{
2413
    AVStream *st;
2414
    int i;
2415

    
2416
    if (s->nb_streams >= MAX_STREAMS)
2417
        return NULL;
2418

    
2419
    st = av_mallocz(sizeof(AVStream));
2420
    if (!st)
2421
        return NULL;
2422

    
2423
    st->codec= avcodec_alloc_context();
2424
    if (s->iformat) {
2425
        /* no default bitrate if decoding */
2426
        st->codec->bit_rate = 0;
2427
    }
2428
    st->index = s->nb_streams;
2429
    st->id = id;
2430
    st->start_time = AV_NOPTS_VALUE;
2431
    st->duration = AV_NOPTS_VALUE;
2432
        /* we set the current DTS to 0 so that formats without any timestamps
2433
           but durations get some timestamps, formats with some unknown
2434
           timestamps have their first few packets buffered and the
2435
           timestamps corrected before they are returned to the user */
2436
    st->cur_dts = 0;
2437
    st->first_dts = AV_NOPTS_VALUE;
2438
    st->probe_packets = MAX_PROBE_PACKETS;
2439

    
2440
    /* default pts setting is MPEG-like */
2441
    av_set_pts_info(st, 33, 1, 90000);
2442
    st->last_IP_pts = AV_NOPTS_VALUE;
2443
    for(i=0; i<MAX_REORDER_DELAY+1; i++)
2444
        st->pts_buffer[i]= AV_NOPTS_VALUE;
2445
    st->reference_dts = AV_NOPTS_VALUE;
2446

    
2447
    st->sample_aspect_ratio = (AVRational){0,1};
2448

    
2449
    s->streams[s->nb_streams++] = st;
2450
    return st;
2451
}
2452

    
2453
AVProgram *av_new_program(AVFormatContext *ac, int id)
2454
{
2455
    AVProgram *program=NULL;
2456
    int i;
2457

    
2458
#ifdef DEBUG_SI
2459
    av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id);
2460
#endif
2461

    
2462
    for(i=0; i<ac->nb_programs; i++)
2463
        if(ac->programs[i]->id == id)
2464
            program = ac->programs[i];
2465

    
2466
    if(!program){
2467
        program = av_mallocz(sizeof(AVProgram));
2468
        if (!program)
2469
            return NULL;
2470
        dynarray_add(&ac->programs, &ac->nb_programs, program);
2471
        program->discard = AVDISCARD_NONE;
2472
    }
2473
    program->id = id;
2474

    
2475
    return program;
2476
}
2477

    
2478
AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2479
{
2480
    AVChapter *chapter = NULL;
2481
    int i;
2482

    
2483
    for(i=0; i<s->nb_chapters; i++)
2484
        if(s->chapters[i]->id == id)
2485
            chapter = s->chapters[i];
2486

    
2487
    if(!chapter){
2488
        chapter= av_mallocz(sizeof(AVChapter));
2489
        if(!chapter)
2490
            return NULL;
2491
        dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2492
    }
2493
#if LIBAVFORMAT_VERSION_INT < (53<<16)
2494
    av_free(chapter->title);
2495
#endif
2496
    av_metadata_set(&chapter->metadata, "title", title);
2497
    chapter->id    = id;
2498
    chapter->time_base= time_base;
2499
    chapter->start = start;
2500
    chapter->end   = end;
2501

    
2502
    return chapter;
2503
}
2504

    
2505
/************************************************************/
2506
/* output media file */
2507

    
2508
int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2509
{
2510
    int ret;
2511

    
2512
    if (s->oformat->priv_data_size > 0) {
2513
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
2514
        if (!s->priv_data)
2515
            return AVERROR(ENOMEM);
2516
    } else
2517
        s->priv_data = NULL;
2518

    
2519
    if (s->oformat->set_parameters) {
2520
        ret = s->oformat->set_parameters(s, ap);
2521
        if (ret < 0)
2522
            return ret;
2523
    }
2524
    return 0;
2525
}
2526

    
2527
int av_write_header(AVFormatContext *s)
2528
{
2529
    int ret, i;
2530
    AVStream *st;
2531

    
2532
    // some sanity checks
2533
    if (s->nb_streams == 0) {
2534
        av_log(s, AV_LOG_ERROR, "no streams\n");
2535
        return -1;
2536
    }
2537

    
2538
    for(i=0;i<s->nb_streams;i++) {
2539
        st = s->streams[i];
2540

    
2541
        switch (st->codec->codec_type) {
2542
        case CODEC_TYPE_AUDIO:
2543
            if(st->codec->sample_rate<=0){
2544
                av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2545
                return -1;
2546
            }
2547
            if(!st->codec->block_align)
2548
                st->codec->block_align = st->codec->channels *
2549
                    av_get_bits_per_sample(st->codec->codec_id) >> 3;
2550
            break;
2551
        case CODEC_TYPE_VIDEO:
2552
            if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2553
                av_log(s, AV_LOG_ERROR, "time base not set\n");
2554
                return -1;
2555
            }
2556
            if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){
2557
                av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2558
                return -1;
2559
            }
2560
            if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)){
2561
                av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");
2562
                return -1;
2563
            }
2564
            break;
2565
        }
2566

    
2567
        if(s->oformat->codec_tag){
2568
            if(st->codec->codec_tag){
2569
                //FIXME
2570
                //check that tag + id is in the table
2571
                //if neither is in the table -> OK
2572
                //if tag is in the table with another id -> FAIL
2573
                //if id is in the table with another tag -> FAIL unless strict < ?
2574
            }else
2575
                st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
2576
        }
2577

    
2578
        if(s->oformat->flags & AVFMT_GLOBALHEADER &&
2579
            !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))
2580
          av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);
2581
    }
2582

    
2583
    if (!s->priv_data && s->oformat->priv_data_size > 0) {
2584
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
2585
        if (!s->priv_data)
2586
            return AVERROR(ENOMEM);
2587
    }
2588

    
2589
#if LIBAVFORMAT_VERSION_MAJOR < 53
2590
    ff_metadata_mux_compat(s);
2591
#endif
2592

    
2593
    /* set muxer identification string */
2594
    if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
2595
        AVMetadata *m;
2596
        AVMetadataTag *t;
2597

    
2598
        if (!(m = av_mallocz(sizeof(AVMetadata))))
2599
            return AVERROR(ENOMEM);
2600
        av_metadata_set2(&m, "encoder", LIBAVFORMAT_IDENT, 0);
2601
        metadata_conv(&m, s->oformat->metadata_conv, NULL);
2602
        if ((t = av_metadata_get(m, "", NULL, AV_METADATA_IGNORE_SUFFIX)))
2603
            av_metadata_set2(&s->metadata, t->key, t->value, 0);
2604
        av_metadata_free(&m);
2605
    }
2606

    
2607
    if(s->oformat->write_header){
2608
        ret = s->oformat->write_header(s);
2609
        if (ret < 0)
2610
            return ret;
2611
    }
2612

    
2613
    /* init PTS generation */
2614
    for(i=0;i<s->nb_streams;i++) {
2615
        int64_t den = AV_NOPTS_VALUE;
2616
        st = s->streams[i];
2617

    
2618
        switch (st->codec->codec_type) {
2619
        case CODEC_TYPE_AUDIO:
2620
            den = (int64_t)st->time_base.num * st->codec->sample_rate;
2621
            break;
2622
        case CODEC_TYPE_VIDEO:
2623
            den = (int64_t)st->time_base.num * st->codec->time_base.den;
2624
            break;
2625
        default:
2626
            break;
2627
        }
2628
        if (den != AV_NOPTS_VALUE) {
2629
            if (den <= 0)
2630
                return AVERROR_INVALIDDATA;
2631
            av_frac_init(&st->pts, 0, 0, den);
2632
        }
2633
    }
2634
    return 0;
2635
}
2636

    
2637
//FIXME merge with compute_pkt_fields
2638
static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){
2639
    int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
2640
    int num, den, frame_size, i;
2641

    
2642
//    av_log(s, 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);
2643

    
2644
/*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2645
        return -1;*/
2646

    
2647
    /* duration field */
2648
    if (pkt->duration == 0) {
2649
        compute_frame_duration(&num, &den, st, NULL, pkt);
2650
        if (den && num) {
2651
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
2652
        }
2653
    }
2654

    
2655
    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
2656
        pkt->pts= pkt->dts;
2657

    
2658
    //XXX/FIXME this is a temporary hack until all encoders output pts
2659
    if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
2660
        pkt->dts=
2661
//        pkt->pts= st->cur_dts;
2662
        pkt->pts= st->pts.val;
2663
    }
2664

    
2665
    //calculate dts from pts
2666
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
2667
        st->pts_buffer[0]= pkt->pts;
2668
        for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
2669
            st->pts_buffer[i]= pkt->pts + (i-delay-1) * pkt->duration;
2670
        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
2671
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
2672

    
2673
        pkt->dts= st->pts_buffer[0];
2674
    }
2675

    
2676
    if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2677
        av_log(s, AV_LOG_ERROR,
2678
               "st:%d error, non monotone timestamps %"PRId64" >= %"PRId64"\n",
2679
               st->index, st->cur_dts, pkt->dts);
2680
        return -1;
2681
    }
2682
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2683
        av_log(s, AV_LOG_ERROR, "st:%d error, pts < dts\n", st->index);
2684
        return -1;
2685
    }
2686

    
2687
//    av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
2688
    st->cur_dts= pkt->dts;
2689
    st->pts.val= pkt->dts;
2690

    
2691
    /* update pts */
2692
    switch (st->codec->codec_type) {
2693
    case CODEC_TYPE_AUDIO:
2694
        frame_size = get_audio_frame_size(st->codec, pkt->size);
2695

    
2696
        /* HACK/FIXME, we skip the initial 0 size packets as they are most
2697
           likely equal to the encoder delay, but it would be better if we
2698
           had the real timestamps from the encoder */
2699
        if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2700
            av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2701
        }
2702
        break;
2703
    case CODEC_TYPE_VIDEO:
2704
        av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
2705
        break;
2706
    default:
2707
        break;
2708
    }
2709
    return 0;
2710
}
2711

    
2712
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2713
{
2714
    int ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
2715

    
2716
    if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2717
        return ret;
2718

    
2719
    ret= s->oformat->write_packet(s, pkt);
2720
    if(!ret)
2721
        ret= url_ferror(s->pb);
2722
    return ret;
2723
}
2724

    
2725
void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
2726
                              int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
2727
{
2728
    AVPacketList **next_point, *this_pktl;
2729

    
2730
    this_pktl = av_mallocz(sizeof(AVPacketList));
2731
    this_pktl->pkt= *pkt;
2732
    pkt->destruct= NULL;             // do not free original but only the copy
2733
    av_dup_packet(&this_pktl->pkt);  // duplicate the packet if it uses non-alloced memory
2734

    
2735
    if(s->streams[pkt->stream_index]->last_in_packet_buffer){
2736
        next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
2737
    }else
2738
        next_point = &s->packet_buffer;
2739

    
2740
    if(*next_point){
2741
        if(compare(s, &s->packet_buffer_end->pkt, pkt)){
2742
            while(!compare(s, &(*next_point)->pkt, pkt)){
2743
                next_point= &(*next_point)->next;
2744
            }
2745
            goto next_non_null;
2746
        }else{
2747
            next_point = &(s->packet_buffer_end->next);
2748
        }
2749
    }
2750
    assert(!*next_point);
2751

    
2752
    s->packet_buffer_end= this_pktl;
2753
next_non_null:
2754

    
2755
    this_pktl->next= *next_point;
2756

    
2757
    s->streams[pkt->stream_index]->last_in_packet_buffer=
2758
    *next_point= this_pktl;
2759
}
2760

    
2761
int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
2762
{
2763
    AVStream *st = s->streams[ pkt ->stream_index];
2764
    AVStream *st2= s->streams[ next->stream_index];
2765
    int64_t a= st2->time_base.num * (int64_t)st ->time_base.den;
2766
    int64_t b= st ->time_base.num * (int64_t)st2->time_base.den;
2767
    return av_rescale_rnd(pkt->dts, b, a, AV_ROUND_DOWN) < next->dts;
2768
}
2769

    
2770
int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2771
    AVPacketList *pktl;
2772
    int stream_count=0;
2773
    int i;
2774

    
2775
    if(pkt){
2776
        ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
2777
    }
2778

    
2779
    for(i=0; i < s->nb_streams; i++)
2780
        stream_count+= !!s->streams[i]->last_in_packet_buffer;
2781

    
2782
    if(stream_count && (s->nb_streams == stream_count || flush)){
2783
        pktl= s->packet_buffer;
2784
        *out= pktl->pkt;
2785

    
2786
        s->packet_buffer= pktl->next;
2787
        if(!s->packet_buffer)
2788
            s->packet_buffer_end= NULL;
2789

    
2790
        if(s->streams[out->stream_index]->last_in_packet_buffer == pktl)
2791
            s->streams[out->stream_index]->last_in_packet_buffer= NULL;
2792
        av_freep(&pktl);
2793
        return 1;
2794
    }else{
2795
        av_init_packet(out);
2796
        return 0;
2797
    }
2798
}
2799

    
2800
/**
2801
 * Interleaves an AVPacket correctly so it can be muxed.
2802
 * @param out the interleaved packet will be output here
2803
 * @param in the input packet
2804
 * @param flush 1 if no further packets are available as input and all
2805
 *              remaining packets should be output
2806
 * @return 1 if a packet was output, 0 if no packet could be output,
2807
 *         < 0 if an error occurred
2808
 */
2809
static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2810
    if(s->oformat->interleave_packet)
2811
        return s->oformat->interleave_packet(s, out, in, flush);
2812
    else
2813
        return av_interleave_packet_per_dts(s, out, in, flush);
2814
}
2815

    
2816
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2817
    AVStream *st= s->streams[ pkt->stream_index];
2818

    
2819
    //FIXME/XXX/HACK drop zero sized packets
2820
    if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
2821
        return 0;
2822

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

    
2827
    if(pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2828
        return -1;
2829

    
2830
    for(;;){
2831
        AVPacket opkt;
2832
        int ret= av_interleave_packet(s, &opkt, pkt, 0);
2833
        if(ret<=0) //FIXME cleanup needed for ret<0 ?
2834
            return ret;
2835

    
2836
        ret= s->oformat->write_packet(s, &opkt);
2837

    
2838
        av_free_packet(&opkt);
2839
        pkt= NULL;
2840

    
2841
        if(ret<0)
2842
            return ret;
2843
        if(url_ferror(s->pb))
2844
            return url_ferror(s->pb);
2845
    }
2846
}
2847

    
2848
int av_write_trailer(AVFormatContext *s)
2849
{
2850
    int ret, i;
2851

    
2852
    for(;;){
2853
        AVPacket pkt;
2854
        ret= av_interleave_packet(s, &pkt, NULL, 1);
2855
        if(ret<0) //FIXME cleanup needed for ret<0 ?
2856
            goto fail;
2857
        if(!ret)
2858
            break;
2859

    
2860
        ret= s->oformat->write_packet(s, &pkt);
2861

    
2862
        av_free_packet(&pkt);
2863

    
2864
        if(ret<0)
2865
            goto fail;
2866
        if(url_ferror(s->pb))
2867
            goto fail;
2868
    }
2869

    
2870
    if(s->oformat->write_trailer)
2871
        ret = s->oformat->write_trailer(s);
2872
fail:
2873
    if(ret == 0)
2874
       ret=url_ferror(s->pb);
2875
    for(i=0;i<s->nb_streams;i++) {
2876
        av_freep(&s->streams[i]->priv_data);
2877
        av_freep(&s->streams[i]->index_entries);
2878
    }
2879
    av_freep(&s->priv_data);
2880
    return ret;
2881
}
2882

    
2883
void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
2884
{
2885
    int i, j;
2886
    AVProgram *program=NULL;
2887
    void *tmp;
2888

    
2889
    if (idx >= ac->nb_streams) {
2890
        av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
2891
        return;
2892
    }
2893

    
2894
    for(i=0; i<ac->nb_programs; i++){
2895
        if(ac->programs[i]->id != progid)
2896
            continue;
2897
        program = ac->programs[i];
2898
        for(j=0; j<program->nb_stream_indexes; j++)
2899
            if(program->stream_index[j] == idx)
2900
                return;
2901

    
2902
        tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
2903
        if(!tmp)
2904
            return;
2905
        program->stream_index = tmp;
2906
        program->stream_index[program->nb_stream_indexes++] = idx;
2907
        return;
2908
    }
2909
}
2910

    
2911
static void print_fps(double d, const char *postfix){
2912
    uint64_t v= lrintf(d*100);
2913
    if     (v% 100      ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
2914
    else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
2915
    else                  av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
2916
}
2917

    
2918
static void dump_metadata(void *ctx, AVMetadata *m, const char *indent)
2919
{
2920
    if(m && !(m->count == 1 && av_metadata_get(m, "language", NULL, 0))){
2921
        AVMetadataTag *tag=NULL;
2922

    
2923
        av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
2924
        while((tag=av_metadata_get(m, "", tag, AV_METADATA_IGNORE_SUFFIX))) {
2925
            if(strcmp("language", tag->key))
2926
                av_log(ctx, AV_LOG_INFO, "%s  %-16s: %s\n", indent, tag->key, tag->value);
2927
        }
2928
    }
2929
}
2930

    
2931
/* "user interface" functions */
2932
static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
2933
{
2934
    char buf[256];
2935
    int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
2936
    AVStream *st = ic->streams[i];
2937
    int g = av_gcd(st->time_base.num, st->time_base.den);
2938
    AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL, 0);
2939
    avcodec_string(buf, sizeof(buf), st->codec, is_output);
2940
    av_log(NULL, AV_LOG_INFO, "    Stream #%d.%d", index, i);
2941
    /* the pid is an important information, so we display it */
2942
    /* XXX: add a generic system */
2943
    if (flags & AVFMT_SHOW_IDS)
2944
        av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2945
    if (lang)
2946
        av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
2947
    av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
2948
    av_log(NULL, AV_LOG_INFO, ": %s", buf);
2949
    if (st->sample_aspect_ratio.num && // default
2950
        av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
2951
        AVRational display_aspect_ratio;
2952
        av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2953
                  st->codec->width*st->sample_aspect_ratio.num,
2954
                  st->codec->height*st->sample_aspect_ratio.den,
2955
                  1024*1024);
2956
        av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
2957
                 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
2958
                 display_aspect_ratio.num, display_aspect_ratio.den);
2959
    }
2960
    if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2961
        if(st->avg_frame_rate.den && st->avg_frame_rate.num)
2962
            print_fps(av_q2d(st->avg_frame_rate), "fps");
2963
        if(st->r_frame_rate.den && st->r_frame_rate.num)
2964
            print_fps(av_q2d(st->r_frame_rate), "tbr");
2965
        if(st->time_base.den && st->time_base.num)
2966
            print_fps(1/av_q2d(st->time_base), "tbn");
2967
        if(st->codec->time_base.den && st->codec->time_base.num)
2968
            print_fps(1/av_q2d(st->codec->time_base), "tbc");
2969
    }
2970
    av_log(NULL, AV_LOG_INFO, "\n");
2971
    dump_metadata(NULL, st->metadata, "    ");
2972
}
2973

    
2974
void dump_format(AVFormatContext *ic,
2975
                 int index,
2976
                 const char *url,
2977
                 int is_output)
2978
{
2979
    int i;
2980
    uint8_t *printed = av_mallocz(ic->nb_streams);
2981
    if (ic->nb_streams && !printed)
2982
        return;
2983

    
2984
    av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2985
            is_output ? "Output" : "Input",
2986
            index,
2987
            is_output ? ic->oformat->name : ic->iformat->name,
2988
            is_output ? "to" : "from", url);
2989
    dump_metadata(NULL, ic->metadata, "  ");
2990
    if (!is_output) {
2991
        av_log(NULL, AV_LOG_INFO, "  Duration: ");
2992
        if (ic->duration != AV_NOPTS_VALUE) {
2993
            int hours, mins, secs, us;
2994
            secs = ic->duration / AV_TIME_BASE;
2995
            us = ic->duration % AV_TIME_BASE;
2996
            mins = secs / 60;
2997
            secs %= 60;
2998
            hours = mins / 60;
2999
            mins %= 60;
3000
            av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
3001
                   (100 * us) / AV_TIME_BASE);
3002
        } else {
3003
            av_log(NULL, AV_LOG_INFO, "N/A");
3004
        }
3005
        if (ic->start_time != AV_NOPTS_VALUE) {
3006
            int secs, us;
3007
            av_log(NULL, AV_LOG_INFO, ", start: ");
3008
            secs = ic->start_time / AV_TIME_BASE;
3009
            us = ic->start_time % AV_TIME_BASE;
3010
            av_log(NULL, AV_LOG_INFO, "%d.%06d",
3011
                   secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
3012
        }
3013
        av_log(NULL, AV_LOG_INFO, ", bitrate: ");
3014
        if (ic->bit_rate) {
3015
            av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
3016
        } else {
3017
            av_log(NULL, AV_LOG_INFO, "N/A");
3018
        }
3019
        av_log(NULL, AV_LOG_INFO, "\n");
3020
    }
3021
    for (i = 0; i < ic->nb_chapters; i++) {
3022
        AVChapter *ch = ic->chapters[i];
3023
        av_log(NULL, AV_LOG_INFO, "    Chapter #%d.%d: ", index, i);
3024
        av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
3025
        av_log(NULL, AV_LOG_INFO, "end %f\n",   ch->end   * av_q2d(ch->time_base));
3026

    
3027
        dump_metadata(NULL, ch->metadata, "    ");
3028
    }
3029
    if(ic->nb_programs) {
3030
        int j, k, total = 0;
3031
        for(j=0; j<ic->nb_programs; j++) {
3032
            AVMetadataTag *name = av_metadata_get(ic->programs[j]->metadata,
3033
                                                  "name", NULL, 0);
3034
            av_log(NULL, AV_LOG_INFO, "  Program %d %s\n", ic->programs[j]->id,
3035
                   name ? name->value : "");
3036
            dump_metadata(NULL, ic->programs[j]->metadata, "    ");
3037
            for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
3038
                dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
3039
                printed[ic->programs[j]->stream_index[k]] = 1;
3040
            }
3041
            total += ic->programs[j]->nb_stream_indexes;
3042
        }
3043
        if (total < ic->nb_streams)
3044
            av_log(NULL, AV_LOG_INFO, "  No Program\n");
3045
    }
3046
    for(i=0;i<ic->nb_streams;i++)
3047
        if (!printed[i])
3048
            dump_stream_format(ic, i, index, is_output);
3049

    
3050
    av_free(printed);
3051
}
3052

    
3053
#if LIBAVFORMAT_VERSION_MAJOR < 53
3054
int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
3055
{
3056
    return av_parse_video_frame_size(width_ptr, height_ptr, str);
3057
}
3058

    
3059
int parse_frame_rate(int *frame_rate_num, int *frame_rate_den, const char *arg)
3060
{
3061
    AVRational frame_rate;
3062
    int ret = av_parse_video_frame_rate(&frame_rate, arg);
3063
    *frame_rate_num= frame_rate.num;
3064
    *frame_rate_den= frame_rate.den;
3065
    return ret;
3066
}
3067
#endif
3068

    
3069
int64_t av_gettime(void)
3070
{
3071
    struct timeval tv;
3072
    gettimeofday(&tv,NULL);
3073
    return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
3074
}
3075

    
3076
int64_t parse_date(const char *datestr, int duration)
3077
{
3078
    const char *p;
3079
    int64_t t;
3080
    struct tm dt;
3081
    int i;
3082
    static const char * const date_fmt[] = {
3083
        "%Y-%m-%d",
3084
        "%Y%m%d",
3085
    };
3086
    static const char * const time_fmt[] = {
3087
        "%H:%M:%S",
3088
        "%H%M%S",
3089
    };
3090
    const char *q;
3091
    int is_utc, len;
3092
    char lastch;
3093
    int negative = 0;
3094

    
3095
#undef time
3096
    time_t now = time(0);
3097

    
3098
    len = strlen(datestr);
3099
    if (len > 0)
3100
        lastch = datestr[len - 1];
3101
    else
3102
        lastch = '\0';
3103
    is_utc = (lastch == 'z' || lastch == 'Z');
3104

    
3105
    memset(&dt, 0, sizeof(dt));
3106

    
3107
    p = datestr;
3108
    q = NULL;
3109
    if (!duration) {
3110
        if (!strncasecmp(datestr, "now", len))
3111
            return (int64_t) now * 1000000;
3112

    
3113
        /* parse the year-month-day part */
3114
        for (i = 0; i < FF_ARRAY_ELEMS(date_fmt); i++) {
3115
            q = small_strptime(p, date_fmt[i], &dt);
3116
            if (q) {
3117
                break;
3118
            }
3119
        }
3120

    
3121
        /* if the year-month-day part is missing, then take the
3122
         * current year-month-day time */
3123
        if (!q) {
3124
            if (is_utc) {
3125
                dt = *gmtime(&now);
3126
            } else {
3127
                dt = *localtime(&now);
3128
            }
3129
            dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
3130
        } else {
3131
            p = q;
3132
        }
3133

    
3134
        if (*p == 'T' || *p == 't' || *p == ' ')
3135
            p++;
3136

    
3137
        /* parse the hour-minute-second part */
3138
        for (i = 0; i < FF_ARRAY_ELEMS(time_fmt); i++) {
3139
            q = small_strptime(p, time_fmt[i], &dt);
3140
            if (q) {
3141
                break;
3142
            }
3143
        }
3144
    } else {
3145
        /* parse datestr as a duration */
3146
        if (p[0] == '-') {
3147
            negative = 1;
3148
            ++p;
3149
        }
3150
        /* parse datestr as HH:MM:SS */
3151
        q = small_strptime(p, time_fmt[0], &dt);
3152
        if (!q) {
3153
            /* parse datestr as S+ */
3154
            dt.tm_sec = strtol(p, (char **)&q, 10);
3155
            if (q == p)
3156
                /* the parsing didn't succeed */
3157
                return INT64_MIN;
3158
            dt.tm_min = 0;
3159
            dt.tm_hour = 0;
3160
        }
3161
    }
3162

    
3163
    /* Now we have all the fields that we can get */
3164
    if (!q) {
3165
        return INT64_MIN;
3166
    }
3167

    
3168
    if (duration) {
3169
        t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
3170
    } else {
3171
        dt.tm_isdst = -1;       /* unknown */
3172
        if (is_utc) {
3173
            t = mktimegm(&dt);
3174
        } else {
3175
            t = mktime(&dt);
3176
        }
3177
    }
3178

    
3179
    t *= 1000000;
3180

    
3181
    /* parse the .m... part */
3182
    if (*q == '.') {
3183
        int val, n;
3184
        q++;
3185
        for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
3186
            if (!isdigit(*q))
3187
                break;
3188
            val += n * (*q - '0');
3189
        }
3190
        t += val;
3191
    }
3192
    return negative ? -t : t;
3193
}
3194

    
3195
int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
3196
{
3197
    const char *p;
3198
    char tag[128], *q;
3199

    
3200
    p = info;
3201
    if (*p == '?')
3202
        p++;
3203
    for(;;) {
3204
        q = tag;
3205
        while (*p != '\0' && *p != '=' && *p != '&') {
3206
            if ((q - tag) < sizeof(tag) - 1)
3207
                *q++ = *p;
3208
            p++;
3209
        }
3210
        *q = '\0';
3211
        q = arg;
3212
        if (*p == '=') {
3213
            p++;
3214
            while (*p != '&' && *p != '\0') {
3215
                if ((q - arg) < arg_size - 1) {
3216
                    if (*p == '+')
3217
                        *q++ = ' ';
3218
                    else
3219
                        *q++ = *p;
3220
                }
3221
                p++;
3222
            }
3223
            *q = '\0';
3224
        }
3225
        if (!strcmp(tag, tag1))
3226
            return 1;
3227
        if (*p != '&')
3228
            break;
3229
        p++;
3230
    }
3231
    return 0;
3232
}
3233

    
3234
int av_get_frame_filename(char *buf, int buf_size,
3235
                          const char *path, int number)
3236
{
3237
    const char *p;
3238
    char *q, buf1[20], c;
3239
    int nd, len, percentd_found;
3240

    
3241
    q = buf;
3242
    p = path;
3243
    percentd_found = 0;
3244
    for(;;) {
3245
        c = *p++;
3246
        if (c == '\0')
3247
            break;
3248
        if (c == '%') {
3249
            do {
3250
                nd = 0;
3251
                while (isdigit(*p)) {
3252
                    nd = nd * 10 + *p++ - '0';
3253
                }
3254
                c = *p++;
3255
            } while (isdigit(c));
3256

    
3257
            switch(c) {
3258
            case '%':
3259
                goto addchar;
3260
            case 'd':
3261
                if (percentd_found)
3262
                    goto fail;
3263
                percentd_found = 1;
3264
                snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3265
                len = strlen(buf1);
3266
                if ((q - buf + len) > buf_size - 1)
3267
                    goto fail;
3268
                memcpy(q, buf1, len);
3269
                q += len;
3270
                break;
3271
            default:
3272
                goto fail;
3273
            }
3274
        } else {
3275
        addchar:
3276
            if ((q - buf) < buf_size - 1)
3277
                *q++ = c;
3278
        }
3279
    }
3280
    if (!percentd_found)
3281
        goto fail;
3282
    *q = '\0';
3283
    return 0;
3284
 fail:
3285
    *q = '\0';
3286
    return -1;
3287
}
3288

    
3289
static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
3290
{
3291
    int len, i, j, c;
3292
#undef fprintf
3293
#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3294

    
3295
    for(i=0;i<size;i+=16) {
3296
        len = size - i;
3297
        if (len > 16)
3298
            len = 16;
3299
        PRINT("%08x ", i);
3300
        for(j=0;j<16;j++) {
3301
            if (j < len)
3302
                PRINT(" %02x", buf[i+j]);
3303
            else
3304
                PRINT("   ");
3305
        }
3306
        PRINT(" ");
3307
        for(j=0;j<len;j++) {
3308
            c = buf[i+j];
3309
            if (c < ' ' || c > '~')
3310
                c = '.';
3311
            PRINT("%c", c);
3312
        }
3313
        PRINT("\n");
3314
    }
3315
#undef PRINT
3316
}
3317

    
3318
void av_hex_dump(FILE *f, uint8_t *buf, int size)
3319
{
3320
    hex_dump_internal(NULL, f, 0, buf, size);
3321
}
3322

    
3323
void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
3324
{
3325
    hex_dump_internal(avcl, NULL, level, buf, size);
3326
}
3327

    
3328
 //FIXME needs to know the time_base
3329
static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload)
3330
{
3331
#undef fprintf
3332
#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3333
    PRINT("stream #%d:\n", pkt->stream_index);
3334
    PRINT("  keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
3335
    PRINT("  duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
3336
    /* DTS is _always_ valid after av_read_frame() */
3337
    PRINT("  dts=");
3338
    if (pkt->dts == AV_NOPTS_VALUE)
3339
        PRINT("N/A");
3340
    else
3341
        PRINT("%0.3f", (double)pkt->dts / AV_TIME_BASE);
3342
    /* PTS may not be known if B-frames are present. */
3343
    PRINT("  pts=");
3344
    if (pkt->pts == AV_NOPTS_VALUE)
3345
        PRINT("N/A");
3346
    else
3347
        PRINT("%0.3f", (double)pkt->pts / AV_TIME_BASE);
3348
    PRINT("\n");
3349
    PRINT("  size=%d\n", pkt->size);
3350
#undef PRINT
3351
    if (dump_payload)
3352
        av_hex_dump(f, pkt->data, pkt->size);
3353
}
3354

    
3355
void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3356
{
3357
    pkt_dump_internal(NULL, f, 0, pkt, dump_payload);
3358
}
3359

    
3360
void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
3361
{
3362
    pkt_dump_internal(avcl, NULL, level, pkt, dump_payload);
3363
}
3364

    
3365
void ff_url_split(char *proto, int proto_size,
3366
                  char *authorization, int authorization_size,
3367
                  char *hostname, int hostname_size,
3368
                  int *port_ptr,
3369
                  char *path, int path_size,
3370
                  const char *url)
3371
{
3372
    const char *p, *ls, *at, *col, *brk;
3373

    
3374
    if (port_ptr)               *port_ptr = -1;
3375
    if (proto_size > 0)         proto[0] = 0;
3376
    if (authorization_size > 0) authorization[0] = 0;
3377
    if (hostname_size > 0)      hostname[0] = 0;
3378
    if (path_size > 0)          path[0] = 0;
3379

    
3380
    /* parse protocol */
3381
    if ((p = strchr(url, ':'))) {
3382
        av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3383
        p++; /* skip ':' */
3384
        if (*p == '/') p++;
3385
        if (*p == '/') p++;
3386
    } else {
3387
        /* no protocol means plain filename */
3388
        av_strlcpy(path, url, path_size);
3389
        return;
3390
    }
3391

    
3392
    /* separate path from hostname */
3393
    ls = strchr(p, '/');
3394
    if(!ls)
3395
        ls = strchr(p, '?');
3396
    if(ls)
3397
        av_strlcpy(path, ls, path_size);
3398
    else
3399
        ls = &p[strlen(p)]; // XXX
3400

    
3401
    /* the rest is hostname, use that to parse auth/port */
3402
    if (ls != p) {
3403
        /* authorization (user[:pass]@hostname) */
3404
        if ((at = strchr(p, '@')) && at < ls) {
3405
            av_strlcpy(authorization, p,
3406
                       FFMIN(authorization_size, at + 1 - p));
3407
            p = at + 1; /* skip '@' */
3408
        }
3409

    
3410
        if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3411
            /* [host]:port */
3412
            av_strlcpy(hostname, p + 1,
3413
                       FFMIN(hostname_size, brk - p));
3414
            if (brk[1] == ':' && port_ptr)
3415
                *port_ptr = atoi(brk + 2);
3416
        } else if ((col = strchr(p, ':')) && col < ls) {
3417
            av_strlcpy(hostname, p,
3418
                       FFMIN(col + 1 - p, hostname_size));
3419
            if (port_ptr) *port_ptr = atoi(col + 1);
3420
        } else
3421
            av_strlcpy(hostname, p,
3422
                       FFMIN(ls + 1 - p, hostname_size));
3423
    }
3424
}
3425

    
3426
char *ff_data_to_hex(char *buff, const uint8_t *src, int s)
3427
{
3428
    int i;
3429
    static const char hex_table[16] = { '0', '1', '2', '3',
3430
                                        '4', '5', '6', '7',
3431
                                        '8', '9', 'A', 'B',
3432
                                        'C', 'D', 'E', 'F' };
3433

    
3434
    for(i = 0; i < s; i++) {
3435
        buff[i * 2]     = hex_table[src[i] >> 4];
3436
        buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3437
    }
3438

    
3439
    return buff;
3440
}
3441

    
3442
void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3443
                     unsigned int pts_num, unsigned int pts_den)
3444
{
3445
    s->pts_wrap_bits = pts_wrap_bits;
3446

    
3447
    if(av_reduce(&s->time_base.num, &s->time_base.den, pts_num, pts_den, INT_MAX)){
3448
        if(s->time_base.num != pts_num)
3449
            av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/s->time_base.num);
3450
    }else
3451
        av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3452

    
3453
    if(!s->time_base.num || !s->time_base.den)
3454
        s->time_base.num= s->time_base.den= 0;
3455
}
3456

    
3457
int ff_url_join(char *str, int size, const char *proto,
3458
                const char *authorization, const char *hostname,
3459
                int port, const char *fmt, ...)
3460
{
3461
#if CONFIG_NETWORK
3462
    struct addrinfo hints, *ai;
3463
#endif
3464

    
3465
    str[0] = '\0';
3466
    if (proto)
3467
        av_strlcatf(str, size, "%s://", proto);
3468
    if (authorization)
3469
        av_strlcatf(str, size, "%s@", authorization);
3470
#if CONFIG_NETWORK && defined(AF_INET6)
3471
    /* Determine if hostname is a numerical IPv6 address,
3472
     * properly escape it within [] in that case. */
3473
    memset(&hints, 0, sizeof(hints));
3474
    hints.ai_flags = AI_NUMERICHOST;
3475
    if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
3476
        if (ai->ai_family == AF_INET6) {
3477
            av_strlcat(str, "[", size);
3478
            av_strlcat(str, hostname, size);
3479
            av_strlcat(str, "]", size);
3480
        } else {
3481
            av_strlcat(str, hostname, size);
3482
        }
3483
        freeaddrinfo(ai);
3484
    } else
3485
#endif
3486
        /* Not an IPv6 address, just output the plain string. */
3487
        av_strlcat(str, hostname, size);
3488

    
3489
    if (port >= 0)
3490
        av_strlcatf(str, size, ":%d", port);
3491
    if (fmt) {
3492
        va_list vl;
3493
        int len = strlen(str);
3494

    
3495
        va_start(vl, fmt);
3496
        vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
3497
        va_end(vl);
3498
    }
3499
    return strlen(str);
3500
}