Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ 0b9dffc6

History | View | Annotate | Download (125 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

    
22
/* #define DEBUG */
23

    
24
#include "avformat.h"
25
#include "avio_internal.h"
26
#include "internal.h"
27
#include "libavcodec/internal.h"
28
#include "libavcodec/raw.h"
29
#include "libavutil/opt.h"
30
#include "metadata.h"
31
#include "id3v2.h"
32
#include "libavutil/avstring.h"
33
#include "riff.h"
34
#include "audiointerleave.h"
35
#include <sys/time.h>
36
#include <time.h>
37
#include <strings.h>
38
#include <stdarg.h>
39
#if CONFIG_NETWORK
40
#include "network.h"
41
#endif
42

    
43
#undef NDEBUG
44
#include <assert.h>
45

    
46
/**
47
 * @file
48
 * various utility functions for use within FFmpeg
49
 */
50

    
51
unsigned avformat_version(void)
52
{
53
    return LIBAVFORMAT_VERSION_INT;
54
}
55

    
56
const char *avformat_configuration(void)
57
{
58
    return FFMPEG_CONFIGURATION;
59
}
60

    
61
const char *avformat_license(void)
62
{
63
#define LICENSE_PREFIX "libavformat license: "
64
    return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
65
}
66

    
67
/* fraction handling */
68

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

    
91
/**
92
 * Fractional addition to f: f = f + (incr / f->den).
93
 *
94
 * @param f fractional number
95
 * @param incr increment, can be positive or negative
96
 */
97
static void av_frac_add(AVFrac *f, int64_t incr)
98
{
99
    int64_t num, den;
100

    
101
    num = f->num + incr;
102
    den = f->den;
103
    if (num < 0) {
104
        f->val += num / den;
105
        num = num % den;
106
        if (num < 0) {
107
            num += den;
108
            f->val--;
109
        }
110
    } else if (num >= den) {
111
        f->val += num / den;
112
        num = num % den;
113
    }
114
    f->num = num;
115
}
116

    
117
/** head of registered input format linked list */
118
#if !FF_API_FIRST_FORMAT
119
static
120
#endif
121
AVInputFormat *first_iformat = NULL;
122
/** head of registered output format linked list */
123
#if !FF_API_FIRST_FORMAT
124
static
125
#endif
126
AVOutputFormat *first_oformat = NULL;
127

    
128
AVInputFormat  *av_iformat_next(AVInputFormat  *f)
129
{
130
    if(f) return f->next;
131
    else  return first_iformat;
132
}
133

    
134
AVOutputFormat *av_oformat_next(AVOutputFormat *f)
135
{
136
    if(f) return f->next;
137
    else  return first_oformat;
138
}
139

    
140
void av_register_input_format(AVInputFormat *format)
141
{
142
    AVInputFormat **p;
143
    p = &first_iformat;
144
    while (*p != NULL) p = &(*p)->next;
145
    *p = format;
146
    format->next = NULL;
147
}
148

    
149
void av_register_output_format(AVOutputFormat *format)
150
{
151
    AVOutputFormat **p;
152
    p = &first_oformat;
153
    while (*p != NULL) p = &(*p)->next;
154
    *p = format;
155
    format->next = NULL;
156
}
157

    
158
int av_match_ext(const char *filename, const char *extensions)
159
{
160
    const char *ext, *p;
161
    char ext1[32], *q;
162

    
163
    if(!filename)
164
        return 0;
165

    
166
    ext = strrchr(filename, '.');
167
    if (ext) {
168
        ext++;
169
        p = extensions;
170
        for(;;) {
171
            q = ext1;
172
            while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
173
                *q++ = *p++;
174
            *q = '\0';
175
            if (!strcasecmp(ext1, ext))
176
                return 1;
177
            if (*p == '\0')
178
                break;
179
            p++;
180
        }
181
    }
182
    return 0;
183
}
184

    
185
static int match_format(const char *name, const char *names)
186
{
187
    const char *p;
188
    int len, namelen;
189

    
190
    if (!name || !names)
191
        return 0;
192

    
193
    namelen = strlen(name);
194
    while ((p = strchr(names, ','))) {
195
        len = FFMAX(p - names, namelen);
196
        if (!strncasecmp(name, names, len))
197
            return 1;
198
        names = p+1;
199
    }
200
    return !strcasecmp(name, names);
201
}
202

    
203
#if FF_API_GUESS_FORMAT
204
AVOutputFormat *guess_format(const char *short_name, const char *filename,
205
                             const char *mime_type)
206
{
207
    return av_guess_format(short_name, filename, mime_type);
208
}
209
#endif
210

    
211
AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
212
                                const char *mime_type)
213
{
214
    AVOutputFormat *fmt = NULL, *fmt_found;
215
    int score_max, score;
216

    
217
    /* specific test for image sequences */
218
#if CONFIG_IMAGE2_MUXER
219
    if (!short_name && filename &&
220
        av_filename_number_test(filename) &&
221
        av_guess_image2_codec(filename) != CODEC_ID_NONE) {
222
        return av_guess_format("image2", NULL, NULL);
223
    }
224
#endif
225
    /* Find the proper file type. */
226
    fmt_found = NULL;
227
    score_max = 0;
228
    while ((fmt = av_oformat_next(fmt))) {
229
        score = 0;
230
        if (fmt->name && short_name && !strcmp(fmt->name, short_name))
231
            score += 100;
232
        if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
233
            score += 10;
234
        if (filename && fmt->extensions &&
235
            av_match_ext(filename, fmt->extensions)) {
236
            score += 5;
237
        }
238
        if (score > score_max) {
239
            score_max = score;
240
            fmt_found = fmt;
241
        }
242
    }
243
    return fmt_found;
244
}
245

    
246
#if FF_API_GUESS_FORMAT
247
AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
248
                             const char *mime_type)
249
{
250
    AVOutputFormat *fmt = av_guess_format(short_name, filename, mime_type);
251

    
252
    if (fmt) {
253
        AVOutputFormat *stream_fmt;
254
        char stream_format_name[64];
255

    
256
        snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
257
        stream_fmt = av_guess_format(stream_format_name, NULL, NULL);
258

    
259
        if (stream_fmt)
260
            fmt = stream_fmt;
261
    }
262

    
263
    return fmt;
264
}
265
#endif
266

    
267
enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
268
                            const char *filename, const char *mime_type, enum AVMediaType type){
269
    if(type == AVMEDIA_TYPE_VIDEO){
270
        enum CodecID codec_id= CODEC_ID_NONE;
271

    
272
#if CONFIG_IMAGE2_MUXER
273
        if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
274
            codec_id= av_guess_image2_codec(filename);
275
        }
276
#endif
277
        if(codec_id == CODEC_ID_NONE)
278
            codec_id= fmt->video_codec;
279
        return codec_id;
280
    }else if(type == AVMEDIA_TYPE_AUDIO)
281
        return fmt->audio_codec;
282
    else if (type == AVMEDIA_TYPE_SUBTITLE)
283
        return fmt->subtitle_codec;
284
    else
285
        return CODEC_ID_NONE;
286
}
287

    
288
AVInputFormat *av_find_input_format(const char *short_name)
289
{
290
    AVInputFormat *fmt = NULL;
291
    while ((fmt = av_iformat_next(fmt))) {
292
        if (match_format(short_name, fmt->name))
293
            return fmt;
294
    }
295
    return NULL;
296
}
297

    
298
#if FF_API_SYMVER && CONFIG_SHARED && HAVE_SYMVER
299
FF_SYMVER(void, av_destruct_packet_nofree, (AVPacket *pkt), "LIBAVFORMAT_52")
300
{
301
    av_destruct_packet_nofree(pkt);
302
}
303

    
304
FF_SYMVER(void, av_destruct_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
305
{
306
    av_destruct_packet(pkt);
307
}
308

    
309
FF_SYMVER(int, av_new_packet, (AVPacket *pkt, int size), "LIBAVFORMAT_52")
310
{
311
    return av_new_packet(pkt, size);
312
}
313

    
314
FF_SYMVER(int, av_dup_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
315
{
316
    return av_dup_packet(pkt);
317
}
318

    
319
FF_SYMVER(void, av_free_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
320
{
321
    av_free_packet(pkt);
322
}
323

    
324
FF_SYMVER(void, av_init_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
325
{
326
    av_log(NULL, AV_LOG_WARNING, "Diverting av_*_packet function calls to libavcodec. Recompile to improve performance\n");
327
    av_init_packet(pkt);
328
}
329
#endif
330

    
331
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
332
{
333
    int ret= av_new_packet(pkt, size);
334

    
335
    if(ret<0)
336
        return ret;
337

    
338
    pkt->pos= avio_tell(s);
339

    
340
    ret= avio_read(s, pkt->data, size);
341
    if(ret<=0)
342
        av_free_packet(pkt);
343
    else
344
        av_shrink_packet(pkt, ret);
345

    
346
    return ret;
347
}
348

    
349
int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
350
{
351
    int ret;
352
    int old_size;
353
    if (!pkt->size)
354
        return av_get_packet(s, pkt, size);
355
    old_size = pkt->size;
356
    ret = av_grow_packet(pkt, size);
357
    if (ret < 0)
358
        return ret;
359
    ret = avio_read(s, pkt->data + old_size, size);
360
    av_shrink_packet(pkt, old_size + FFMAX(ret, 0));
361
    return ret;
362
}
363

    
364

    
365
int av_filename_number_test(const char *filename)
366
{
367
    char buf[1024];
368
    return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
369
}
370

    
371
AVInputFormat *av_probe_input_format3(AVProbeData *pd, int is_opened, int *score_ret)
372
{
373
    AVProbeData lpd = *pd;
374
    AVInputFormat *fmt1 = NULL, *fmt;
375
    int score, score_max=0;
376

    
377
    if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
378
        int id3len = ff_id3v2_tag_len(lpd.buf);
379
        if (lpd.buf_size > id3len + 16) {
380
            lpd.buf += id3len;
381
            lpd.buf_size -= id3len;
382
        }
383
    }
384

    
385
    fmt = NULL;
386
    while ((fmt1 = av_iformat_next(fmt1))) {
387
        if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
388
            continue;
389
        score = 0;
390
        if (fmt1->read_probe) {
391
            score = fmt1->read_probe(&lpd);
392
        } else if (fmt1->extensions) {
393
            if (av_match_ext(lpd.filename, fmt1->extensions)) {
394
                score = 50;
395
            }
396
        }
397
        if (score > score_max) {
398
            score_max = score;
399
            fmt = fmt1;
400
        }else if (score == score_max)
401
            fmt = NULL;
402
    }
403
    *score_ret= score_max;
404
    return fmt;
405
}
406

    
407
AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
408
{
409
    int score_ret;
410
    AVInputFormat *fmt= av_probe_input_format3(pd, is_opened, &score_ret);
411
    if(score_ret > *score_max){
412
        *score_max= score_ret;
413
        return fmt;
414
    }else
415
        return NULL;
416
}
417

    
418
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
419
    int score=0;
420
    return av_probe_input_format2(pd, is_opened, &score);
421
}
422

    
423
static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd)
424
{
425
    static const struct {
426
        const char *name; enum CodecID id; enum AVMediaType type;
427
    } fmt_id_type[] = {
428
        { "aac"      , CODEC_ID_AAC       , AVMEDIA_TYPE_AUDIO },
429
        { "ac3"      , CODEC_ID_AC3       , AVMEDIA_TYPE_AUDIO },
430
        { "dts"      , CODEC_ID_DTS       , AVMEDIA_TYPE_AUDIO },
431
        { "eac3"     , CODEC_ID_EAC3      , AVMEDIA_TYPE_AUDIO },
432
        { "h264"     , CODEC_ID_H264      , AVMEDIA_TYPE_VIDEO },
433
        { "m4v"      , CODEC_ID_MPEG4     , AVMEDIA_TYPE_VIDEO },
434
        { "mp3"      , CODEC_ID_MP3       , AVMEDIA_TYPE_AUDIO },
435
        { "mpegvideo", CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
436
        { 0 }
437
    };
438
    int score;
439
    AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
440

    
441
    if (fmt) {
442
        int i;
443
        av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
444
               pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
445
        for (i = 0; fmt_id_type[i].name; i++) {
446
            if (!strcmp(fmt->name, fmt_id_type[i].name)) {
447
                st->codec->codec_id   = fmt_id_type[i].id;
448
                st->codec->codec_type = fmt_id_type[i].type;
449
                break;
450
            }
451
        }
452
    }
453
    return score;
454
}
455

    
456
/************************************************************/
457
/* input media file */
458

    
459
/**
460
 * Open a media file from an IO stream. 'fmt' must be specified.
461
 */
462
int av_open_input_stream(AVFormatContext **ic_ptr,
463
                         AVIOContext *pb, const char *filename,
464
                         AVInputFormat *fmt, AVFormatParameters *ap)
465
{
466
    int err;
467
    AVFormatContext *ic;
468
    AVFormatParameters default_ap;
469

    
470
    if(!ap){
471
        ap=&default_ap;
472
        memset(ap, 0, sizeof(default_ap));
473
    }
474

    
475
    if(!ap->prealloced_context)
476
        ic = avformat_alloc_context();
477
    else
478
        ic = *ic_ptr;
479
    if (!ic) {
480
        err = AVERROR(ENOMEM);
481
        goto fail;
482
    }
483
    ic->iformat = fmt;
484
    ic->pb = pb;
485
    ic->duration = AV_NOPTS_VALUE;
486
    ic->start_time = AV_NOPTS_VALUE;
487
    av_strlcpy(ic->filename, filename, sizeof(ic->filename));
488

    
489
    /* allocate private data */
490
    if (fmt->priv_data_size > 0) {
491
        ic->priv_data = av_mallocz(fmt->priv_data_size);
492
        if (!ic->priv_data) {
493
            err = AVERROR(ENOMEM);
494
            goto fail;
495
        }
496
    } else {
497
        ic->priv_data = NULL;
498
    }
499

    
500
    // e.g. AVFMT_NOFILE formats will not have a AVIOContext
501
    if (ic->pb)
502
        ff_id3v2_read(ic, ID3v2_DEFAULT_MAGIC);
503

    
504
    if (ic->iformat->read_header) {
505
        err = ic->iformat->read_header(ic, ap);
506
        if (err < 0)
507
            goto fail;
508
    }
509

    
510
    if (pb && !ic->data_offset)
511
        ic->data_offset = avio_tell(ic->pb);
512

    
513
#if FF_API_OLD_METADATA
514
    ff_metadata_demux_compat(ic);
515
#endif
516

    
517
    ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
518

    
519
    *ic_ptr = ic;
520
    return 0;
521
 fail:
522
    if (ic) {
523
        int i;
524
        av_freep(&ic->priv_data);
525
        for(i=0;i<ic->nb_streams;i++) {
526
            AVStream *st = ic->streams[i];
527
            if (st) {
528
                av_free(st->priv_data);
529
                av_free(st->codec->extradata);
530
                av_free(st->codec);
531
                av_free(st->info);
532
            }
533
            av_free(st);
534
        }
535
    }
536
    av_free(ic);
537
    *ic_ptr = NULL;
538
    return err;
539
}
540

    
541
/** size of probe buffer, for guessing file type from file contents */
542
#define PROBE_BUF_MIN 2048
543
#define PROBE_BUF_MAX (1<<20)
544

    
545
int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
546
                          const char *filename, void *logctx,
547
                          unsigned int offset, unsigned int max_probe_size)
548
{
549
    AVProbeData pd = { filename ? filename : "", NULL, -offset };
550
    unsigned char *buf = NULL;
551
    int ret = 0, probe_size;
552

    
553
    if (!max_probe_size) {
554
        max_probe_size = PROBE_BUF_MAX;
555
    } else if (max_probe_size > PROBE_BUF_MAX) {
556
        max_probe_size = PROBE_BUF_MAX;
557
    } else if (max_probe_size < PROBE_BUF_MIN) {
558
        return AVERROR(EINVAL);
559
    }
560

    
561
    if (offset >= max_probe_size) {
562
        return AVERROR(EINVAL);
563
    }
564

    
565
    for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt && ret >= 0;
566
        probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
567
        int ret, score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
568
        int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;
569

    
570
        if (probe_size < offset) {
571
            continue;
572
        }
573

    
574
        /* read probe data */
575
        buf = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
576
        if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
577
            /* fail if error was not end of file, otherwise, lower score */
578
            if (ret != AVERROR_EOF) {
579
                av_free(buf);
580
                return ret;
581
            }
582
            score = 0;
583
            ret = 0;            /* error was end of file, nothing read */
584
        }
585
        pd.buf_size += ret;
586
        pd.buf = &buf[offset];
587

    
588
        memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
589

    
590
        /* guess file format */
591
        *fmt = av_probe_input_format2(&pd, 1, &score);
592
        if(*fmt){
593
            if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
594
                av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);
595
            }else
596
                av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);
597
        }
598
    }
599

    
600
    if (!*fmt) {
601
        av_free(buf);
602
        return AVERROR_INVALIDDATA;
603
    }
604

    
605
    /* rewind. reuse probe buffer to avoid seeking */
606
    if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
607
        av_free(buf);
608

    
609
    return ret;
610
}
611

    
612
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
613
                       AVInputFormat *fmt,
614
                       int buf_size,
615
                       AVFormatParameters *ap)
616
{
617
    int err;
618
    AVProbeData probe_data, *pd = &probe_data;
619
    AVIOContext *pb = NULL;
620
    void *logctx= ap && ap->prealloced_context ? *ic_ptr : NULL;
621

    
622
    pd->filename = "";
623
    if (filename)
624
        pd->filename = filename;
625
    pd->buf = NULL;
626
    pd->buf_size = 0;
627

    
628
    if (!fmt) {
629
        /* guess format if no file can be opened */
630
        fmt = av_probe_input_format(pd, 0);
631
    }
632

    
633
    /* Do not open file if the format does not need it. XXX: specific
634
       hack needed to handle RTSP/TCP */
635
    if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
636
        /* if no file needed do not try to open one */
637
        if ((err=avio_open(&pb, filename, URL_RDONLY)) < 0) {
638
            goto fail;
639
        }
640
        if (buf_size > 0) {
641
            ffio_set_buf_size(pb, buf_size);
642
        }
643
        if (!fmt && (err = av_probe_input_buffer(pb, &fmt, filename, logctx, 0, logctx ? (*ic_ptr)->probesize : 0)) < 0) {
644
            goto fail;
645
        }
646
    }
647

    
648
    /* if still no format found, error */
649
    if (!fmt) {
650
        err = AVERROR_INVALIDDATA;
651
        goto fail;
652
    }
653

    
654
    /* check filename in case an image number is expected */
655
    if (fmt->flags & AVFMT_NEEDNUMBER) {
656
        if (!av_filename_number_test(filename)) {
657
            err = AVERROR_NUMEXPECTED;
658
            goto fail;
659
        }
660
    }
661
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
662
    if (err)
663
        goto fail;
664
    return 0;
665
 fail:
666
    av_freep(&pd->buf);
667
    if (pb)
668
        avio_close(pb);
669
    if (ap && ap->prealloced_context)
670
        av_free(*ic_ptr);
671
    *ic_ptr = NULL;
672
    return err;
673

    
674
}
675

    
676
/*******************************************************/
677

    
678
static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
679
                               AVPacketList **plast_pktl){
680
    AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
681
    if (!pktl)
682
        return NULL;
683

    
684
    if (*packet_buffer)
685
        (*plast_pktl)->next = pktl;
686
    else
687
        *packet_buffer = pktl;
688

    
689
    /* add the packet in the buffered packet list */
690
    *plast_pktl = pktl;
691
    pktl->pkt= *pkt;
692
    return &pktl->pkt;
693
}
694

    
695
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
696
{
697
    int ret, i;
698
    AVStream *st;
699

    
700
    for(;;){
701
        AVPacketList *pktl = s->raw_packet_buffer;
702

    
703
        if (pktl) {
704
            *pkt = pktl->pkt;
705
            if(s->streams[pkt->stream_index]->request_probe <= 0){
706
                s->raw_packet_buffer = pktl->next;
707
                s->raw_packet_buffer_remaining_size += pkt->size;
708
                av_free(pktl);
709
                return 0;
710
            }
711
        }
712

    
713
        av_init_packet(pkt);
714
        ret= s->iformat->read_packet(s, pkt);
715
        if (ret < 0) {
716
            if (!pktl || ret == AVERROR(EAGAIN))
717
                return ret;
718
            for (i = 0; i < s->nb_streams; i++)
719
                if(s->streams[i]->request_probe > 0)
720
                    s->streams[i]->request_probe = -1;
721
            continue;
722
        }
723
        st= s->streams[pkt->stream_index];
724

    
725
        switch(st->codec->codec_type){
726
        case AVMEDIA_TYPE_VIDEO:
727
            if(s->video_codec_id)   st->codec->codec_id= s->video_codec_id;
728
            break;
729
        case AVMEDIA_TYPE_AUDIO:
730
            if(s->audio_codec_id)   st->codec->codec_id= s->audio_codec_id;
731
            break;
732
        case AVMEDIA_TYPE_SUBTITLE:
733
            if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
734
            break;
735
        }
736

    
737
        if(!pktl && st->request_probe <= 0)
738
            return ret;
739

    
740
        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
741
        s->raw_packet_buffer_remaining_size -= pkt->size;
742

    
743
        if(st->request_probe>0){
744
            AVProbeData *pd = &st->probe_data;
745
            int end;
746
            av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->probe_packets);
747
            --st->probe_packets;
748

    
749
            pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
750
            memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
751
            pd->buf_size += pkt->size;
752
            memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
753

    
754
            end=    s->raw_packet_buffer_remaining_size <= 0
755
                 || st->probe_packets<=0;
756

    
757
            if(end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
758
                int score= set_codec_from_probe_data(s, st, pd);
759
                if(    (st->codec->codec_id != CODEC_ID_NONE && score > AVPROBE_SCORE_MAX/4)
760
                    || end){
761
                    pd->buf_size=0;
762
                    av_freep(&pd->buf);
763
                    st->request_probe= -1;
764
                    if(st->codec->codec_id != CODEC_ID_NONE){
765
                    av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
766
                    }else
767
                        av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
768
                }
769
            }
770
        }
771
    }
772
}
773

    
774
/**********************************************************/
775

    
776
/**
777
 * Get the number of samples of an audio frame. Return -1 on error.
778
 */
779
static int get_audio_frame_size(AVCodecContext *enc, int size)
780
{
781
    int frame_size;
782

    
783
    if(enc->codec_id == CODEC_ID_VORBIS)
784
        return -1;
785

    
786
    if (enc->frame_size <= 1) {
787
        int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
788

    
789
        if (bits_per_sample) {
790
            if (enc->channels == 0)
791
                return -1;
792
            frame_size = (size << 3) / (bits_per_sample * enc->channels);
793
        } else {
794
            /* used for example by ADPCM codecs */
795
            if (enc->bit_rate == 0)
796
                return -1;
797
            frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
798
        }
799
    } else {
800
        frame_size = enc->frame_size;
801
    }
802
    return frame_size;
803
}
804

    
805

    
806
/**
807
 * Return the frame duration in seconds. Return 0 if not available.
808
 */
809
static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
810
                                   AVCodecParserContext *pc, AVPacket *pkt)
811
{
812
    int frame_size;
813

    
814
    *pnum = 0;
815
    *pden = 0;
816
    switch(st->codec->codec_type) {
817
    case AVMEDIA_TYPE_VIDEO:
818
        if(st->time_base.num*1000LL > st->time_base.den){
819
            *pnum = st->time_base.num;
820
            *pden = st->time_base.den;
821
        }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
822
            *pnum = st->codec->time_base.num;
823
            *pden = st->codec->time_base.den;
824
            if (pc && pc->repeat_pict) {
825
                *pnum = (*pnum) * (1 + pc->repeat_pict);
826
            }
827
            //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
828
            //Thus if we have no parser in such case leave duration undefined.
829
            if(st->codec->ticks_per_frame>1 && !pc){
830
                *pnum = *pden = 0;
831
            }
832
        }
833
        break;
834
    case AVMEDIA_TYPE_AUDIO:
835
        frame_size = get_audio_frame_size(st->codec, pkt->size);
836
        if (frame_size <= 0 || st->codec->sample_rate <= 0)
837
            break;
838
        *pnum = frame_size;
839
        *pden = st->codec->sample_rate;
840
        break;
841
    default:
842
        break;
843
    }
844
}
845

    
846
static int is_intra_only(AVCodecContext *enc){
847
    if(enc->codec_type == AVMEDIA_TYPE_AUDIO){
848
        return 1;
849
    }else if(enc->codec_type == AVMEDIA_TYPE_VIDEO){
850
        switch(enc->codec_id){
851
        case CODEC_ID_MJPEG:
852
        case CODEC_ID_MJPEGB:
853
        case CODEC_ID_LJPEG:
854
        case CODEC_ID_RAWVIDEO:
855
        case CODEC_ID_DVVIDEO:
856
        case CODEC_ID_HUFFYUV:
857
        case CODEC_ID_FFVHUFF:
858
        case CODEC_ID_ASV1:
859
        case CODEC_ID_ASV2:
860
        case CODEC_ID_VCR1:
861
        case CODEC_ID_DNXHD:
862
        case CODEC_ID_JPEG2000:
863
            return 1;
864
        default: break;
865
        }
866
    }
867
    return 0;
868
}
869

    
870
static void update_initial_timestamps(AVFormatContext *s, int stream_index,
871
                                      int64_t dts, int64_t pts)
872
{
873
    AVStream *st= s->streams[stream_index];
874
    AVPacketList *pktl= s->packet_buffer;
875

    
876
    if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
877
        return;
878

    
879
    st->first_dts= dts - st->cur_dts;
880
    st->cur_dts= dts;
881

    
882
    for(; pktl; pktl= pktl->next){
883
        if(pktl->pkt.stream_index != stream_index)
884
            continue;
885
        //FIXME think more about this check
886
        if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
887
            pktl->pkt.pts += st->first_dts;
888

    
889
        if(pktl->pkt.dts != AV_NOPTS_VALUE)
890
            pktl->pkt.dts += st->first_dts;
891

    
892
        if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
893
            st->start_time= pktl->pkt.pts;
894
    }
895
    if (st->start_time == AV_NOPTS_VALUE)
896
        st->start_time = pts;
897
}
898

    
899
static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
900
{
901
    AVPacketList *pktl= s->packet_buffer;
902
    int64_t cur_dts= 0;
903

    
904
    if(st->first_dts != AV_NOPTS_VALUE){
905
        cur_dts= st->first_dts;
906
        for(; pktl; pktl= pktl->next){
907
            if(pktl->pkt.stream_index == pkt->stream_index){
908
                if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
909
                    break;
910
                cur_dts -= pkt->duration;
911
            }
912
        }
913
        pktl= s->packet_buffer;
914
        st->first_dts = cur_dts;
915
    }else if(st->cur_dts)
916
        return;
917

    
918
    for(; pktl; pktl= pktl->next){
919
        if(pktl->pkt.stream_index != pkt->stream_index)
920
            continue;
921
        if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
922
           && !pktl->pkt.duration){
923
            pktl->pkt.dts= cur_dts;
924
            if(!st->codec->has_b_frames)
925
                pktl->pkt.pts= cur_dts;
926
            cur_dts += pkt->duration;
927
            pktl->pkt.duration= pkt->duration;
928
        }else
929
            break;
930
    }
931
    if(st->first_dts == AV_NOPTS_VALUE)
932
        st->cur_dts= cur_dts;
933
}
934

    
935
static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
936
                               AVCodecParserContext *pc, AVPacket *pkt)
937
{
938
    int num, den, presentation_delayed, delay, i;
939
    int64_t offset;
940

    
941
    if (s->flags & AVFMT_FLAG_NOFILLIN)
942
        return;
943

    
944
    if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
945
        pkt->dts= AV_NOPTS_VALUE;
946

    
947
    if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == FF_B_TYPE)
948
        //FIXME Set low_delay = 0 when has_b_frames = 1
949
        st->codec->has_b_frames = 1;
950

    
951
    /* do we have a video B-frame ? */
952
    delay= st->codec->has_b_frames;
953
    presentation_delayed = 0;
954

    
955
    // ignore delay caused by frame threading so that the mpeg2-without-dts
956
    // warning will not trigger
957
    if (delay && st->codec->active_thread_type&FF_THREAD_FRAME)
958
        delay -= st->codec->thread_count-1;
959

    
960
    /* XXX: need has_b_frame, but cannot get it if the codec is
961
        not initialized */
962
    if (delay &&
963
        pc && pc->pict_type != FF_B_TYPE)
964
        presentation_delayed = 1;
965

    
966
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
967
       /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
968
        pkt->dts -= 1LL<<st->pts_wrap_bits;
969
    }
970

    
971
    // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
972
    // we take the conservative approach and discard both
973
    // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
974
    if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
975
        av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
976
        pkt->dts= pkt->pts= AV_NOPTS_VALUE;
977
    }
978

    
979
    if (pkt->duration == 0) {
980
        compute_frame_duration(&num, &den, st, pc, pkt);
981
        if (den && num) {
982
            pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
983

    
984
            if(pkt->duration != 0 && s->packet_buffer)
985
                update_initial_durations(s, st, pkt);
986
        }
987
    }
988

    
989
    /* correct timestamps with byte offset if demuxers only have timestamps
990
       on packet boundaries */
991
    if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
992
        /* this will estimate bitrate based on this frame's duration and size */
993
        offset = av_rescale(pc->offset, pkt->duration, pkt->size);
994
        if(pkt->pts != AV_NOPTS_VALUE)
995
            pkt->pts += offset;
996
        if(pkt->dts != AV_NOPTS_VALUE)
997
            pkt->dts += offset;
998
    }
999

    
1000
    if (pc && pc->dts_sync_point >= 0) {
1001
        // we have synchronization info from the parser
1002
        int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
1003
        if (den > 0) {
1004
            int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
1005
            if (pkt->dts != AV_NOPTS_VALUE) {
1006
                // got DTS from the stream, update reference timestamp
1007
                st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
1008
                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
1009
            } else if (st->reference_dts != AV_NOPTS_VALUE) {
1010
                // compute DTS based on reference timestamp
1011
                pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
1012
                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
1013
            }
1014
            if (pc->dts_sync_point > 0)
1015
                st->reference_dts = pkt->dts; // new reference
1016
        }
1017
    }
1018

    
1019
    /* This may be redundant, but it should not hurt. */
1020
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
1021
        presentation_delayed = 1;
1022

    
1023
//    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);
1024
    /* interpolate PTS and DTS if they are not present */
1025
    //We skip H264 currently because delay and has_b_frames are not reliably set
1026
    if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){
1027
        if (presentation_delayed) {
1028
            /* DTS = decompression timestamp */
1029
            /* PTS = presentation timestamp */
1030
            if (pkt->dts == AV_NOPTS_VALUE)
1031
                pkt->dts = st->last_IP_pts;
1032
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
1033
            if (pkt->dts == AV_NOPTS_VALUE)
1034
                pkt->dts = st->cur_dts;
1035

    
1036
            /* this is tricky: the dts must be incremented by the duration
1037
            of the frame we are displaying, i.e. the last I- or P-frame */
1038
            if (st->last_IP_duration == 0)
1039
                st->last_IP_duration = pkt->duration;
1040
            if(pkt->dts != AV_NOPTS_VALUE)
1041
                st->cur_dts = pkt->dts + st->last_IP_duration;
1042
            st->last_IP_duration  = pkt->duration;
1043
            st->last_IP_pts= pkt->pts;
1044
            /* cannot compute PTS if not present (we can compute it only
1045
            by knowing the future */
1046
        } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
1047
            if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
1048
                int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
1049
                int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
1050
                if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
1051
                    pkt->pts += pkt->duration;
1052
    //                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);
1053
                }
1054
            }
1055

    
1056
            /* presentation is not delayed : PTS and DTS are the same */
1057
            if(pkt->pts == AV_NOPTS_VALUE)
1058
                pkt->pts = pkt->dts;
1059
            update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
1060
            if(pkt->pts == AV_NOPTS_VALUE)
1061
                pkt->pts = st->cur_dts;
1062
            pkt->dts = pkt->pts;
1063
            if(pkt->pts != AV_NOPTS_VALUE)
1064
                st->cur_dts = pkt->pts + pkt->duration;
1065
        }
1066
    }
1067

    
1068
    if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
1069
        st->pts_buffer[0]= pkt->pts;
1070
        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
1071
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
1072
        if(pkt->dts == AV_NOPTS_VALUE)
1073
            pkt->dts= st->pts_buffer[0];
1074
        if(st->codec->codec_id == CODEC_ID_H264){ //we skiped it above so we try here
1075
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
1076
        }
1077
        if(pkt->dts > st->cur_dts)
1078
            st->cur_dts = pkt->dts;
1079
    }
1080

    
1081
//    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);
1082

    
1083
    /* update flags */
1084
    if(is_intra_only(st->codec))
1085
        pkt->flags |= AV_PKT_FLAG_KEY;
1086
    else if (pc) {
1087
        pkt->flags = 0;
1088
        /* keyframe computation */
1089
        if (pc->key_frame == 1)
1090
            pkt->flags |= AV_PKT_FLAG_KEY;
1091
        else if (pc->key_frame == -1 && pc->pict_type == FF_I_TYPE)
1092
            pkt->flags |= AV_PKT_FLAG_KEY;
1093
    }
1094
    if (pc)
1095
        pkt->convergence_duration = pc->convergence_duration;
1096
}
1097

    
1098

    
1099
static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1100
{
1101
    AVStream *st;
1102
    int len, ret, i;
1103

    
1104
    av_init_packet(pkt);
1105

    
1106
    for(;;) {
1107
        /* select current input stream component */
1108
        st = s->cur_st;
1109
        if (st) {
1110
            if (!st->need_parsing || !st->parser) {
1111
                /* no parsing needed: we just output the packet as is */
1112
                /* raw data support */
1113
                *pkt = st->cur_pkt; st->cur_pkt.data= NULL;
1114
                compute_pkt_fields(s, st, NULL, pkt);
1115
                s->cur_st = NULL;
1116
                if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1117
                    (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1118
                    ff_reduce_index(s, st->index);
1119
                    av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1120
                }
1121
                break;
1122
            } else if (st->cur_len > 0 && st->discard < AVDISCARD_ALL) {
1123
                len = av_parser_parse2(st->parser, st->codec, &pkt->data, &pkt->size,
1124
                                       st->cur_ptr, st->cur_len,
1125
                                       st->cur_pkt.pts, st->cur_pkt.dts,
1126
                                       st->cur_pkt.pos);
1127
                st->cur_pkt.pts = AV_NOPTS_VALUE;
1128
                st->cur_pkt.dts = AV_NOPTS_VALUE;
1129
                /* increment read pointer */
1130
                st->cur_ptr += len;
1131
                st->cur_len -= len;
1132

    
1133
                /* return packet if any */
1134
                if (pkt->size) {
1135
                got_packet:
1136
                    pkt->duration = 0;
1137
                    pkt->stream_index = st->index;
1138
                    pkt->pts = st->parser->pts;
1139
                    pkt->dts = st->parser->dts;
1140
                    pkt->pos = st->parser->pos;
1141
                    if(pkt->data == st->cur_pkt.data && pkt->size == st->cur_pkt.size){
1142
                        s->cur_st = NULL;
1143
                        pkt->destruct= st->cur_pkt.destruct;
1144
                        st->cur_pkt.destruct= NULL;
1145
                        st->cur_pkt.data    = NULL;
1146
                        assert(st->cur_len == 0);
1147
                    }else{
1148
                    pkt->destruct = NULL;
1149
                    }
1150
                    compute_pkt_fields(s, st, st->parser, pkt);
1151

    
1152
                    if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY){
1153
                        ff_reduce_index(s, st->index);
1154
                        av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
1155
                                           0, 0, AVINDEX_KEYFRAME);
1156
                    }
1157

    
1158
                    break;
1159
                }
1160
            } else {
1161
                /* free packet */
1162
                av_free_packet(&st->cur_pkt);
1163
                s->cur_st = NULL;
1164
            }
1165
        } else {
1166
            AVPacket cur_pkt;
1167
            /* read next packet */
1168
            ret = av_read_packet(s, &cur_pkt);
1169
            if (ret < 0) {
1170
                if (ret == AVERROR(EAGAIN))
1171
                    return ret;
1172
                /* return the last frames, if any */
1173
                for(i = 0; i < s->nb_streams; i++) {
1174
                    st = s->streams[i];
1175
                    if (st->parser && st->need_parsing) {
1176
                        av_parser_parse2(st->parser, st->codec,
1177
                                        &pkt->data, &pkt->size,
1178
                                        NULL, 0,
1179
                                        AV_NOPTS_VALUE, AV_NOPTS_VALUE,
1180
                                        AV_NOPTS_VALUE);
1181
                        if (pkt->size)
1182
                            goto got_packet;
1183
                    }
1184
                }
1185
                /* no more packets: really terminate parsing */
1186
                return ret;
1187
            }
1188
            st = s->streams[cur_pkt.stream_index];
1189
            st->cur_pkt= cur_pkt;
1190

    
1191
            if(st->cur_pkt.pts != AV_NOPTS_VALUE &&
1192
               st->cur_pkt.dts != AV_NOPTS_VALUE &&
1193
               st->cur_pkt.pts < st->cur_pkt.dts){
1194
                av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1195
                    st->cur_pkt.stream_index,
1196
                    st->cur_pkt.pts,
1197
                    st->cur_pkt.dts,
1198
                    st->cur_pkt.size);
1199
//                av_free_packet(&st->cur_pkt);
1200
//                return -1;
1201
            }
1202

    
1203
            if(s->debug & FF_FDEBUG_TS)
1204
                av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1205
                    st->cur_pkt.stream_index,
1206
                    st->cur_pkt.pts,
1207
                    st->cur_pkt.dts,
1208
                    st->cur_pkt.size,
1209
                    st->cur_pkt.duration,
1210
                    st->cur_pkt.flags);
1211

    
1212
            s->cur_st = st;
1213
            st->cur_ptr = st->cur_pkt.data;
1214
            st->cur_len = st->cur_pkt.size;
1215
            if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1216
                st->parser = av_parser_init(st->codec->codec_id);
1217
                if (!st->parser) {
1218
                    /* no parser available: just output the raw packets */
1219
                    st->need_parsing = AVSTREAM_PARSE_NONE;
1220
                }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
1221
                    st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1222
                }else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE){
1223
                    st->parser->flags |= PARSER_FLAG_ONCE;
1224
                }
1225
            }
1226
        }
1227
    }
1228
    if(s->debug & FF_FDEBUG_TS)
1229
        av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1230
            pkt->stream_index,
1231
            pkt->pts,
1232
            pkt->dts,
1233
            pkt->size,
1234
            pkt->duration,
1235
            pkt->flags);
1236

    
1237
    return 0;
1238
}
1239

    
1240
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1241
{
1242
    AVPacketList *pktl;
1243
    int eof=0;
1244
    const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1245

    
1246
    for(;;){
1247
        pktl = s->packet_buffer;
1248
        if (pktl) {
1249
            AVPacket *next_pkt= &pktl->pkt;
1250

    
1251
            if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1252
                int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1253
                while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1254
                    if(   pktl->pkt.stream_index == next_pkt->stream_index
1255
                       && (0 > av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)))
1256
                       && av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
1257
                        next_pkt->pts= pktl->pkt.dts;
1258
                    }
1259
                    pktl= pktl->next;
1260
                }
1261
                pktl = s->packet_buffer;
1262
            }
1263

    
1264
            if(   next_pkt->pts != AV_NOPTS_VALUE
1265
               || next_pkt->dts == AV_NOPTS_VALUE
1266
               || !genpts || eof){
1267
                /* read packet from packet buffer, if there is data */
1268
                *pkt = *next_pkt;
1269
                s->packet_buffer = pktl->next;
1270
                av_free(pktl);
1271
                return 0;
1272
            }
1273
        }
1274
        if(genpts){
1275
            int ret= av_read_frame_internal(s, pkt);
1276
            if(ret<0){
1277
                if(pktl && ret != AVERROR(EAGAIN)){
1278
                    eof=1;
1279
                    continue;
1280
                }else
1281
                    return ret;
1282
            }
1283

    
1284
            if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1285
                                           &s->packet_buffer_end)) < 0)
1286
                return AVERROR(ENOMEM);
1287
        }else{
1288
            assert(!s->packet_buffer);
1289
            return av_read_frame_internal(s, pkt);
1290
        }
1291
    }
1292
}
1293

    
1294
/* XXX: suppress the packet queue */
1295
static void flush_packet_queue(AVFormatContext *s)
1296
{
1297
    AVPacketList *pktl;
1298

    
1299
    for(;;) {
1300
        pktl = s->packet_buffer;
1301
        if (!pktl)
1302
            break;
1303
        s->packet_buffer = pktl->next;
1304
        av_free_packet(&pktl->pkt);
1305
        av_free(pktl);
1306
    }
1307
    while(s->raw_packet_buffer){
1308
        pktl = s->raw_packet_buffer;
1309
        s->raw_packet_buffer = pktl->next;
1310
        av_free_packet(&pktl->pkt);
1311
        av_free(pktl);
1312
    }
1313
    s->packet_buffer_end=
1314
    s->raw_packet_buffer_end= NULL;
1315
    s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1316
}
1317

    
1318
/*******************************************************/
1319
/* seek support */
1320

    
1321
int av_find_default_stream_index(AVFormatContext *s)
1322
{
1323
    int first_audio_index = -1;
1324
    int i;
1325
    AVStream *st;
1326

    
1327
    if (s->nb_streams <= 0)
1328
        return -1;
1329
    for(i = 0; i < s->nb_streams; i++) {
1330
        st = s->streams[i];
1331
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1332
            return i;
1333
        }
1334
        if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1335
            first_audio_index = i;
1336
    }
1337
    return first_audio_index >= 0 ? first_audio_index : 0;
1338
}
1339

    
1340
/**
1341
 * Flush the frame reader.
1342
 */
1343
void ff_read_frame_flush(AVFormatContext *s)
1344
{
1345
    AVStream *st;
1346
    int i, j;
1347

    
1348
    flush_packet_queue(s);
1349

    
1350
    s->cur_st = NULL;
1351

    
1352
    /* for each stream, reset read state */
1353
    for(i = 0; i < s->nb_streams; i++) {
1354
        st = s->streams[i];
1355

    
1356
        if (st->parser) {
1357
            av_parser_close(st->parser);
1358
            st->parser = NULL;
1359
            av_free_packet(&st->cur_pkt);
1360
        }
1361
        st->last_IP_pts = AV_NOPTS_VALUE;
1362
        st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1363
        st->reference_dts = AV_NOPTS_VALUE;
1364
        /* fail safe */
1365
        st->cur_ptr = NULL;
1366
        st->cur_len = 0;
1367

    
1368
        st->probe_packets = MAX_PROBE_PACKETS;
1369

    
1370
        for(j=0; j<MAX_REORDER_DELAY+1; j++)
1371
            st->pts_buffer[j]= AV_NOPTS_VALUE;
1372
    }
1373
}
1374

    
1375
void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1376
    int i;
1377

    
1378
    for(i = 0; i < s->nb_streams; i++) {
1379
        AVStream *st = s->streams[i];
1380

    
1381
        st->cur_dts = av_rescale(timestamp,
1382
                                 st->time_base.den * (int64_t)ref_st->time_base.num,
1383
                                 st->time_base.num * (int64_t)ref_st->time_base.den);
1384
    }
1385
}
1386

    
1387
void ff_reduce_index(AVFormatContext *s, int stream_index)
1388
{
1389
    AVStream *st= s->streams[stream_index];
1390
    unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1391

    
1392
    if((unsigned)st->nb_index_entries >= max_entries){
1393
        int i;
1394
        for(i=0; 2*i<st->nb_index_entries; i++)
1395
            st->index_entries[i]= st->index_entries[2*i];
1396
        st->nb_index_entries= i;
1397
    }
1398
}
1399

    
1400
int ff_add_index_entry(AVIndexEntry **index_entries,
1401
                       int *nb_index_entries,
1402
                       unsigned int *index_entries_allocated_size,
1403
                       int64_t pos, int64_t timestamp, int size, int distance, int flags)
1404
{
1405
    AVIndexEntry *entries, *ie;
1406
    int index;
1407

    
1408
    if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1409
        return -1;
1410

    
1411
    entries = av_fast_realloc(*index_entries,
1412
                              index_entries_allocated_size,
1413
                              (*nb_index_entries + 1) *
1414
                              sizeof(AVIndexEntry));
1415
    if(!entries)
1416
        return -1;
1417

    
1418
    *index_entries= entries;
1419

    
1420
    index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
1421

    
1422
    if(index<0){
1423
        index= (*nb_index_entries)++;
1424
        ie= &entries[index];
1425
        assert(index==0 || ie[-1].timestamp < timestamp);
1426
    }else{
1427
        ie= &entries[index];
1428
        if(ie->timestamp != timestamp){
1429
            if(ie->timestamp <= timestamp)
1430
                return -1;
1431
            memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
1432
            (*nb_index_entries)++;
1433
        }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1434
            distance= ie->min_distance;
1435
    }
1436

    
1437
    ie->pos = pos;
1438
    ie->timestamp = timestamp;
1439
    ie->min_distance= distance;
1440
    ie->size= size;
1441
    ie->flags = flags;
1442

    
1443
    return index;
1444
}
1445

    
1446
int av_add_index_entry(AVStream *st,
1447
                       int64_t pos, int64_t timestamp, int size, int distance, int flags)
1448
{
1449
    return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1450
                              &st->index_entries_allocated_size, pos,
1451
                              timestamp, size, distance, flags);
1452
}
1453

    
1454
int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1455
                              int64_t wanted_timestamp, int flags)
1456
{
1457
    int a, b, m;
1458
    int64_t timestamp;
1459

    
1460
    a = - 1;
1461
    b = nb_entries;
1462

    
1463
    //optimize appending index entries at the end
1464
    if(b && entries[b-1].timestamp < wanted_timestamp)
1465
        a= b-1;
1466

    
1467
    while (b - a > 1) {
1468
        m = (a + b) >> 1;
1469
        timestamp = entries[m].timestamp;
1470
        if(timestamp >= wanted_timestamp)
1471
            b = m;
1472
        if(timestamp <= wanted_timestamp)
1473
            a = m;
1474
    }
1475
    m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1476

    
1477
    if(!(flags & AVSEEK_FLAG_ANY)){
1478
        while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1479
            m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1480
        }
1481
    }
1482

    
1483
    if(m == nb_entries)
1484
        return -1;
1485
    return  m;
1486
}
1487

    
1488
int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1489
                              int flags)
1490
{
1491
    return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1492
                                     wanted_timestamp, flags);
1493
}
1494

    
1495
#define DEBUG_SEEK
1496

    
1497
int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1498
    AVInputFormat *avif= s->iformat;
1499
    int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1500
    int64_t ts_min, ts_max, ts;
1501
    int index;
1502
    int64_t ret;
1503
    AVStream *st;
1504

    
1505
    if (stream_index < 0)
1506
        return -1;
1507

    
1508
#ifdef DEBUG_SEEK
1509
    av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1510
#endif
1511

    
1512
    ts_max=
1513
    ts_min= AV_NOPTS_VALUE;
1514
    pos_limit= -1; //gcc falsely says it may be uninitialized
1515

    
1516
    st= s->streams[stream_index];
1517
    if(st->index_entries){
1518
        AVIndexEntry *e;
1519

    
1520
        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()
1521
        index= FFMAX(index, 0);
1522
        e= &st->index_entries[index];
1523

    
1524
        if(e->timestamp <= target_ts || e->pos == e->min_distance){
1525
            pos_min= e->pos;
1526
            ts_min= e->timestamp;
1527
#ifdef DEBUG_SEEK
1528
            av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1529
                   pos_min,ts_min);
1530
#endif
1531
        }else{
1532
            assert(index==0);
1533
        }
1534

    
1535
        index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1536
        assert(index < st->nb_index_entries);
1537
        if(index >= 0){
1538
            e= &st->index_entries[index];
1539
            assert(e->timestamp >= target_ts);
1540
            pos_max= e->pos;
1541
            ts_max= e->timestamp;
1542
            pos_limit= pos_max - e->min_distance;
1543
#ifdef DEBUG_SEEK
1544
            av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1545
                   pos_max,pos_limit, ts_max);
1546
#endif
1547
        }
1548
    }
1549

    
1550
    pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1551
    if(pos<0)
1552
        return -1;
1553

    
1554
    /* do the seek */
1555
    if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1556
        return ret;
1557

    
1558
    av_update_cur_dts(s, st, ts);
1559

    
1560
    return 0;
1561
}
1562

    
1563
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 )){
1564
    int64_t pos, ts;
1565
    int64_t start_pos, filesize;
1566
    int no_change;
1567

    
1568
#ifdef DEBUG_SEEK
1569
    av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1570
#endif
1571

    
1572
    if(ts_min == AV_NOPTS_VALUE){
1573
        pos_min = s->data_offset;
1574
        ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1575
        if (ts_min == AV_NOPTS_VALUE)
1576
            return -1;
1577
    }
1578

    
1579
    if(ts_max == AV_NOPTS_VALUE){
1580
        int step= 1024;
1581
        filesize = avio_size(s->pb);
1582
        pos_max = filesize - 1;
1583
        do{
1584
            pos_max -= step;
1585
            ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1586
            step += step;
1587
        }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1588
        if (ts_max == AV_NOPTS_VALUE)
1589
            return -1;
1590

    
1591
        for(;;){
1592
            int64_t tmp_pos= pos_max + 1;
1593
            int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1594
            if(tmp_ts == AV_NOPTS_VALUE)
1595
                break;
1596
            ts_max= tmp_ts;
1597
            pos_max= tmp_pos;
1598
            if(tmp_pos >= filesize)
1599
                break;
1600
        }
1601
        pos_limit= pos_max;
1602
    }
1603

    
1604
    if(ts_min > ts_max){
1605
        return -1;
1606
    }else if(ts_min == ts_max){
1607
        pos_limit= pos_min;
1608
    }
1609

    
1610
    no_change=0;
1611
    while (pos_min < pos_limit) {
1612
#ifdef DEBUG_SEEK
1613
        av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1614
               pos_min, pos_max,
1615
               ts_min, ts_max);
1616
#endif
1617
        assert(pos_limit <= pos_max);
1618

    
1619
        if(no_change==0){
1620
            int64_t approximate_keyframe_distance= pos_max - pos_limit;
1621
            // interpolate position (better than dichotomy)
1622
            pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1623
                + pos_min - approximate_keyframe_distance;
1624
        }else if(no_change==1){
1625
            // bisection, if interpolation failed to change min or max pos last time
1626
            pos = (pos_min + pos_limit)>>1;
1627
        }else{
1628
            /* linear search if bisection failed, can only happen if there
1629
               are very few or no keyframes between min/max */
1630
            pos=pos_min;
1631
        }
1632
        if(pos <= pos_min)
1633
            pos= pos_min + 1;
1634
        else if(pos > pos_limit)
1635
            pos= pos_limit;
1636
        start_pos= pos;
1637

    
1638
        ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1639
        if(pos == pos_max)
1640
            no_change++;
1641
        else
1642
            no_change=0;
1643
#ifdef DEBUG_SEEK
1644
        av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1645
               pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit,
1646
               start_pos, no_change);
1647
#endif
1648
        if(ts == AV_NOPTS_VALUE){
1649
            av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1650
            return -1;
1651
        }
1652
        assert(ts != AV_NOPTS_VALUE);
1653
        if (target_ts <= ts) {
1654
            pos_limit = start_pos - 1;
1655
            pos_max = pos;
1656
            ts_max = ts;
1657
        }
1658
        if (target_ts >= ts) {
1659
            pos_min = pos;
1660
            ts_min = ts;
1661
        }
1662
    }
1663

    
1664
    pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1665
    ts  = (flags & AVSEEK_FLAG_BACKWARD) ?  ts_min :  ts_max;
1666
#ifdef DEBUG_SEEK
1667
    pos_min = pos;
1668
    ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1669
    pos_min++;
1670
    ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1671
    av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1672
           pos, ts_min, target_ts, ts_max);
1673
#endif
1674
    *ts_ret= ts;
1675
    return pos;
1676
}
1677

    
1678
static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1679
    int64_t pos_min, pos_max;
1680
#if 0
1681
    AVStream *st;
1682

1683
    if (stream_index < 0)
1684
        return -1;
1685

1686
    st= s->streams[stream_index];
1687
#endif
1688

    
1689
    pos_min = s->data_offset;
1690
    pos_max = avio_size(s->pb) - 1;
1691

    
1692
    if     (pos < pos_min) pos= pos_min;
1693
    else if(pos > pos_max) pos= pos_max;
1694

    
1695
    avio_seek(s->pb, pos, SEEK_SET);
1696

    
1697
#if 0
1698
    av_update_cur_dts(s, st, ts);
1699
#endif
1700
    return 0;
1701
}
1702

    
1703
static int av_seek_frame_generic(AVFormatContext *s,
1704
                                 int stream_index, int64_t timestamp, int flags)
1705
{
1706
    int index;
1707
    int64_t ret;
1708
    AVStream *st;
1709
    AVIndexEntry *ie;
1710

    
1711
    st = s->streams[stream_index];
1712

    
1713
    index = av_index_search_timestamp(st, timestamp, flags);
1714

    
1715
    if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1716
        return -1;
1717

    
1718
    if(index < 0 || index==st->nb_index_entries-1){
1719
        int i;
1720
        AVPacket pkt;
1721

    
1722
        if(st->nb_index_entries){
1723
            assert(st->index_entries);
1724
            ie= &st->index_entries[st->nb_index_entries-1];
1725
            if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1726
                return ret;
1727
            av_update_cur_dts(s, st, ie->timestamp);
1728
        }else{
1729
            if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
1730
                return ret;
1731
        }
1732
        for(i=0;; i++) {
1733
            int ret;
1734
            do{
1735
                ret = av_read_frame(s, &pkt);
1736
            }while(ret == AVERROR(EAGAIN));
1737
            if(ret<0)
1738
                break;
1739
            av_free_packet(&pkt);
1740
            if(stream_index == pkt.stream_index){
1741
                if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
1742
                    break;
1743
            }
1744
        }
1745
        index = av_index_search_timestamp(st, timestamp, flags);
1746
    }
1747
    if (index < 0)
1748
        return -1;
1749

    
1750
    ff_read_frame_flush(s);
1751
    if (s->iformat->read_seek){
1752
        if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1753
            return 0;
1754
    }
1755
    ie = &st->index_entries[index];
1756
    if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1757
        return ret;
1758
    av_update_cur_dts(s, st, ie->timestamp);
1759

    
1760
    return 0;
1761
}
1762

    
1763
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1764
{
1765
    int ret;
1766
    AVStream *st;
1767

    
1768
    ff_read_frame_flush(s);
1769

    
1770
    if(flags & AVSEEK_FLAG_BYTE)
1771
        return av_seek_frame_byte(s, stream_index, timestamp, flags);
1772

    
1773
    if(stream_index < 0){
1774
        stream_index= av_find_default_stream_index(s);
1775
        if(stream_index < 0)
1776
            return -1;
1777

    
1778
        st= s->streams[stream_index];
1779
       /* timestamp for default must be expressed in AV_TIME_BASE units */
1780
        timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1781
    }
1782

    
1783
    /* first, we try the format specific seek */
1784
    if (s->iformat->read_seek)
1785
        ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1786
    else
1787
        ret = -1;
1788
    if (ret >= 0) {
1789
        return 0;
1790
    }
1791

    
1792
    if(s->iformat->read_timestamp)
1793
        return av_seek_frame_binary(s, stream_index, timestamp, flags);
1794
    else
1795
        return av_seek_frame_generic(s, stream_index, timestamp, flags);
1796
}
1797

    
1798
int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1799
{
1800
    if(min_ts > ts || max_ts < ts)
1801
        return -1;
1802

    
1803
    ff_read_frame_flush(s);
1804

    
1805
    if (s->iformat->read_seek2)
1806
        return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1807

    
1808
    if(s->iformat->read_timestamp){
1809
        //try to seek via read_timestamp()
1810
    }
1811

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

    
1817
    // try some generic seek like av_seek_frame_generic() but with new ts semantics
1818
}
1819

    
1820
/*******************************************************/
1821

    
1822
/**
1823
 * Return TRUE if the stream has accurate duration in any stream.
1824
 *
1825
 * @return TRUE if the stream has accurate duration for at least one component.
1826
 */
1827
static int av_has_duration(AVFormatContext *ic)
1828
{
1829
    int i;
1830
    AVStream *st;
1831

    
1832
    for(i = 0;i < ic->nb_streams; i++) {
1833
        st = ic->streams[i];
1834
        if (st->duration != AV_NOPTS_VALUE)
1835
            return 1;
1836
    }
1837
    return 0;
1838
}
1839

    
1840
/**
1841
 * Estimate the stream timings from the one of each components.
1842
 *
1843
 * Also computes the global bitrate if possible.
1844
 */
1845
static void av_update_stream_timings(AVFormatContext *ic)
1846
{
1847
    int64_t start_time, start_time1, end_time, end_time1;
1848
    int64_t duration, duration1;
1849
    int i;
1850
    AVStream *st;
1851

    
1852
    start_time = INT64_MAX;
1853
    end_time = INT64_MIN;
1854
    duration = INT64_MIN;
1855
    for(i = 0;i < ic->nb_streams; i++) {
1856
        st = ic->streams[i];
1857
        if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1858
            start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1859
            if (start_time1 < start_time)
1860
                start_time = start_time1;
1861
            if (st->duration != AV_NOPTS_VALUE) {
1862
                end_time1 = start_time1
1863
                          + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1864
                if (end_time1 > end_time)
1865
                    end_time = end_time1;
1866
            }
1867
        }
1868
        if (st->duration != AV_NOPTS_VALUE) {
1869
            duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1870
            if (duration1 > duration)
1871
                duration = duration1;
1872
        }
1873
    }
1874
    if (start_time != INT64_MAX) {
1875
        ic->start_time = start_time;
1876
        if (end_time != INT64_MIN) {
1877
            if (end_time - start_time > duration)
1878
                duration = end_time - start_time;
1879
        }
1880
    }
1881
    if (duration != INT64_MIN) {
1882
        ic->duration = duration;
1883
        if (ic->file_size > 0) {
1884
            /* compute the bitrate */
1885
            ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1886
                (double)ic->duration;
1887
        }
1888
    }
1889
}
1890

    
1891
static void fill_all_stream_timings(AVFormatContext *ic)
1892
{
1893
    int i;
1894
    AVStream *st;
1895

    
1896
    av_update_stream_timings(ic);
1897
    for(i = 0;i < ic->nb_streams; i++) {
1898
        st = ic->streams[i];
1899
        if (st->start_time == AV_NOPTS_VALUE) {
1900
            if(ic->start_time != AV_NOPTS_VALUE)
1901
                st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1902
            if(ic->duration != AV_NOPTS_VALUE)
1903
                st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1904
        }
1905
    }
1906
}
1907

    
1908
static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1909
{
1910
    int64_t filesize, duration;
1911
    int bit_rate, i;
1912
    AVStream *st;
1913

    
1914
    /* if bit_rate is already set, we believe it */
1915
    if (ic->bit_rate <= 0) {
1916
        bit_rate = 0;
1917
        for(i=0;i<ic->nb_streams;i++) {
1918
            st = ic->streams[i];
1919
            if (st->codec->bit_rate > 0)
1920
            bit_rate += st->codec->bit_rate;
1921
        }
1922
        ic->bit_rate = bit_rate;
1923
    }
1924

    
1925
    /* if duration is already set, we believe it */
1926
    if (ic->duration == AV_NOPTS_VALUE &&
1927
        ic->bit_rate != 0 &&
1928
        ic->file_size != 0)  {
1929
        filesize = ic->file_size;
1930
        if (filesize > 0) {
1931
            for(i = 0; i < ic->nb_streams; i++) {
1932
                st = ic->streams[i];
1933
                duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1934
                if (st->duration == AV_NOPTS_VALUE)
1935
                    st->duration = duration;
1936
            }
1937
        }
1938
    }
1939
}
1940

    
1941
#define DURATION_MAX_READ_SIZE 250000
1942
#define DURATION_MAX_RETRY 3
1943

    
1944
/* only usable for MPEG-PS streams */
1945
static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1946
{
1947
    AVPacket pkt1, *pkt = &pkt1;
1948
    AVStream *st;
1949
    int read_size, i, ret;
1950
    int64_t end_time;
1951
    int64_t filesize, offset, duration;
1952
    int retry=0;
1953

    
1954
    ic->cur_st = NULL;
1955

    
1956
    /* flush packet queue */
1957
    flush_packet_queue(ic);
1958

    
1959
    for (i=0; i<ic->nb_streams; i++) {
1960
        st = ic->streams[i];
1961
        if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
1962
            av_log(st->codec, AV_LOG_WARNING, "start time is not set in av_estimate_timings_from_pts\n");
1963

    
1964
        if (st->parser) {
1965
            av_parser_close(st->parser);
1966
            st->parser= NULL;
1967
            av_free_packet(&st->cur_pkt);
1968
        }
1969
    }
1970

    
1971
    /* estimate the end time (duration) */
1972
    /* XXX: may need to support wrapping */
1973
    filesize = ic->file_size;
1974
    end_time = AV_NOPTS_VALUE;
1975
    do{
1976
    offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
1977
    if (offset < 0)
1978
        offset = 0;
1979

    
1980
    avio_seek(ic->pb, offset, SEEK_SET);
1981
    read_size = 0;
1982
    for(;;) {
1983
        if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
1984
            break;
1985

    
1986
        do{
1987
            ret = av_read_packet(ic, pkt);
1988
        }while(ret == AVERROR(EAGAIN));
1989
        if (ret != 0)
1990
            break;
1991
        read_size += pkt->size;
1992
        st = ic->streams[pkt->stream_index];
1993
        if (pkt->pts != AV_NOPTS_VALUE &&
1994
            (st->start_time != AV_NOPTS_VALUE ||
1995
             st->first_dts  != AV_NOPTS_VALUE)) {
1996
            duration = end_time = pkt->pts;
1997
            if (st->start_time != AV_NOPTS_VALUE)  duration -= st->start_time;
1998
            else                                   duration -= st->first_dts;
1999
            if (duration < 0)
2000
                duration += 1LL<<st->pts_wrap_bits;
2001
            if (duration > 0) {
2002
                if (st->duration == AV_NOPTS_VALUE ||
2003
                    st->duration < duration)
2004
                    st->duration = duration;
2005
            }
2006
        }
2007
        av_free_packet(pkt);
2008
    }
2009
    }while(   end_time==AV_NOPTS_VALUE
2010
           && filesize > (DURATION_MAX_READ_SIZE<<retry)
2011
           && ++retry <= DURATION_MAX_RETRY);
2012

    
2013
    fill_all_stream_timings(ic);
2014

    
2015
    avio_seek(ic->pb, old_offset, SEEK_SET);
2016
    for (i=0; i<ic->nb_streams; i++) {
2017
        st= ic->streams[i];
2018
        st->cur_dts= st->first_dts;
2019
        st->last_IP_pts = AV_NOPTS_VALUE;
2020
        st->reference_dts = AV_NOPTS_VALUE;
2021
    }
2022
}
2023

    
2024
static void av_estimate_timings(AVFormatContext *ic, int64_t old_offset)
2025
{
2026
    int64_t file_size;
2027

    
2028
    /* get the file size, if possible */
2029
    if (ic->iformat->flags & AVFMT_NOFILE) {
2030
        file_size = 0;
2031
    } else {
2032
        file_size = avio_size(ic->pb);
2033
        if (file_size < 0)
2034
            file_size = 0;
2035
    }
2036
    ic->file_size = file_size;
2037

    
2038
    if ((!strcmp(ic->iformat->name, "mpeg") ||
2039
         !strcmp(ic->iformat->name, "mpegts")) &&
2040
        file_size && !url_is_streamed(ic->pb)) {
2041
        /* get accurate estimate from the PTSes */
2042
        av_estimate_timings_from_pts(ic, old_offset);
2043
    } else if (av_has_duration(ic)) {
2044
        /* at least one component has timings - we use them for all
2045
           the components */
2046
        fill_all_stream_timings(ic);
2047
    } else {
2048
        av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
2049
        /* less precise: use bitrate info */
2050
        av_estimate_timings_from_bit_rate(ic);
2051
    }
2052
    av_update_stream_timings(ic);
2053

    
2054
#if 0
2055
    {
2056
        int i;
2057
        AVStream *st;
2058
        for(i = 0;i < ic->nb_streams; i++) {
2059
            st = ic->streams[i];
2060
        printf("%d: start_time: %0.3f duration: %0.3f\n",
2061
               i, (double)st->start_time / AV_TIME_BASE,
2062
               (double)st->duration / AV_TIME_BASE);
2063
        }
2064
        printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2065
               (double)ic->start_time / AV_TIME_BASE,
2066
               (double)ic->duration / AV_TIME_BASE,
2067
               ic->bit_rate / 1000);
2068
    }
2069
#endif
2070
}
2071

    
2072
static int has_codec_parameters(AVCodecContext *enc)
2073
{
2074
    int val;
2075
    switch(enc->codec_type) {
2076
    case AVMEDIA_TYPE_AUDIO:
2077
        val = enc->sample_rate && enc->channels && enc->sample_fmt != AV_SAMPLE_FMT_NONE;
2078
        if(!enc->frame_size &&
2079
           (enc->codec_id == CODEC_ID_VORBIS ||
2080
            enc->codec_id == CODEC_ID_AAC ||
2081
            enc->codec_id == CODEC_ID_MP1 ||
2082
            enc->codec_id == CODEC_ID_MP2 ||
2083
            enc->codec_id == CODEC_ID_MP3 ||
2084
            enc->codec_id == CODEC_ID_SPEEX))
2085
            return 0;
2086
        break;
2087
    case AVMEDIA_TYPE_VIDEO:
2088
        val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
2089
        break;
2090
    default:
2091
        val = 1;
2092
        break;
2093
    }
2094
    return enc->codec_id != CODEC_ID_NONE && val != 0;
2095
}
2096

    
2097
static int has_decode_delay_been_guessed(AVStream *st)
2098
{
2099
    return st->codec->codec_id != CODEC_ID_H264 ||
2100
        st->codec_info_nb_frames >= 6 + st->codec->has_b_frames;
2101
}
2102

    
2103
static int try_decode_frame(AVStream *st, AVPacket *avpkt)
2104
{
2105
    int16_t *samples;
2106
    AVCodec *codec;
2107
    int got_picture, data_size, ret=0;
2108
    AVFrame picture;
2109

    
2110
    if(!st->codec->codec){
2111
        codec = avcodec_find_decoder(st->codec->codec_id);
2112
        if (!codec)
2113
            return -1;
2114
        ret = avcodec_open(st->codec, codec);
2115
        if (ret < 0)
2116
            return ret;
2117
    }
2118

    
2119
    if(!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st)){
2120
        switch(st->codec->codec_type) {
2121
        case AVMEDIA_TYPE_VIDEO:
2122
            avcodec_get_frame_defaults(&picture);
2123
            ret = avcodec_decode_video2(st->codec, &picture,
2124
                                        &got_picture, avpkt);
2125
            break;
2126
        case AVMEDIA_TYPE_AUDIO:
2127
            data_size = FFMAX(avpkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
2128
            samples = av_malloc(data_size);
2129
            if (!samples)
2130
                goto fail;
2131
            ret = avcodec_decode_audio3(st->codec, samples,
2132
                                        &data_size, avpkt);
2133
            av_free(samples);
2134
            break;
2135
        default:
2136
            break;
2137
        }
2138
    }
2139
 fail:
2140
    return ret;
2141
}
2142

    
2143
unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum CodecID id)
2144
{
2145
    while (tags->id != CODEC_ID_NONE) {
2146
        if (tags->id == id)
2147
            return tags->tag;
2148
        tags++;
2149
    }
2150
    return 0;
2151
}
2152

    
2153
enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2154
{
2155
    int i;
2156
    for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
2157
        if(tag == tags[i].tag)
2158
            return tags[i].id;
2159
    }
2160
    for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
2161
        if (ff_toupper4(tag) == ff_toupper4(tags[i].tag))
2162
            return tags[i].id;
2163
    }
2164
    return CODEC_ID_NONE;
2165
}
2166

    
2167
unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
2168
{
2169
    int i;
2170
    for(i=0; tags && tags[i]; i++){
2171
        int tag= ff_codec_get_tag(tags[i], id);
2172
        if(tag) return tag;
2173
    }
2174
    return 0;
2175
}
2176

    
2177
enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2178
{
2179
    int i;
2180
    for(i=0; tags && tags[i]; i++){
2181
        enum CodecID id= ff_codec_get_id(tags[i], tag);
2182
        if(id!=CODEC_ID_NONE) return id;
2183
    }
2184
    return CODEC_ID_NONE;
2185
}
2186

    
2187
static void compute_chapters_end(AVFormatContext *s)
2188
{
2189
    unsigned int i, j;
2190
    int64_t max_time = s->duration + (s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time;
2191

    
2192
    for (i = 0; i < s->nb_chapters; i++)
2193
        if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2194
            AVChapter *ch = s->chapters[i];
2195
            int64_t   end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
2196
                                     : INT64_MAX;
2197

    
2198
            for (j = 0; j < s->nb_chapters; j++) {
2199
                AVChapter *ch1 = s->chapters[j];
2200
                int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
2201
                if (j != i && next_start > ch->start && next_start < end)
2202
                    end = next_start;
2203
            }
2204
            ch->end = (end == INT64_MAX) ? ch->start : end;
2205
        }
2206
}
2207

    
2208
static int get_std_framerate(int i){
2209
    if(i<60*12) return i*1001;
2210
    else        return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2211
}
2212

    
2213
/*
2214
 * Is the time base unreliable.
2215
 * This is a heuristic to balance between quick acceptance of the values in
2216
 * the headers vs. some extra checks.
2217
 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2218
 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2219
 * And there are "variable" fps files this needs to detect as well.
2220
 */
2221
static int tb_unreliable(AVCodecContext *c){
2222
    if(   c->time_base.den >= 101L*c->time_base.num
2223
       || c->time_base.den <    5L*c->time_base.num
2224
/*       || c->codec_tag == AV_RL32("DIVX")
2225
       || c->codec_tag == AV_RL32("XVID")*/
2226
       || c->codec_id == CODEC_ID_MPEG2VIDEO
2227
       || c->codec_id == CODEC_ID_H264
2228
       )
2229
        return 1;
2230
    return 0;
2231
}
2232

    
2233
int av_find_stream_info(AVFormatContext *ic)
2234
{
2235
    int i, count, ret, read_size, j;
2236
    AVStream *st;
2237
    AVPacket pkt1, *pkt;
2238
    int64_t old_offset = avio_tell(ic->pb);
2239

    
2240
    for(i=0;i<ic->nb_streams;i++) {
2241
        AVCodec *codec;
2242
        st = ic->streams[i];
2243
        if (st->codec->codec_id == CODEC_ID_AAC) {
2244
            st->codec->sample_rate = 0;
2245
            st->codec->frame_size = 0;
2246
            st->codec->channels = 0;
2247
        }
2248
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2249
            st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2250
/*            if(!st->time_base.num)
2251
                st->time_base= */
2252
            if(!st->codec->time_base.num)
2253
                st->codec->time_base= st->time_base;
2254
        }
2255
        //only for the split stuff
2256
        if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2257
            st->parser = av_parser_init(st->codec->codec_id);
2258
            if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2259
                st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2260
            }
2261
        }
2262
        assert(!st->codec->codec);
2263
        codec = avcodec_find_decoder(st->codec->codec_id);
2264

    
2265
        /* Force decoding of at least one frame of codec data
2266
         * this makes sure the codec initializes the channel configuration
2267
         * and does not trust the values from the container.
2268
         */
2269
        if (codec && codec->capabilities & CODEC_CAP_CHANNEL_CONF)
2270
            st->codec->channels = 0;
2271

    
2272
        /* Ensure that subtitle_header is properly set. */
2273
        if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
2274
            && codec && !st->codec->codec)
2275
            avcodec_open(st->codec, codec);
2276

    
2277
        //try to just open decoders, in case this is enough to get parameters
2278
        if(!has_codec_parameters(st->codec)){
2279
            if (codec && !st->codec->codec)
2280
                avcodec_open(st->codec, codec);
2281
        }
2282
    }
2283

    
2284
    for (i=0; i<ic->nb_streams; i++) {
2285
        ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
2286
    }
2287

    
2288
    count = 0;
2289
    read_size = 0;
2290
    for(;;) {
2291
        if(url_interrupt_cb()){
2292
            ret= AVERROR_EXIT;
2293
            av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2294
            break;
2295
        }
2296

    
2297
        /* check if one codec still needs to be handled */
2298
        for(i=0;i<ic->nb_streams;i++) {
2299
            int fps_analyze_framecount = 20;
2300

    
2301
            st = ic->streams[i];
2302
            if (!has_codec_parameters(st->codec))
2303
                break;
2304
            /* if the timebase is coarse (like the usual millisecond precision
2305
               of mkv), we need to analyze more frames to reliably arrive at
2306
               the correct fps */
2307
            if (av_q2d(st->time_base) > 0.0005)
2308
                fps_analyze_framecount *= 2;
2309
            /* variable fps and no guess at the real fps */
2310
            if(   tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)
2311
               && st->info->duration_count < fps_analyze_framecount
2312
               && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2313
                break;
2314
            if(st->parser && st->parser->parser->split && !st->codec->extradata)
2315
                break;
2316
            if(st->first_dts == AV_NOPTS_VALUE)
2317
                break;
2318
        }
2319
        if (i == ic->nb_streams) {
2320
            /* NOTE: if the format has no header, then we need to read
2321
               some packets to get most of the streams, so we cannot
2322
               stop here */
2323
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2324
                /* if we found the info for all the codecs, we can stop */
2325
                ret = count;
2326
                av_log(ic, AV_LOG_DEBUG, "All info found\n");
2327
                break;
2328
            }
2329
        }
2330
        /* we did not get all the codec info, but we read too much data */
2331
        if (read_size >= ic->probesize) {
2332
            ret = count;
2333
            av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2334
            break;
2335
        }
2336

    
2337
        /* NOTE: a new stream can be added there if no header in file
2338
           (AVFMTCTX_NOHEADER) */
2339
        ret = av_read_frame_internal(ic, &pkt1);
2340
        if (ret < 0 && ret != AVERROR(EAGAIN)) {
2341
            /* EOF or error */
2342
            ret = -1; /* we could not have all the codec parameters before EOF */
2343
            for(i=0;i<ic->nb_streams;i++) {
2344
                st = ic->streams[i];
2345
                if (!has_codec_parameters(st->codec)){
2346
                    char buf[256];
2347
                    avcodec_string(buf, sizeof(buf), st->codec, 0);
2348
                    av_log(ic, AV_LOG_WARNING, "Could not find codec parameters (%s)\n", buf);
2349
                } else {
2350
                    ret = 0;
2351
                }
2352
            }
2353
            break;
2354
        }
2355

    
2356
        if (ret == AVERROR(EAGAIN))
2357
            continue;
2358

    
2359
        pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
2360
        if ((ret = av_dup_packet(pkt)) < 0)
2361
            goto find_stream_info_err;
2362

    
2363
        read_size += pkt->size;
2364

    
2365
        st = ic->streams[pkt->stream_index];
2366
        if (st->codec_info_nb_frames>1) {
2367
            if (st->time_base.den > 0 && av_rescale_q(st->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
2368
                av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2369
                break;
2370
            }
2371
            st->info->codec_info_duration += pkt->duration;
2372
        }
2373
        {
2374
            int64_t last = st->info->last_dts;
2375
            int64_t duration= pkt->dts - last;
2376

    
2377
            if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
2378
                double dur= duration * av_q2d(st->time_base);
2379

    
2380
//                if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2381
//                    av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
2382
                if (st->info->duration_count < 2)
2383
                    memset(st->info->duration_error, 0, sizeof(st->info->duration_error));
2384
                for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error); i++) {
2385
                    int framerate= get_std_framerate(i);
2386
                    int ticks= lrintf(dur*framerate/(1001*12));
2387
                    double error= dur - ticks*1001*12/(double)framerate;
2388
                    st->info->duration_error[i] += error*error;
2389
                }
2390
                st->info->duration_count++;
2391
                // ignore the first 4 values, they might have some random jitter
2392
                if (st->info->duration_count > 3)
2393
                    st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
2394
            }
2395
            if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
2396
                st->info->last_dts = pkt->dts;
2397
        }
2398
        if(st->parser && st->parser->parser->split && !st->codec->extradata){
2399
            int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2400
            if(i){
2401
                st->codec->extradata_size= i;
2402
                st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2403
                memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2404
                memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2405
            }
2406
        }
2407

    
2408
        /* if still no information, we try to open the codec and to
2409
           decompress the frame. We try to avoid that in most cases as
2410
           it takes longer and uses more memory. For MPEG-4, we need to
2411
           decompress for QuickTime. */
2412
        if (!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st))
2413
            try_decode_frame(st, pkt);
2414

    
2415
        st->codec_info_nb_frames++;
2416
        count++;
2417
    }
2418

    
2419
    // close codecs which were opened in try_decode_frame()
2420
    for(i=0;i<ic->nb_streams;i++) {
2421
        st = ic->streams[i];
2422
        if(st->codec->codec)
2423
            avcodec_close(st->codec);
2424
    }
2425
    for(i=0;i<ic->nb_streams;i++) {
2426
        st = ic->streams[i];
2427
        if (st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && st->info->codec_info_duration)
2428
            av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2429
                     (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,
2430
                      st->info->codec_info_duration*(int64_t)st->time_base.num, 60000);
2431
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2432
            if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample){
2433
                uint32_t tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2434
                if(ff_find_pix_fmt(ff_raw_pix_fmt_tags, tag) == st->codec->pix_fmt)
2435
                    st->codec->codec_tag= tag;
2436
            }
2437

    
2438
            // the check for tb_unreliable() is not completely correct, since this is not about handling
2439
            // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2440
            // ipmovie.c produces.
2441
            if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > FFMAX(1, st->time_base.den/(500LL*st->time_base.num)) && !st->r_frame_rate.num)
2442
                av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * st->info->duration_gcd, INT_MAX);
2443
            if (st->info->duration_count && !st->r_frame_rate.num
2444
               && tb_unreliable(st->codec) /*&&
2445
               //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2446
               st->time_base.num*duration_sum[i]/st->info->duration_count*101LL > st->time_base.den*/){
2447
                int num = 0;
2448
                double best_error= 2*av_q2d(st->time_base);
2449
                best_error = best_error*best_error*st->info->duration_count*1000*12*30;
2450

    
2451
                for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error); j++) {
2452
                    double error = st->info->duration_error[j] * get_std_framerate(j);
2453
//                    if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2454
//                        av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
2455
                    if(error < best_error){
2456
                        best_error= error;
2457
                        num = get_std_framerate(j);
2458
                    }
2459
                }
2460
                // do not increase frame rate by more than 1 % in order to match a standard rate.
2461
                if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
2462
                    av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2463
            }
2464

    
2465
            if (!st->r_frame_rate.num){
2466
                if(    st->codec->time_base.den * (int64_t)st->time_base.num
2467
                    <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){
2468
                    st->r_frame_rate.num = st->codec->time_base.den;
2469
                    st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
2470
                }else{
2471
                    st->r_frame_rate.num = st->time_base.den;
2472
                    st->r_frame_rate.den = st->time_base.num;
2473
                }
2474
            }
2475
        }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2476
            if(!st->codec->bits_per_coded_sample)
2477
                st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2478
            // set stream disposition based on audio service type
2479
            switch (st->codec->audio_service_type) {
2480
            case AV_AUDIO_SERVICE_TYPE_EFFECTS:
2481
                st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;    break;
2482
            case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
2483
                st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;  break;
2484
            case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
2485
                st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
2486
            case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
2487
                st->disposition = AV_DISPOSITION_COMMENT;          break;
2488
            case AV_AUDIO_SERVICE_TYPE_KARAOKE:
2489
                st->disposition = AV_DISPOSITION_KARAOKE;          break;
2490
            }
2491
        }
2492
    }
2493

    
2494
    av_estimate_timings(ic, old_offset);
2495

    
2496
    compute_chapters_end(ic);
2497

    
2498
#if 0
2499
    /* correct DTS for B-frame streams with no timestamps */
2500
    for(i=0;i<ic->nb_streams;i++) {
2501
        st = ic->streams[i];
2502
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2503
            if(b-frames){
2504
                ppktl = &ic->packet_buffer;
2505
                while(ppkt1){
2506
                    if(ppkt1->stream_index != i)
2507
                        continue;
2508
                    if(ppkt1->pkt->dts < 0)
2509
                        break;
2510
                    if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2511
                        break;
2512
                    ppkt1->pkt->dts -= delta;
2513
                    ppkt1= ppkt1->next;
2514
                }
2515
                if(ppkt1)
2516
                    continue;
2517
                st->cur_dts -= delta;
2518
            }
2519
        }
2520
    }
2521
#endif
2522

    
2523
 find_stream_info_err:
2524
    for (i=0; i < ic->nb_streams; i++)
2525
        av_freep(&ic->streams[i]->info);
2526
    return ret;
2527
}
2528

    
2529
static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
2530
{
2531
    int i, j;
2532

    
2533
    for (i = 0; i < ic->nb_programs; i++)
2534
        for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2535
            if (ic->programs[i]->stream_index[j] == s)
2536
                return ic->programs[i];
2537
    return NULL;
2538
}
2539

    
2540
int av_find_best_stream(AVFormatContext *ic,
2541
                        enum AVMediaType type,
2542
                        int wanted_stream_nb,
2543
                        int related_stream,
2544
                        AVCodec **decoder_ret,
2545
                        int flags)
2546
{
2547
    int i, nb_streams = ic->nb_streams;
2548
    int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2549
    unsigned *program = NULL;
2550
    AVCodec *decoder = NULL, *best_decoder = NULL;
2551

    
2552
    if (related_stream >= 0 && wanted_stream_nb < 0) {
2553
        AVProgram *p = find_program_from_stream(ic, related_stream);
2554
        if (p) {
2555
            program = p->stream_index;
2556
            nb_streams = p->nb_stream_indexes;
2557
        }
2558
    }
2559
    for (i = 0; i < nb_streams; i++) {
2560
        int real_stream_index = program ? program[i] : i;
2561
        AVStream *st = ic->streams[real_stream_index];
2562
        AVCodecContext *avctx = st->codec;
2563
        if (avctx->codec_type != type)
2564
            continue;
2565
        if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
2566
            continue;
2567
        if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
2568
            continue;
2569
        if (decoder_ret) {
2570
            decoder = avcodec_find_decoder(st->codec->codec_id);
2571
            if (!decoder) {
2572
                if (ret < 0)
2573
                    ret = AVERROR_DECODER_NOT_FOUND;
2574
                continue;
2575
            }
2576
        }
2577
        if (best_count >= st->codec_info_nb_frames)
2578
            continue;
2579
        best_count = st->codec_info_nb_frames;
2580
        ret = real_stream_index;
2581
        best_decoder = decoder;
2582
        if (program && i == nb_streams - 1 && ret < 0) {
2583
            program = NULL;
2584
            nb_streams = ic->nb_streams;
2585
            i = 0; /* no related stream found, try again with everything */
2586
        }
2587
    }
2588
    if (decoder_ret)
2589
        *decoder_ret = best_decoder;
2590
    return ret;
2591
}
2592

    
2593
/*******************************************************/
2594

    
2595
int av_read_play(AVFormatContext *s)
2596
{
2597
    if (s->iformat->read_play)
2598
        return s->iformat->read_play(s);
2599
    if (s->pb)
2600
        return ffio_read_pause(s->pb, 0);
2601
    return AVERROR(ENOSYS);
2602
}
2603

    
2604
int av_read_pause(AVFormatContext *s)
2605
{
2606
    if (s->iformat->read_pause)
2607
        return s->iformat->read_pause(s);
2608
    if (s->pb)
2609
        return ffio_read_pause(s->pb, 1);
2610
    return AVERROR(ENOSYS);
2611
}
2612

    
2613
void av_close_input_stream(AVFormatContext *s)
2614
{
2615
    flush_packet_queue(s);
2616
    if (s->iformat->read_close)
2617
        s->iformat->read_close(s);
2618
    avformat_free_context(s);
2619
}
2620

    
2621
void avformat_free_context(AVFormatContext *s)
2622
{
2623
    int i;
2624
    AVStream *st;
2625

    
2626
    for(i=0;i<s->nb_streams;i++) {
2627
        /* free all data in a stream component */
2628
        st = s->streams[i];
2629
        if (st->parser) {
2630
            av_parser_close(st->parser);
2631
            av_free_packet(&st->cur_pkt);
2632
        }
2633
        av_metadata_free(&st->metadata);
2634
        av_free(st->index_entries);
2635
        av_free(st->codec->extradata);
2636
        av_free(st->codec->subtitle_header);
2637
        av_free(st->codec);
2638
#if FF_API_OLD_METADATA
2639
        av_free(st->filename);
2640
#endif
2641
        av_free(st->priv_data);
2642
        av_free(st->info);
2643
        av_free(st);
2644
    }
2645
    for(i=s->nb_programs-1; i>=0; i--) {
2646
#if FF_API_OLD_METADATA
2647
        av_freep(&s->programs[i]->provider_name);
2648
        av_freep(&s->programs[i]->name);
2649
#endif
2650
        av_metadata_free(&s->programs[i]->metadata);
2651
        av_freep(&s->programs[i]->stream_index);
2652
        av_freep(&s->programs[i]);
2653
    }
2654
    av_freep(&s->programs);
2655
    av_freep(&s->priv_data);
2656
    while(s->nb_chapters--) {
2657
#if FF_API_OLD_METADATA
2658
        av_free(s->chapters[s->nb_chapters]->title);
2659
#endif
2660
        av_metadata_free(&s->chapters[s->nb_chapters]->metadata);
2661
        av_free(s->chapters[s->nb_chapters]);
2662
    }
2663
    av_freep(&s->chapters);
2664
    av_metadata_free(&s->metadata);
2665
    av_freep(&s->key);
2666
    av_free(s);
2667
}
2668

    
2669
void av_close_input_file(AVFormatContext *s)
2670
{
2671
    AVIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
2672
    av_close_input_stream(s);
2673
    if (pb)
2674
        avio_close(pb);
2675
}
2676

    
2677
AVStream *av_new_stream(AVFormatContext *s, int id)
2678
{
2679
    AVStream *st;
2680
    int i;
2681

    
2682
#if FF_API_MAX_STREAMS
2683
    if (s->nb_streams >= MAX_STREAMS){
2684
        av_log(s, AV_LOG_ERROR, "Too many streams\n");
2685
        return NULL;
2686
    }
2687
#else
2688
    AVStream **streams;
2689

    
2690
    if (s->nb_streams >= INT_MAX/sizeof(*streams))
2691
        return NULL;
2692
    streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
2693
    if (!streams)
2694
        return NULL;
2695
    s->streams = streams;
2696
#endif
2697

    
2698
    st = av_mallocz(sizeof(AVStream));
2699
    if (!st)
2700
        return NULL;
2701
    if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2702
        av_free(st);
2703
        return NULL;
2704
    }
2705

    
2706
    st->codec= avcodec_alloc_context();
2707
    if (s->iformat) {
2708
        /* no default bitrate if decoding */
2709
        st->codec->bit_rate = 0;
2710
    }
2711
    st->index = s->nb_streams;
2712
    st->id = id;
2713
    st->start_time = AV_NOPTS_VALUE;
2714
    st->duration = AV_NOPTS_VALUE;
2715
        /* we set the current DTS to 0 so that formats without any timestamps
2716
           but durations get some timestamps, formats with some unknown
2717
           timestamps have their first few packets buffered and the
2718
           timestamps corrected before they are returned to the user */
2719
    st->cur_dts = 0;
2720
    st->first_dts = AV_NOPTS_VALUE;
2721
    st->probe_packets = MAX_PROBE_PACKETS;
2722

    
2723
    /* default pts setting is MPEG-like */
2724
    av_set_pts_info(st, 33, 1, 90000);
2725
    st->last_IP_pts = AV_NOPTS_VALUE;
2726
    for(i=0; i<MAX_REORDER_DELAY+1; i++)
2727
        st->pts_buffer[i]= AV_NOPTS_VALUE;
2728
    st->reference_dts = AV_NOPTS_VALUE;
2729

    
2730
    st->sample_aspect_ratio = (AVRational){0,1};
2731

    
2732
    s->streams[s->nb_streams++] = st;
2733
    return st;
2734
}
2735

    
2736
AVProgram *av_new_program(AVFormatContext *ac, int id)
2737
{
2738
    AVProgram *program=NULL;
2739
    int i;
2740

    
2741
#ifdef DEBUG_SI
2742
    av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id);
2743
#endif
2744

    
2745
    for(i=0; i<ac->nb_programs; i++)
2746
        if(ac->programs[i]->id == id)
2747
            program = ac->programs[i];
2748

    
2749
    if(!program){
2750
        program = av_mallocz(sizeof(AVProgram));
2751
        if (!program)
2752
            return NULL;
2753
        dynarray_add(&ac->programs, &ac->nb_programs, program);
2754
        program->discard = AVDISCARD_NONE;
2755
    }
2756
    program->id = id;
2757

    
2758
    return program;
2759
}
2760

    
2761
AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2762
{
2763
    AVChapter *chapter = NULL;
2764
    int i;
2765

    
2766
    for(i=0; i<s->nb_chapters; i++)
2767
        if(s->chapters[i]->id == id)
2768
            chapter = s->chapters[i];
2769

    
2770
    if(!chapter){
2771
        chapter= av_mallocz(sizeof(AVChapter));
2772
        if(!chapter)
2773
            return NULL;
2774
        dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2775
    }
2776
#if FF_API_OLD_METADATA
2777
    av_free(chapter->title);
2778
#endif
2779
    av_metadata_set2(&chapter->metadata, "title", title, 0);
2780
    chapter->id    = id;
2781
    chapter->time_base= time_base;
2782
    chapter->start = start;
2783
    chapter->end   = end;
2784

    
2785
    return chapter;
2786
}
2787

    
2788
/************************************************************/
2789
/* output media file */
2790

    
2791
int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2792
{
2793
    int ret;
2794

    
2795
    if (s->oformat->priv_data_size > 0) {
2796
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
2797
        if (!s->priv_data)
2798
            return AVERROR(ENOMEM);
2799
        if (s->oformat->priv_class) {
2800
            *(const AVClass**)s->priv_data= s->oformat->priv_class;
2801
            av_opt_set_defaults(s->priv_data);
2802
        }
2803
    } else
2804
        s->priv_data = NULL;
2805

    
2806
    if (s->oformat->set_parameters) {
2807
        ret = s->oformat->set_parameters(s, ap);
2808
        if (ret < 0)
2809
            return ret;
2810
    }
2811
    return 0;
2812
}
2813

    
2814
static int validate_codec_tag(AVFormatContext *s, AVStream *st)
2815
{
2816
    const AVCodecTag *avctag;
2817
    int n;
2818
    enum CodecID id = CODEC_ID_NONE;
2819
    unsigned int tag = 0;
2820

    
2821
    /**
2822
     * Check that tag + id is in the table
2823
     * If neither is in the table -> OK
2824
     * If tag is in the table with another id -> FAIL
2825
     * If id is in the table with another tag -> FAIL unless strict < normal
2826
     */
2827
    for (n = 0; s->oformat->codec_tag[n]; n++) {
2828
        avctag = s->oformat->codec_tag[n];
2829
        while (avctag->id != CODEC_ID_NONE) {
2830
            if (ff_toupper4(avctag->tag) == ff_toupper4(st->codec->codec_tag)) {
2831
                id = avctag->id;
2832
                if (id == st->codec->codec_id)
2833
                    return 1;
2834
            }
2835
            if (avctag->id == st->codec->codec_id)
2836
                tag = avctag->tag;
2837
            avctag++;
2838
        }
2839
    }
2840
    if (id != CODEC_ID_NONE)
2841
        return 0;
2842
    if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
2843
        return 0;
2844
    return 1;
2845
}
2846

    
2847
int av_write_header(AVFormatContext *s)
2848
{
2849
    int ret, i;
2850
    AVStream *st;
2851

    
2852
    // some sanity checks
2853
    if (s->nb_streams == 0 && !(s->oformat->flags & AVFMT_NOSTREAMS)) {
2854
        av_log(s, AV_LOG_ERROR, "no streams\n");
2855
        return AVERROR(EINVAL);
2856
    }
2857

    
2858
    for(i=0;i<s->nb_streams;i++) {
2859
        st = s->streams[i];
2860

    
2861
        switch (st->codec->codec_type) {
2862
        case AVMEDIA_TYPE_AUDIO:
2863
            if(st->codec->sample_rate<=0){
2864
                av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2865
                return AVERROR(EINVAL);
2866
            }
2867
            if(!st->codec->block_align)
2868
                st->codec->block_align = st->codec->channels *
2869
                    av_get_bits_per_sample(st->codec->codec_id) >> 3;
2870
            break;
2871
        case AVMEDIA_TYPE_VIDEO:
2872
            if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2873
                av_log(s, AV_LOG_ERROR, "time base not set\n");
2874
                return AVERROR(EINVAL);
2875
            }
2876
            if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){
2877
                av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2878
                return AVERROR(EINVAL);
2879
            }
2880
            if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)){
2881
                av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");
2882
                return AVERROR(EINVAL);
2883
            }
2884
            break;
2885
        }
2886

    
2887
        if(s->oformat->codec_tag){
2888
            if(st->codec->codec_tag && st->codec->codec_id == CODEC_ID_RAWVIDEO && av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id) == 0 && !validate_codec_tag(s, st)){
2889
                //the current rawvideo encoding system ends up setting the wrong codec_tag for avi, we override it here
2890
                st->codec->codec_tag= 0;
2891
            }
2892
            if(st->codec->codec_tag){
2893
                if (!validate_codec_tag(s, st)) {
2894
                    char tagbuf[32];
2895
                    av_get_codec_tag_string(tagbuf, sizeof(tagbuf), st->codec->codec_tag);
2896
                    av_log(s, AV_LOG_ERROR,
2897
                           "Tag %s/0x%08x incompatible with output codec id '%d'\n",
2898
                           tagbuf, st->codec->codec_tag, st->codec->codec_id);
2899
                    return AVERROR_INVALIDDATA;
2900
                }
2901
            }else
2902
                st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
2903
        }
2904

    
2905
        if(s->oformat->flags & AVFMT_GLOBALHEADER &&
2906
            !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))
2907
          av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);
2908
    }
2909

    
2910
    if (!s->priv_data && s->oformat->priv_data_size > 0) {
2911
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
2912
        if (!s->priv_data)
2913
            return AVERROR(ENOMEM);
2914
    }
2915

    
2916
#if FF_API_OLD_METADATA
2917
    ff_metadata_mux_compat(s);
2918
#endif
2919

    
2920
    /* set muxer identification string */
2921
    if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
2922
        av_metadata_set2(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
2923
    }
2924

    
2925
    if(s->oformat->write_header){
2926
        ret = s->oformat->write_header(s);
2927
        if (ret < 0)
2928
            return ret;
2929
    }
2930

    
2931
    /* init PTS generation */
2932
    for(i=0;i<s->nb_streams;i++) {
2933
        int64_t den = AV_NOPTS_VALUE;
2934
        st = s->streams[i];
2935

    
2936
        switch (st->codec->codec_type) {
2937
        case AVMEDIA_TYPE_AUDIO:
2938
            den = (int64_t)st->time_base.num * st->codec->sample_rate;
2939
            break;
2940
        case AVMEDIA_TYPE_VIDEO:
2941
            den = (int64_t)st->time_base.num * st->codec->time_base.den;
2942
            break;
2943
        default:
2944
            break;
2945
        }
2946
        if (den != AV_NOPTS_VALUE) {
2947
            if (den <= 0)
2948
                return AVERROR_INVALIDDATA;
2949
            av_frac_init(&st->pts, 0, 0, den);
2950
        }
2951
    }
2952
    return 0;
2953
}
2954

    
2955
//FIXME merge with compute_pkt_fields
2956
static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){
2957
    int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
2958
    int num, den, frame_size, i;
2959

    
2960
    av_dlog(s, "compute_pkt_fields2: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n",
2961
            pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
2962

    
2963
/*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2964
        return AVERROR(EINVAL);*/
2965

    
2966
    /* duration field */
2967
    if (pkt->duration == 0) {
2968
        compute_frame_duration(&num, &den, st, NULL, pkt);
2969
        if (den && num) {
2970
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
2971
        }
2972
    }
2973

    
2974
    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
2975
        pkt->pts= pkt->dts;
2976

    
2977
    //XXX/FIXME this is a temporary hack until all encoders output pts
2978
    if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
2979
        pkt->dts=
2980
//        pkt->pts= st->cur_dts;
2981
        pkt->pts= st->pts.val;
2982
    }
2983

    
2984
    //calculate dts from pts
2985
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
2986
        st->pts_buffer[0]= pkt->pts;
2987
        for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
2988
            st->pts_buffer[i]= pkt->pts + (i-delay-1) * pkt->duration;
2989
        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
2990
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
2991

    
2992
        pkt->dts= st->pts_buffer[0];
2993
    }
2994

    
2995
    if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2996
        av_log(s, AV_LOG_ERROR,
2997
               "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %"PRId64" >= %"PRId64"\n",
2998
               st->index, st->cur_dts, pkt->dts);
2999
        return AVERROR(EINVAL);
3000
    }
3001
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
3002
        av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
3003
        return AVERROR(EINVAL);
3004
    }
3005

    
3006
//    av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
3007
    st->cur_dts= pkt->dts;
3008
    st->pts.val= pkt->dts;
3009

    
3010
    /* update pts */
3011
    switch (st->codec->codec_type) {
3012
    case AVMEDIA_TYPE_AUDIO:
3013
        frame_size = get_audio_frame_size(st->codec, pkt->size);
3014

    
3015
        /* HACK/FIXME, we skip the initial 0 size packets as they are most
3016
           likely equal to the encoder delay, but it would be better if we
3017
           had the real timestamps from the encoder */
3018
        if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
3019
            av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
3020
        }
3021
        break;
3022
    case AVMEDIA_TYPE_VIDEO:
3023
        av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
3024
        break;
3025
    default:
3026
        break;
3027
    }
3028
    return 0;
3029
}
3030

    
3031
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
3032
{
3033
    int ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
3034

    
3035
    if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3036
        return ret;
3037

    
3038
    ret= s->oformat->write_packet(s, pkt);
3039
    if(!ret)
3040
        ret= url_ferror(s->pb);
3041
    return ret;
3042
}
3043

    
3044
void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
3045
                              int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
3046
{
3047
    AVPacketList **next_point, *this_pktl;
3048

    
3049
    this_pktl = av_mallocz(sizeof(AVPacketList));
3050
    this_pktl->pkt= *pkt;
3051
    pkt->destruct= NULL;             // do not free original but only the copy
3052
    av_dup_packet(&this_pktl->pkt);  // duplicate the packet if it uses non-alloced memory
3053

    
3054
    if(s->streams[pkt->stream_index]->last_in_packet_buffer){
3055
        next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
3056
    }else
3057
        next_point = &s->packet_buffer;
3058

    
3059
    if(*next_point){
3060
        if(compare(s, &s->packet_buffer_end->pkt, pkt)){
3061
            while(!compare(s, &(*next_point)->pkt, pkt)){
3062
                next_point= &(*next_point)->next;
3063
            }
3064
            goto next_non_null;
3065
        }else{
3066
            next_point = &(s->packet_buffer_end->next);
3067
        }
3068
    }
3069
    assert(!*next_point);
3070

    
3071
    s->packet_buffer_end= this_pktl;
3072
next_non_null:
3073

    
3074
    this_pktl->next= *next_point;
3075

    
3076
    s->streams[pkt->stream_index]->last_in_packet_buffer=
3077
    *next_point= this_pktl;
3078
}
3079

    
3080
static int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
3081
{
3082
    AVStream *st = s->streams[ pkt ->stream_index];
3083
    AVStream *st2= s->streams[ next->stream_index];
3084
    int64_t a= st2->time_base.num * (int64_t)st ->time_base.den;
3085
    int64_t b= st ->time_base.num * (int64_t)st2->time_base.den;
3086
    return av_rescale_rnd(pkt->dts, b, a, AV_ROUND_DOWN) < next->dts;
3087
}
3088

    
3089
int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
3090
    AVPacketList *pktl;
3091
    int stream_count=0;
3092
    int i;
3093

    
3094
    if(pkt){
3095
        ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
3096
    }
3097

    
3098
    for(i=0; i < s->nb_streams; i++)
3099
        stream_count+= !!s->streams[i]->last_in_packet_buffer;
3100

    
3101
    if(stream_count && (s->nb_streams == stream_count || flush)){
3102
        pktl= s->packet_buffer;
3103
        *out= pktl->pkt;
3104

    
3105
        s->packet_buffer= pktl->next;
3106
        if(!s->packet_buffer)
3107
            s->packet_buffer_end= NULL;
3108

    
3109
        if(s->streams[out->stream_index]->last_in_packet_buffer == pktl)
3110
            s->streams[out->stream_index]->last_in_packet_buffer= NULL;
3111
        av_freep(&pktl);
3112
        return 1;
3113
    }else{
3114
        av_init_packet(out);
3115
        return 0;
3116
    }
3117
}
3118

    
3119
/**
3120
 * Interleave an AVPacket correctly so it can be muxed.
3121
 * @param out the interleaved packet will be output here
3122
 * @param in the input packet
3123
 * @param flush 1 if no further packets are available as input and all
3124
 *              remaining packets should be output
3125
 * @return 1 if a packet was output, 0 if no packet could be output,
3126
 *         < 0 if an error occurred
3127
 */
3128
static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
3129
    if(s->oformat->interleave_packet)
3130
        return s->oformat->interleave_packet(s, out, in, flush);
3131
    else
3132
        return av_interleave_packet_per_dts(s, out, in, flush);
3133
}
3134

    
3135
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
3136
    AVStream *st= s->streams[ pkt->stream_index];
3137
    int ret;
3138

    
3139
    //FIXME/XXX/HACK drop zero sized packets
3140
    if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size==0)
3141
        return 0;
3142

    
3143
    av_dlog(s, "av_interleaved_write_frame size:%d dts:%"PRId64" pts:%"PRId64"\n",
3144
            pkt->size, pkt->dts, pkt->pts);
3145
    if((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3146
        return ret;
3147

    
3148
    if(pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3149
        return AVERROR(EINVAL);
3150

    
3151
    for(;;){
3152
        AVPacket opkt;
3153
        int ret= av_interleave_packet(s, &opkt, pkt, 0);
3154
        if(ret<=0) //FIXME cleanup needed for ret<0 ?
3155
            return ret;
3156

    
3157
        ret= s->oformat->write_packet(s, &opkt);
3158

    
3159
        av_free_packet(&opkt);
3160
        pkt= NULL;
3161

    
3162
        if(ret<0)
3163
            return ret;
3164
        if(url_ferror(s->pb))
3165
            return url_ferror(s->pb);
3166
    }
3167
}
3168

    
3169
int av_write_trailer(AVFormatContext *s)
3170
{
3171
    int ret, i;
3172

    
3173
    for(;;){
3174
        AVPacket pkt;
3175
        ret= av_interleave_packet(s, &pkt, NULL, 1);
3176
        if(ret<0) //FIXME cleanup needed for ret<0 ?
3177
            goto fail;
3178
        if(!ret)
3179
            break;
3180

    
3181
        ret= s->oformat->write_packet(s, &pkt);
3182

    
3183
        av_free_packet(&pkt);
3184

    
3185
        if(ret<0)
3186
            goto fail;
3187
        if(url_ferror(s->pb))
3188
            goto fail;
3189
    }
3190

    
3191
    if(s->oformat->write_trailer)
3192
        ret = s->oformat->write_trailer(s);
3193
fail:
3194
    if(ret == 0)
3195
       ret=url_ferror(s->pb);
3196
    for(i=0;i<s->nb_streams;i++) {
3197
        av_freep(&s->streams[i]->priv_data);
3198
        av_freep(&s->streams[i]->index_entries);
3199
    }
3200
    av_freep(&s->priv_data);
3201
    return ret;
3202
}
3203

    
3204
void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
3205
{
3206
    int i, j;
3207
    AVProgram *program=NULL;
3208
    void *tmp;
3209

    
3210
    if (idx >= ac->nb_streams) {
3211
        av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
3212
        return;
3213
    }
3214

    
3215
    for(i=0; i<ac->nb_programs; i++){
3216
        if(ac->programs[i]->id != progid)
3217
            continue;
3218
        program = ac->programs[i];
3219
        for(j=0; j<program->nb_stream_indexes; j++)
3220
            if(program->stream_index[j] == idx)
3221
                return;
3222

    
3223
        tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
3224
        if(!tmp)
3225
            return;
3226
        program->stream_index = tmp;
3227
        program->stream_index[program->nb_stream_indexes++] = idx;
3228
        return;
3229
    }
3230
}
3231

    
3232
static void print_fps(double d, const char *postfix){
3233
    uint64_t v= lrintf(d*100);
3234
    if     (v% 100      ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
3235
    else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
3236
    else                  av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
3237
}
3238

    
3239
static void dump_metadata(void *ctx, AVMetadata *m, const char *indent)
3240
{
3241
    if(m && !(m->count == 1 && av_metadata_get(m, "language", NULL, 0))){
3242
        AVMetadataTag *tag=NULL;
3243

    
3244
        av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
3245
        while((tag=av_metadata_get(m, "", tag, AV_METADATA_IGNORE_SUFFIX))) {
3246
            if(strcmp("language", tag->key))
3247
                av_log(ctx, AV_LOG_INFO, "%s  %-16s: %s\n", indent, tag->key, tag->value);
3248
        }
3249
    }
3250
}
3251

    
3252
/* "user interface" functions */
3253
static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
3254
{
3255
    char buf[256];
3256
    int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
3257
    AVStream *st = ic->streams[i];
3258
    int g = av_gcd(st->time_base.num, st->time_base.den);
3259
    AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL, 0);
3260
    avcodec_string(buf, sizeof(buf), st->codec, is_output);
3261
    av_log(NULL, AV_LOG_INFO, "    Stream #%d.%d", index, i);
3262
    /* the pid is an important information, so we display it */
3263
    /* XXX: add a generic system */
3264
    if (flags & AVFMT_SHOW_IDS)
3265
        av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
3266
    if (lang)
3267
        av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
3268
    av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
3269
    av_log(NULL, AV_LOG_INFO, ": %s", buf);
3270
    if (st->sample_aspect_ratio.num && // default
3271
        av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
3272
        AVRational display_aspect_ratio;
3273
        av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
3274
                  st->codec->width*st->sample_aspect_ratio.num,
3275
                  st->codec->height*st->sample_aspect_ratio.den,
3276
                  1024*1024);
3277
        av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
3278
                 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
3279
                 display_aspect_ratio.num, display_aspect_ratio.den);
3280
    }
3281
    if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
3282
        if(st->avg_frame_rate.den && st->avg_frame_rate.num)
3283
            print_fps(av_q2d(st->avg_frame_rate), "fps");
3284
        if(st->r_frame_rate.den && st->r_frame_rate.num)
3285
            print_fps(av_q2d(st->r_frame_rate), "tbr");
3286
        if(st->time_base.den && st->time_base.num)
3287
            print_fps(1/av_q2d(st->time_base), "tbn");
3288
        if(st->codec->time_base.den && st->codec->time_base.num)
3289
            print_fps(1/av_q2d(st->codec->time_base), "tbc");
3290
    }
3291
    if (st->disposition & AV_DISPOSITION_DEFAULT)
3292
        av_log(NULL, AV_LOG_INFO, " (default)");
3293
    if (st->disposition & AV_DISPOSITION_DUB)
3294
        av_log(NULL, AV_LOG_INFO, " (dub)");
3295
    if (st->disposition & AV_DISPOSITION_ORIGINAL)
3296
        av_log(NULL, AV_LOG_INFO, " (original)");
3297
    if (st->disposition & AV_DISPOSITION_COMMENT)
3298
        av_log(NULL, AV_LOG_INFO, " (comment)");
3299
    if (st->disposition & AV_DISPOSITION_LYRICS)
3300
        av_log(NULL, AV_LOG_INFO, " (lyrics)");
3301
    if (st->disposition & AV_DISPOSITION_KARAOKE)
3302
        av_log(NULL, AV_LOG_INFO, " (karaoke)");
3303
    if (st->disposition & AV_DISPOSITION_FORCED)
3304
        av_log(NULL, AV_LOG_INFO, " (forced)");
3305
    if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
3306
        av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
3307
    if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
3308
        av_log(NULL, AV_LOG_INFO, " (visual impaired)");
3309
    if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
3310
        av_log(NULL, AV_LOG_INFO, " (clean effects)");
3311
    av_log(NULL, AV_LOG_INFO, "\n");
3312
    dump_metadata(NULL, st->metadata, "    ");
3313
}
3314

    
3315
#if FF_API_DUMP_FORMAT
3316
void dump_format(AVFormatContext *ic,
3317
                 int index,
3318
                 const char *url,
3319
                 int is_output)
3320
{
3321
    av_dump_format(ic, index, url, is_output);
3322
}
3323
#endif
3324

    
3325
void av_dump_format(AVFormatContext *ic,
3326
                    int index,
3327
                    const char *url,
3328
                    int is_output)
3329
{
3330
    int i;
3331
    uint8_t *printed = av_mallocz(ic->nb_streams);
3332
    if (ic->nb_streams && !printed)
3333
        return;
3334

    
3335
    av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
3336
            is_output ? "Output" : "Input",
3337
            index,
3338
            is_output ? ic->oformat->name : ic->iformat->name,
3339
            is_output ? "to" : "from", url);
3340
    dump_metadata(NULL, ic->metadata, "  ");
3341
    if (!is_output) {
3342
        av_log(NULL, AV_LOG_INFO, "  Duration: ");
3343
        if (ic->duration != AV_NOPTS_VALUE) {
3344
            int hours, mins, secs, us;
3345
            secs = ic->duration / AV_TIME_BASE;
3346
            us = ic->duration % AV_TIME_BASE;
3347
            mins = secs / 60;
3348
            secs %= 60;
3349
            hours = mins / 60;
3350
            mins %= 60;
3351
            av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
3352
                   (100 * us) / AV_TIME_BASE);
3353
        } else {
3354
            av_log(NULL, AV_LOG_INFO, "N/A");
3355
        }
3356
        if (ic->start_time != AV_NOPTS_VALUE) {
3357
            int secs, us;
3358
            av_log(NULL, AV_LOG_INFO, ", start: ");
3359
            secs = ic->start_time / AV_TIME_BASE;
3360
            us = abs(ic->start_time % AV_TIME_BASE);
3361
            av_log(NULL, AV_LOG_INFO, "%d.%06d",
3362
                   secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
3363
        }
3364
        av_log(NULL, AV_LOG_INFO, ", bitrate: ");
3365
        if (ic->bit_rate) {
3366
            av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
3367
        } else {
3368
            av_log(NULL, AV_LOG_INFO, "N/A");
3369
        }
3370
        av_log(NULL, AV_LOG_INFO, "\n");
3371
    }
3372
    for (i = 0; i < ic->nb_chapters; i++) {
3373
        AVChapter *ch = ic->chapters[i];
3374
        av_log(NULL, AV_LOG_INFO, "    Chapter #%d.%d: ", index, i);
3375
        av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
3376
        av_log(NULL, AV_LOG_INFO, "end %f\n",   ch->end   * av_q2d(ch->time_base));
3377

    
3378
        dump_metadata(NULL, ch->metadata, "    ");
3379
    }
3380
    if(ic->nb_programs) {
3381
        int j, k, total = 0;
3382
        for(j=0; j<ic->nb_programs; j++) {
3383
            AVMetadataTag *name = av_metadata_get(ic->programs[j]->metadata,
3384
                                                  "name", NULL, 0);
3385
            av_log(NULL, AV_LOG_INFO, "  Program %d %s\n", ic->programs[j]->id,
3386
                   name ? name->value : "");
3387
            dump_metadata(NULL, ic->programs[j]->metadata, "    ");
3388
            for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
3389
                dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
3390
                printed[ic->programs[j]->stream_index[k]] = 1;
3391
            }
3392
            total += ic->programs[j]->nb_stream_indexes;
3393
        }
3394
        if (total < ic->nb_streams)
3395
            av_log(NULL, AV_LOG_INFO, "  No Program\n");
3396
    }
3397
    for(i=0;i<ic->nb_streams;i++)
3398
        if (!printed[i])
3399
            dump_stream_format(ic, i, index, is_output);
3400

    
3401
    av_free(printed);
3402
}
3403

    
3404
#if FF_API_PARSE_FRAME_PARAM
3405
#include "libavutil/parseutils.h"
3406

    
3407
int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
3408
{
3409
    return av_parse_video_size(width_ptr, height_ptr, str);
3410
}
3411

    
3412
int parse_frame_rate(int *frame_rate_num, int *frame_rate_den, const char *arg)
3413
{
3414
    AVRational frame_rate;
3415
    int ret = av_parse_video_rate(&frame_rate, arg);
3416
    *frame_rate_num= frame_rate.num;
3417
    *frame_rate_den= frame_rate.den;
3418
    return ret;
3419
}
3420
#endif
3421

    
3422
int64_t av_gettime(void)
3423
{
3424
    struct timeval tv;
3425
    gettimeofday(&tv,NULL);
3426
    return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
3427
}
3428

    
3429
uint64_t ff_ntp_time(void)
3430
{
3431
  return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
3432
}
3433

    
3434
#if FF_API_PARSE_DATE
3435
#include "libavutil/parseutils.h"
3436

    
3437
int64_t parse_date(const char *timestr, int duration)
3438
{
3439
    int64_t timeval;
3440
    av_parse_time(&timeval, timestr, duration);
3441
    return timeval;
3442
}
3443
#endif
3444

    
3445
#if FF_API_FIND_INFO_TAG
3446
#include "libavutil/parseutils.h"
3447

    
3448
int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
3449
{
3450
    return av_find_info_tag(arg, arg_size, tag1, info);
3451
}
3452
#endif
3453

    
3454
int av_get_frame_filename(char *buf, int buf_size,
3455
                          const char *path, int number)
3456
{
3457
    const char *p;
3458
    char *q, buf1[20], c;
3459
    int nd, len, percentd_found;
3460

    
3461
    q = buf;
3462
    p = path;
3463
    percentd_found = 0;
3464
    for(;;) {
3465
        c = *p++;
3466
        if (c == '\0')
3467
            break;
3468
        if (c == '%') {
3469
            do {
3470
                nd = 0;
3471
                while (isdigit(*p)) {
3472
                    nd = nd * 10 + *p++ - '0';
3473
                }
3474
                c = *p++;
3475
            } while (isdigit(c));
3476

    
3477
            switch(c) {
3478
            case '%':
3479
                goto addchar;
3480
            case 'd':
3481
                if (percentd_found)
3482
                    goto fail;
3483
                percentd_found = 1;
3484
                snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3485
                len = strlen(buf1);
3486
                if ((q - buf + len) > buf_size - 1)
3487
                    goto fail;
3488
                memcpy(q, buf1, len);
3489
                q += len;
3490
                break;
3491
            default:
3492
                goto fail;
3493
            }
3494
        } else {
3495
        addchar:
3496
            if ((q - buf) < buf_size - 1)
3497
                *q++ = c;
3498
        }
3499
    }
3500
    if (!percentd_found)
3501
        goto fail;
3502
    *q = '\0';
3503
    return 0;
3504
 fail:
3505
    *q = '\0';
3506
    return -1;
3507
}
3508

    
3509
static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
3510
{
3511
    int len, i, j, c;
3512
#undef fprintf
3513
#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3514

    
3515
    for(i=0;i<size;i+=16) {
3516
        len = size - i;
3517
        if (len > 16)
3518
            len = 16;
3519
        PRINT("%08x ", i);
3520
        for(j=0;j<16;j++) {
3521
            if (j < len)
3522
                PRINT(" %02x", buf[i+j]);
3523
            else
3524
                PRINT("   ");
3525
        }
3526
        PRINT(" ");
3527
        for(j=0;j<len;j++) {
3528
            c = buf[i+j];
3529
            if (c < ' ' || c > '~')
3530
                c = '.';
3531
            PRINT("%c", c);
3532
        }
3533
        PRINT("\n");
3534
    }
3535
#undef PRINT
3536
}
3537

    
3538
void av_hex_dump(FILE *f, uint8_t *buf, int size)
3539
{
3540
    hex_dump_internal(NULL, f, 0, buf, size);
3541
}
3542

    
3543
void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
3544
{
3545
    hex_dump_internal(avcl, NULL, level, buf, size);
3546
}
3547

    
3548
static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
3549
{
3550
#undef fprintf
3551
#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3552
    PRINT("stream #%d:\n", pkt->stream_index);
3553
    PRINT("  keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
3554
    PRINT("  duration=%0.3f\n", pkt->duration * av_q2d(time_base));
3555
    /* DTS is _always_ valid after av_read_frame() */
3556
    PRINT("  dts=");
3557
    if (pkt->dts == AV_NOPTS_VALUE)
3558
        PRINT("N/A");
3559
    else
3560
        PRINT("%0.3f", pkt->dts * av_q2d(time_base));
3561
    /* PTS may not be known if B-frames are present. */
3562
    PRINT("  pts=");
3563
    if (pkt->pts == AV_NOPTS_VALUE)
3564
        PRINT("N/A");
3565
    else
3566
        PRINT("%0.3f", pkt->pts * av_q2d(time_base));
3567
    PRINT("\n");
3568
    PRINT("  size=%d\n", pkt->size);
3569
#undef PRINT
3570
    if (dump_payload)
3571
        av_hex_dump(f, pkt->data, pkt->size);
3572
}
3573

    
3574
void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3575
{
3576
    AVRational tb = { 1, AV_TIME_BASE };
3577
    pkt_dump_internal(NULL, f, 0, pkt, dump_payload, tb);
3578
}
3579

    
3580
void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
3581
{
3582
    pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
3583
}
3584

    
3585
void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
3586
{
3587
    AVRational tb = { 1, AV_TIME_BASE };
3588
    pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, tb);
3589
}
3590

    
3591
void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
3592
                      AVStream *st)
3593
{
3594
    pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
3595
}
3596

    
3597
#if FF_API_URL_SPLIT
3598
attribute_deprecated
3599
void ff_url_split(char *proto, int proto_size,
3600
                  char *authorization, int authorization_size,
3601
                  char *hostname, int hostname_size,
3602
                  int *port_ptr,
3603
                  char *path, int path_size,
3604
                  const char *url)
3605
{
3606
    av_url_split(proto, proto_size,
3607
                 authorization, authorization_size,
3608
                 hostname, hostname_size,
3609
                 port_ptr,
3610
                 path, path_size,
3611
                 url);
3612
}
3613
#endif
3614

    
3615
void av_url_split(char *proto, int proto_size,
3616
                  char *authorization, int authorization_size,
3617
                  char *hostname, int hostname_size,
3618
                  int *port_ptr,
3619
                  char *path, int path_size,
3620
                  const char *url)
3621
{
3622
    const char *p, *ls, *at, *col, *brk;
3623

    
3624
    if (port_ptr)               *port_ptr = -1;
3625
    if (proto_size > 0)         proto[0] = 0;
3626
    if (authorization_size > 0) authorization[0] = 0;
3627
    if (hostname_size > 0)      hostname[0] = 0;
3628
    if (path_size > 0)          path[0] = 0;
3629

    
3630
    /* parse protocol */
3631
    if ((p = strchr(url, ':'))) {
3632
        av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3633
        p++; /* skip ':' */
3634
        if (*p == '/') p++;
3635
        if (*p == '/') p++;
3636
    } else {
3637
        /* no protocol means plain filename */
3638
        av_strlcpy(path, url, path_size);
3639
        return;
3640
    }
3641

    
3642
    /* separate path from hostname */
3643
    ls = strchr(p, '/');
3644
    if(!ls)
3645
        ls = strchr(p, '?');
3646
    if(ls)
3647
        av_strlcpy(path, ls, path_size);
3648
    else
3649
        ls = &p[strlen(p)]; // XXX
3650

    
3651
    /* the rest is hostname, use that to parse auth/port */
3652
    if (ls != p) {
3653
        /* authorization (user[:pass]@hostname) */
3654
        if ((at = strchr(p, '@')) && at < ls) {
3655
            av_strlcpy(authorization, p,
3656
                       FFMIN(authorization_size, at + 1 - p));
3657
            p = at + 1; /* skip '@' */
3658
        }
3659

    
3660
        if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3661
            /* [host]:port */
3662
            av_strlcpy(hostname, p + 1,
3663
                       FFMIN(hostname_size, brk - p));
3664
            if (brk[1] == ':' && port_ptr)
3665
                *port_ptr = atoi(brk + 2);
3666
        } else if ((col = strchr(p, ':')) && col < ls) {
3667
            av_strlcpy(hostname, p,
3668
                       FFMIN(col + 1 - p, hostname_size));
3669
            if (port_ptr) *port_ptr = atoi(col + 1);
3670
        } else
3671
            av_strlcpy(hostname, p,
3672
                       FFMIN(ls + 1 - p, hostname_size));
3673
    }
3674
}
3675

    
3676
char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3677
{
3678
    int i;
3679
    static const char hex_table_uc[16] = { '0', '1', '2', '3',
3680
                                           '4', '5', '6', '7',
3681
                                           '8', '9', 'A', 'B',
3682
                                           'C', 'D', 'E', 'F' };
3683
    static const char hex_table_lc[16] = { '0', '1', '2', '3',
3684
                                           '4', '5', '6', '7',
3685
                                           '8', '9', 'a', 'b',
3686
                                           'c', 'd', 'e', 'f' };
3687
    const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3688

    
3689
    for(i = 0; i < s; i++) {
3690
        buff[i * 2]     = hex_table[src[i] >> 4];
3691
        buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3692
    }
3693

    
3694
    return buff;
3695
}
3696

    
3697
int ff_hex_to_data(uint8_t *data, const char *p)
3698
{
3699
    int c, len, v;
3700

    
3701
    len = 0;
3702
    v = 1;
3703
    for (;;) {
3704
        p += strspn(p, SPACE_CHARS);
3705
        if (*p == '\0')
3706
            break;
3707
        c = toupper((unsigned char) *p++);
3708
        if (c >= '0' && c <= '9')
3709
            c = c - '0';
3710
        else if (c >= 'A' && c <= 'F')
3711
            c = c - 'A' + 10;
3712
        else
3713
            break;
3714
        v = (v << 4) | c;
3715
        if (v & 0x100) {
3716
            if (data)
3717
                data[len] = v;
3718
            len++;
3719
            v = 1;
3720
        }
3721
    }
3722
    return len;
3723
}
3724

    
3725
void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3726
                     unsigned int pts_num, unsigned int pts_den)
3727
{
3728
    AVRational new_tb;
3729
    if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
3730
        if(new_tb.num != pts_num)
3731
            av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
3732
    }else
3733
        av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3734

    
3735
    if(new_tb.num <= 0 || new_tb.den <= 0) {
3736
        av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
3737
        return;
3738
    }
3739
    s->time_base = new_tb;
3740
    s->pts_wrap_bits = pts_wrap_bits;
3741
}
3742

    
3743
int ff_url_join(char *str, int size, const char *proto,
3744
                const char *authorization, const char *hostname,
3745
                int port, const char *fmt, ...)
3746
{
3747
#if CONFIG_NETWORK
3748
    struct addrinfo hints, *ai;
3749
#endif
3750

    
3751
    str[0] = '\0';
3752
    if (proto)
3753
        av_strlcatf(str, size, "%s://", proto);
3754
    if (authorization && authorization[0])
3755
        av_strlcatf(str, size, "%s@", authorization);
3756
#if CONFIG_NETWORK && defined(AF_INET6)
3757
    /* Determine if hostname is a numerical IPv6 address,
3758
     * properly escape it within [] in that case. */
3759
    memset(&hints, 0, sizeof(hints));
3760
    hints.ai_flags = AI_NUMERICHOST;
3761
    if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
3762
        if (ai->ai_family == AF_INET6) {
3763
            av_strlcat(str, "[", size);
3764
            av_strlcat(str, hostname, size);
3765
            av_strlcat(str, "]", size);
3766
        } else {
3767
            av_strlcat(str, hostname, size);
3768
        }
3769
        freeaddrinfo(ai);
3770
    } else
3771
#endif
3772
        /* Not an IPv6 address, just output the plain string. */
3773
        av_strlcat(str, hostname, size);
3774

    
3775
    if (port >= 0)
3776
        av_strlcatf(str, size, ":%d", port);
3777
    if (fmt) {
3778
        va_list vl;
3779
        int len = strlen(str);
3780

    
3781
        va_start(vl, fmt);
3782
        vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
3783
        va_end(vl);
3784
    }
3785
    return strlen(str);
3786
}
3787

    
3788
int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
3789
                     AVFormatContext *src)
3790
{
3791
    AVPacket local_pkt;
3792

    
3793
    local_pkt = *pkt;
3794
    local_pkt.stream_index = dst_stream;
3795
    if (pkt->pts != AV_NOPTS_VALUE)
3796
        local_pkt.pts = av_rescale_q(pkt->pts,
3797
                                     src->streams[pkt->stream_index]->time_base,
3798
                                     dst->streams[dst_stream]->time_base);
3799
    if (pkt->dts != AV_NOPTS_VALUE)
3800
        local_pkt.dts = av_rescale_q(pkt->dts,
3801
                                     src->streams[pkt->stream_index]->time_base,
3802
                                     dst->streams[dst_stream]->time_base);
3803
    return av_write_frame(dst, &local_pkt);
3804
}
3805

    
3806
void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3807
                        void *context)
3808
{
3809
    const char *ptr = str;
3810

    
3811
    /* Parse key=value pairs. */
3812
    for (;;) {
3813
        const char *key;
3814
        char *dest = NULL, *dest_end;
3815
        int key_len, dest_len = 0;
3816

    
3817
        /* Skip whitespace and potential commas. */
3818
        while (*ptr && (isspace(*ptr) || *ptr == ','))
3819
            ptr++;
3820
        if (!*ptr)
3821
            break;
3822

    
3823
        key = ptr;
3824

    
3825
        if (!(ptr = strchr(key, '=')))
3826
            break;
3827
        ptr++;
3828
        key_len = ptr - key;
3829

    
3830
        callback_get_buf(context, key, key_len, &dest, &dest_len);
3831
        dest_end = dest + dest_len - 1;
3832

    
3833
        if (*ptr == '\"') {
3834
            ptr++;
3835
            while (*ptr && *ptr != '\"') {
3836
                if (*ptr == '\\') {
3837
                    if (!ptr[1])
3838
                        break;
3839
                    if (dest && dest < dest_end)
3840
                        *dest++ = ptr[1];
3841
                    ptr += 2;
3842
                } else {
3843
                    if (dest && dest < dest_end)
3844
                        *dest++ = *ptr;
3845
                    ptr++;
3846
                }
3847
            }
3848
            if (*ptr == '\"')
3849
                ptr++;
3850
        } else {
3851
            for (; *ptr && !(isspace(*ptr) || *ptr == ','); ptr++)
3852
                if (dest && dest < dest_end)
3853
                    *dest++ = *ptr;
3854
        }
3855
        if (dest)
3856
            *dest = 0;
3857
    }
3858
}
3859

    
3860
int ff_find_stream_index(AVFormatContext *s, int id)
3861
{
3862
    int i;
3863
    for (i = 0; i < s->nb_streams; i++) {
3864
        if (s->streams[i]->id == id)
3865
            return i;
3866
    }
3867
    return -1;
3868
}
3869

    
3870
void ff_make_absolute_url(char *buf, int size, const char *base,
3871
                          const char *rel)
3872
{
3873
    char *sep;
3874
    /* Absolute path, relative to the current server */
3875
    if (base && strstr(base, "://") && rel[0] == '/') {
3876
        if (base != buf)
3877
            av_strlcpy(buf, base, size);
3878
        sep = strstr(buf, "://");
3879
        if (sep) {
3880
            sep += 3;
3881
            sep = strchr(sep, '/');
3882
            if (sep)
3883
                *sep = '\0';
3884
        }
3885
        av_strlcat(buf, rel, size);
3886
        return;
3887
    }
3888
    /* If rel actually is an absolute url, just copy it */
3889
    if (!base || strstr(rel, "://") || rel[0] == '/') {
3890
        av_strlcpy(buf, rel, size);
3891
        return;
3892
    }
3893
    if (base != buf)
3894
        av_strlcpy(buf, base, size);
3895
    /* Remove the file name from the base url */
3896
    sep = strrchr(buf, '/');
3897
    if (sep)
3898
        sep[1] = '\0';
3899
    else
3900
        buf[0] = '\0';
3901
    while (av_strstart(rel, "../", NULL) && sep) {
3902
        /* Remove the path delimiter at the end */
3903
        sep[0] = '\0';
3904
        sep = strrchr(buf, '/');
3905
        /* If the next directory name to pop off is "..", break here */
3906
        if (!strcmp(sep ? &sep[1] : buf, "..")) {
3907
            /* Readd the slash we just removed */
3908
            av_strlcat(buf, "/", size);
3909
            break;
3910
        }
3911
        /* Cut off the directory name */
3912
        if (sep)
3913
            sep[1] = '\0';
3914
        else
3915
            buf[0] = '\0';
3916
        rel += 3;
3917
    }
3918
    av_strlcat(buf, rel, size);
3919
}