Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ 58d5ff0a

History | View | Annotate | Download (122 KB)

1
/*
2
 * various utility functions for use within Libav
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4
 *
5
 * This file is part of Libav.
6
 *
7
 * Libav 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
 * Libav 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 Libav; 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 "libavutil/opt.h"
29
#include "metadata.h"
30
#include "id3v2.h"
31
#include "libavutil/avstring.h"
32
#include "riff.h"
33
#include "audiointerleave.h"
34
#include "url.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 Libav
49
 */
50

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

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

    
61
const char *avformat_license(void)
62
{
63
#define LICENSE_PREFIX "libavformat license: "
64
    return LICENSE_PREFIX LIBAV_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
AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
204
                                const char *mime_type)
205
{
206
    AVOutputFormat *fmt = NULL, *fmt_found;
207
    int score_max, score;
208

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

    
238
enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
239
                            const char *filename, const char *mime_type, enum AVMediaType type){
240
    if(type == AVMEDIA_TYPE_VIDEO){
241
        enum CodecID codec_id= CODEC_ID_NONE;
242

    
243
#if CONFIG_IMAGE2_MUXER
244
        if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
245
            codec_id= ff_guess_image2_codec(filename);
246
        }
247
#endif
248
        if(codec_id == CODEC_ID_NONE)
249
            codec_id= fmt->video_codec;
250
        return codec_id;
251
    }else if(type == AVMEDIA_TYPE_AUDIO)
252
        return fmt->audio_codec;
253
    else if (type == AVMEDIA_TYPE_SUBTITLE)
254
        return fmt->subtitle_codec;
255
    else
256
        return CODEC_ID_NONE;
257
}
258

    
259
AVInputFormat *av_find_input_format(const char *short_name)
260
{
261
    AVInputFormat *fmt = NULL;
262
    while ((fmt = av_iformat_next(fmt))) {
263
        if (match_format(short_name, fmt->name))
264
            return fmt;
265
    }
266
    return NULL;
267
}
268

    
269
#if FF_API_SYMVER && CONFIG_SHARED && HAVE_SYMVER
270
FF_SYMVER(void, av_destruct_packet_nofree, (AVPacket *pkt), "LIBAVFORMAT_52")
271
{
272
    av_destruct_packet_nofree(pkt);
273
}
274

    
275
FF_SYMVER(void, av_destruct_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
276
{
277
    av_destruct_packet(pkt);
278
}
279

    
280
FF_SYMVER(int, av_new_packet, (AVPacket *pkt, int size), "LIBAVFORMAT_52")
281
{
282
    return av_new_packet(pkt, size);
283
}
284

    
285
FF_SYMVER(int, av_dup_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
286
{
287
    return av_dup_packet(pkt);
288
}
289

    
290
FF_SYMVER(void, av_free_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
291
{
292
    av_free_packet(pkt);
293
}
294

    
295
FF_SYMVER(void, av_init_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
296
{
297
    av_log(NULL, AV_LOG_WARNING, "Diverting av_*_packet function calls to libavcodec. Recompile to improve performance\n");
298
    av_init_packet(pkt);
299
}
300
#endif
301

    
302
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
303
{
304
    int ret= av_new_packet(pkt, size);
305

    
306
    if(ret<0)
307
        return ret;
308

    
309
    pkt->pos= avio_tell(s);
310

    
311
    ret= avio_read(s, pkt->data, size);
312
    if(ret<=0)
313
        av_free_packet(pkt);
314
    else
315
        av_shrink_packet(pkt, ret);
316

    
317
    return ret;
318
}
319

    
320
int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
321
{
322
    int ret;
323
    int old_size;
324
    if (!pkt->size)
325
        return av_get_packet(s, pkt, size);
326
    old_size = pkt->size;
327
    ret = av_grow_packet(pkt, size);
328
    if (ret < 0)
329
        return ret;
330
    ret = avio_read(s, pkt->data + old_size, size);
331
    av_shrink_packet(pkt, old_size + FFMAX(ret, 0));
332
    return ret;
333
}
334

    
335

    
336
int av_filename_number_test(const char *filename)
337
{
338
    char buf[1024];
339
    return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
340
}
341

    
342
AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
343
{
344
    AVProbeData lpd = *pd;
345
    AVInputFormat *fmt1 = NULL, *fmt;
346
    int score, id3 = 0;
347

    
348
    if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
349
        int id3len = ff_id3v2_tag_len(lpd.buf);
350
        if (lpd.buf_size > id3len + 16) {
351
            lpd.buf += id3len;
352
            lpd.buf_size -= id3len;
353
        }
354
        id3 = 1;
355
    }
356

    
357
    fmt = NULL;
358
    while ((fmt1 = av_iformat_next(fmt1))) {
359
        if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
360
            continue;
361
        score = 0;
362
        if (fmt1->read_probe) {
363
            score = fmt1->read_probe(&lpd);
364
        } else if (fmt1->extensions) {
365
            if (av_match_ext(lpd.filename, fmt1->extensions)) {
366
                score = 50;
367
            }
368
        }
369
        if (score > *score_max) {
370
            *score_max = score;
371
            fmt = fmt1;
372
        }else if (score == *score_max)
373
            fmt = NULL;
374
    }
375

    
376
    /* a hack for files with huge id3v2 tags -- try to guess by file extension. */
377
    if (!fmt && id3 && *score_max < AVPROBE_SCORE_MAX/4) {
378
        while ((fmt = av_iformat_next(fmt)))
379
            if (fmt->extensions && av_match_ext(lpd.filename, fmt->extensions)) {
380
                *score_max = AVPROBE_SCORE_MAX/4;
381
                break;
382
            }
383
    }
384

    
385
    return fmt;
386
}
387

    
388
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
389
    int score=0;
390
    return av_probe_input_format2(pd, is_opened, &score);
391
}
392

    
393
static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
394
{
395
    static const struct {
396
        const char *name; enum CodecID id; enum AVMediaType type;
397
    } fmt_id_type[] = {
398
        { "aac"      , CODEC_ID_AAC       , AVMEDIA_TYPE_AUDIO },
399
        { "ac3"      , CODEC_ID_AC3       , AVMEDIA_TYPE_AUDIO },
400
        { "dts"      , CODEC_ID_DTS       , AVMEDIA_TYPE_AUDIO },
401
        { "eac3"     , CODEC_ID_EAC3      , AVMEDIA_TYPE_AUDIO },
402
        { "h264"     , CODEC_ID_H264      , AVMEDIA_TYPE_VIDEO },
403
        { "m4v"      , CODEC_ID_MPEG4     , AVMEDIA_TYPE_VIDEO },
404
        { "mp3"      , CODEC_ID_MP3       , AVMEDIA_TYPE_AUDIO },
405
        { "mpegvideo", CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
406
        { 0 }
407
    };
408
    AVInputFormat *fmt = av_probe_input_format2(pd, 1, &score);
409

    
410
    if (fmt) {
411
        int i;
412
        av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
413
               pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
414
        for (i = 0; fmt_id_type[i].name; i++) {
415
            if (!strcmp(fmt->name, fmt_id_type[i].name)) {
416
                st->codec->codec_id   = fmt_id_type[i].id;
417
                st->codec->codec_type = fmt_id_type[i].type;
418
                break;
419
            }
420
        }
421
    }
422
    return !!fmt;
423
}
424

    
425
/************************************************************/
426
/* input media file */
427

    
428
/**
429
 * Open a media file from an IO stream. 'fmt' must be specified.
430
 */
431
int av_open_input_stream(AVFormatContext **ic_ptr,
432
                         AVIOContext *pb, const char *filename,
433
                         AVInputFormat *fmt, AVFormatParameters *ap)
434
{
435
    int err;
436
    AVFormatContext *ic;
437
    AVFormatParameters default_ap;
438

    
439
    if(!ap){
440
        ap=&default_ap;
441
        memset(ap, 0, sizeof(default_ap));
442
    }
443

    
444
    if(!ap->prealloced_context)
445
        ic = avformat_alloc_context();
446
    else
447
        ic = *ic_ptr;
448
    if (!ic) {
449
        err = AVERROR(ENOMEM);
450
        goto fail;
451
    }
452
    ic->iformat = fmt;
453
    ic->pb = pb;
454
    ic->duration = AV_NOPTS_VALUE;
455
    ic->start_time = AV_NOPTS_VALUE;
456
    av_strlcpy(ic->filename, filename, sizeof(ic->filename));
457

    
458
    /* allocate private data */
459
    if (fmt->priv_data_size > 0) {
460
        ic->priv_data = av_mallocz(fmt->priv_data_size);
461
        if (!ic->priv_data) {
462
            err = AVERROR(ENOMEM);
463
            goto fail;
464
        }
465
    } else {
466
        ic->priv_data = NULL;
467
    }
468

    
469
    // e.g. AVFMT_NOFILE formats will not have a AVIOContext
470
    if (ic->pb)
471
        ff_id3v2_read(ic, ID3v2_DEFAULT_MAGIC);
472

    
473
    if (ic->iformat->read_header) {
474
        err = ic->iformat->read_header(ic, ap);
475
        if (err < 0)
476
            goto fail;
477
    }
478

    
479
    if (pb && !ic->data_offset)
480
        ic->data_offset = avio_tell(ic->pb);
481

    
482
    ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
483

    
484
    *ic_ptr = ic;
485
    return 0;
486
 fail:
487
    if (ic) {
488
        int i;
489
        av_freep(&ic->priv_data);
490
        for(i=0;i<ic->nb_streams;i++) {
491
            AVStream *st = ic->streams[i];
492
            if (st) {
493
                av_free(st->priv_data);
494
                av_free(st->codec->extradata);
495
                av_free(st->codec);
496
                av_free(st->info);
497
            }
498
            av_free(st);
499
        }
500
    }
501
    av_free(ic);
502
    *ic_ptr = NULL;
503
    return err;
504
}
505

    
506
/** size of probe buffer, for guessing file type from file contents */
507
#define PROBE_BUF_MIN 2048
508
#define PROBE_BUF_MAX (1<<20)
509

    
510
int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
511
                          const char *filename, void *logctx,
512
                          unsigned int offset, unsigned int max_probe_size)
513
{
514
    AVProbeData pd = { filename ? filename : "", NULL, -offset };
515
    unsigned char *buf = NULL;
516
    int ret = 0, probe_size;
517

    
518
    if (!max_probe_size) {
519
        max_probe_size = PROBE_BUF_MAX;
520
    } else if (max_probe_size > PROBE_BUF_MAX) {
521
        max_probe_size = PROBE_BUF_MAX;
522
    } else if (max_probe_size < PROBE_BUF_MIN) {
523
        return AVERROR(EINVAL);
524
    }
525

    
526
    if (offset >= max_probe_size) {
527
        return AVERROR(EINVAL);
528
    }
529

    
530
    for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt && ret >= 0;
531
        probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
532
        int ret, score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
533
        int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;
534

    
535
        if (probe_size < offset) {
536
            continue;
537
        }
538

    
539
        /* read probe data */
540
        buf = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
541
        if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
542
            /* fail if error was not end of file, otherwise, lower score */
543
            if (ret != AVERROR_EOF) {
544
                av_free(buf);
545
                return ret;
546
            }
547
            score = 0;
548
            ret = 0;            /* error was end of file, nothing read */
549
        }
550
        pd.buf_size += ret;
551
        pd.buf = &buf[offset];
552

    
553
        memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
554

    
555
        /* guess file format */
556
        *fmt = av_probe_input_format2(&pd, 1, &score);
557
        if(*fmt){
558
            if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
559
                av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);
560
            }else
561
                av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);
562
        }
563
    }
564

    
565
    if (!*fmt) {
566
        av_free(buf);
567
        return AVERROR_INVALIDDATA;
568
    }
569

    
570
    /* rewind. reuse probe buffer to avoid seeking */
571
    if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
572
        av_free(buf);
573

    
574
    return ret;
575
}
576

    
577
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
578
                       AVInputFormat *fmt,
579
                       int buf_size,
580
                       AVFormatParameters *ap)
581
{
582
    int err;
583
    AVProbeData probe_data, *pd = &probe_data;
584
    AVIOContext *pb = NULL;
585
    void *logctx= ap && ap->prealloced_context ? *ic_ptr : NULL;
586

    
587
    pd->filename = "";
588
    if (filename)
589
        pd->filename = filename;
590
    pd->buf = NULL;
591
    pd->buf_size = 0;
592

    
593
    if (!fmt) {
594
        /* guess format if no file can be opened */
595
        fmt = av_probe_input_format(pd, 0);
596
    }
597

    
598
    /* Do not open file if the format does not need it. XXX: specific
599
       hack needed to handle RTSP/TCP */
600
    if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
601
        /* if no file needed do not try to open one */
602
        if ((err=avio_open(&pb, filename, AVIO_RDONLY)) < 0) {
603
            goto fail;
604
        }
605
        if (buf_size > 0) {
606
            ffio_set_buf_size(pb, buf_size);
607
        }
608
        if (!fmt && (err = av_probe_input_buffer(pb, &fmt, filename, logctx, 0, logctx ? (*ic_ptr)->probesize : 0)) < 0) {
609
            goto fail;
610
        }
611
    }
612

    
613
    /* if still no format found, error */
614
    if (!fmt) {
615
        err = AVERROR_INVALIDDATA;
616
        goto fail;
617
    }
618

    
619
    /* check filename in case an image number is expected */
620
    if (fmt->flags & AVFMT_NEEDNUMBER) {
621
        if (!av_filename_number_test(filename)) {
622
            err = AVERROR_NUMEXPECTED;
623
            goto fail;
624
        }
625
    }
626
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
627
    if (err)
628
        goto fail;
629
    return 0;
630
 fail:
631
    av_freep(&pd->buf);
632
    if (pb)
633
        avio_close(pb);
634
    if (ap && ap->prealloced_context)
635
        av_free(*ic_ptr);
636
    *ic_ptr = NULL;
637
    return err;
638

    
639
}
640

    
641
/*******************************************************/
642

    
643
static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
644
                               AVPacketList **plast_pktl){
645
    AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
646
    if (!pktl)
647
        return NULL;
648

    
649
    if (*packet_buffer)
650
        (*plast_pktl)->next = pktl;
651
    else
652
        *packet_buffer = pktl;
653

    
654
    /* add the packet in the buffered packet list */
655
    *plast_pktl = pktl;
656
    pktl->pkt= *pkt;
657
    return &pktl->pkt;
658
}
659

    
660
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
661
{
662
    int ret, i;
663
    AVStream *st;
664

    
665
    for(;;){
666
        AVPacketList *pktl = s->raw_packet_buffer;
667

    
668
        if (pktl) {
669
            *pkt = pktl->pkt;
670
            if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||
671
               !s->streams[pkt->stream_index]->probe_packets ||
672
               s->raw_packet_buffer_remaining_size < pkt->size){
673
                AVProbeData *pd = &s->streams[pkt->stream_index]->probe_data;
674
                av_freep(&pd->buf);
675
                pd->buf_size = 0;
676
                s->raw_packet_buffer = pktl->next;
677
                s->raw_packet_buffer_remaining_size += pkt->size;
678
                av_free(pktl);
679
                return 0;
680
            }
681
        }
682

    
683
        av_init_packet(pkt);
684
        ret= s->iformat->read_packet(s, pkt);
685
        if (ret < 0) {
686
            if (!pktl || ret == AVERROR(EAGAIN))
687
                return ret;
688
            for (i = 0; i < s->nb_streams; i++)
689
                s->streams[i]->probe_packets = 0;
690
            continue;
691
        }
692
        st= s->streams[pkt->stream_index];
693

    
694
        switch(st->codec->codec_type){
695
        case AVMEDIA_TYPE_VIDEO:
696
            if(s->video_codec_id)   st->codec->codec_id= s->video_codec_id;
697
            break;
698
        case AVMEDIA_TYPE_AUDIO:
699
            if(s->audio_codec_id)   st->codec->codec_id= s->audio_codec_id;
700
            break;
701
        case AVMEDIA_TYPE_SUBTITLE:
702
            if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
703
            break;
704
        }
705

    
706
        if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
707
                     !st->probe_packets))
708
            return ret;
709

    
710
        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
711
        s->raw_packet_buffer_remaining_size -= pkt->size;
712

    
713
        if(st->codec->codec_id == CODEC_ID_PROBE){
714
            AVProbeData *pd = &st->probe_data;
715
            av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
716
            --st->probe_packets;
717

    
718
            pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
719
            memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
720
            pd->buf_size += pkt->size;
721
            memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
722

    
723
            if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
724
                //FIXME we dont reduce score to 0 for the case of running out of buffer space in bytes
725
                set_codec_from_probe_data(s, st, pd, st->probe_packets > 0 ? AVPROBE_SCORE_MAX/4 : 0);
726
                if(st->codec->codec_id != CODEC_ID_PROBE){
727
                    pd->buf_size=0;
728
                    av_freep(&pd->buf);
729
                    av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
730
                }
731
            }
732
        }
733
    }
734
}
735

    
736
/**********************************************************/
737

    
738
/**
739
 * Get the number of samples of an audio frame. Return -1 on error.
740
 */
741
static int get_audio_frame_size(AVCodecContext *enc, int size)
742
{
743
    int frame_size;
744

    
745
    if(enc->codec_id == CODEC_ID_VORBIS)
746
        return -1;
747

    
748
    if (enc->frame_size <= 1) {
749
        int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
750

    
751
        if (bits_per_sample) {
752
            if (enc->channels == 0)
753
                return -1;
754
            frame_size = (size << 3) / (bits_per_sample * enc->channels);
755
        } else {
756
            /* used for example by ADPCM codecs */
757
            if (enc->bit_rate == 0)
758
                return -1;
759
            frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
760
        }
761
    } else {
762
        frame_size = enc->frame_size;
763
    }
764
    return frame_size;
765
}
766

    
767

    
768
/**
769
 * Return the frame duration in seconds. Return 0 if not available.
770
 */
771
static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
772
                                   AVCodecParserContext *pc, AVPacket *pkt)
773
{
774
    int frame_size;
775

    
776
    *pnum = 0;
777
    *pden = 0;
778
    switch(st->codec->codec_type) {
779
    case AVMEDIA_TYPE_VIDEO:
780
        if(st->time_base.num*1000LL > st->time_base.den){
781
            *pnum = st->time_base.num;
782
            *pden = st->time_base.den;
783
        }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
784
            *pnum = st->codec->time_base.num;
785
            *pden = st->codec->time_base.den;
786
            if (pc && pc->repeat_pict) {
787
                *pnum = (*pnum) * (1 + pc->repeat_pict);
788
            }
789
            //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
790
            //Thus if we have no parser in such case leave duration undefined.
791
            if(st->codec->ticks_per_frame>1 && !pc){
792
                *pnum = *pden = 0;
793
            }
794
        }
795
        break;
796
    case AVMEDIA_TYPE_AUDIO:
797
        frame_size = get_audio_frame_size(st->codec, pkt->size);
798
        if (frame_size <= 0 || st->codec->sample_rate <= 0)
799
            break;
800
        *pnum = frame_size;
801
        *pden = st->codec->sample_rate;
802
        break;
803
    default:
804
        break;
805
    }
806
}
807

    
808
static int is_intra_only(AVCodecContext *enc){
809
    if(enc->codec_type == AVMEDIA_TYPE_AUDIO){
810
        return 1;
811
    }else if(enc->codec_type == AVMEDIA_TYPE_VIDEO){
812
        switch(enc->codec_id){
813
        case CODEC_ID_MJPEG:
814
        case CODEC_ID_MJPEGB:
815
        case CODEC_ID_LJPEG:
816
        case CODEC_ID_RAWVIDEO:
817
        case CODEC_ID_DVVIDEO:
818
        case CODEC_ID_HUFFYUV:
819
        case CODEC_ID_FFVHUFF:
820
        case CODEC_ID_ASV1:
821
        case CODEC_ID_ASV2:
822
        case CODEC_ID_VCR1:
823
        case CODEC_ID_DNXHD:
824
        case CODEC_ID_JPEG2000:
825
            return 1;
826
        default: break;
827
        }
828
    }
829
    return 0;
830
}
831

    
832
static void update_initial_timestamps(AVFormatContext *s, int stream_index,
833
                                      int64_t dts, int64_t pts)
834
{
835
    AVStream *st= s->streams[stream_index];
836
    AVPacketList *pktl= s->packet_buffer;
837

    
838
    if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
839
        return;
840

    
841
    st->first_dts= dts - st->cur_dts;
842
    st->cur_dts= dts;
843

    
844
    for(; pktl; pktl= pktl->next){
845
        if(pktl->pkt.stream_index != stream_index)
846
            continue;
847
        //FIXME think more about this check
848
        if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
849
            pktl->pkt.pts += st->first_dts;
850

    
851
        if(pktl->pkt.dts != AV_NOPTS_VALUE)
852
            pktl->pkt.dts += st->first_dts;
853

    
854
        if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
855
            st->start_time= pktl->pkt.pts;
856
    }
857
    if (st->start_time == AV_NOPTS_VALUE)
858
        st->start_time = pts;
859
}
860

    
861
static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
862
{
863
    AVPacketList *pktl= s->packet_buffer;
864
    int64_t cur_dts= 0;
865

    
866
    if(st->first_dts != AV_NOPTS_VALUE){
867
        cur_dts= st->first_dts;
868
        for(; pktl; pktl= pktl->next){
869
            if(pktl->pkt.stream_index == pkt->stream_index){
870
                if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
871
                    break;
872
                cur_dts -= pkt->duration;
873
            }
874
        }
875
        pktl= s->packet_buffer;
876
        st->first_dts = cur_dts;
877
    }else if(st->cur_dts)
878
        return;
879

    
880
    for(; pktl; pktl= pktl->next){
881
        if(pktl->pkt.stream_index != pkt->stream_index)
882
            continue;
883
        if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
884
           && !pktl->pkt.duration){
885
            pktl->pkt.dts= cur_dts;
886
            if(!st->codec->has_b_frames)
887
                pktl->pkt.pts= cur_dts;
888
            cur_dts += pkt->duration;
889
            pktl->pkt.duration= pkt->duration;
890
        }else
891
            break;
892
    }
893
    if(st->first_dts == AV_NOPTS_VALUE)
894
        st->cur_dts= cur_dts;
895
}
896

    
897
static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
898
                               AVCodecParserContext *pc, AVPacket *pkt)
899
{
900
    int num, den, presentation_delayed, delay, i;
901
    int64_t offset;
902

    
903
    if (s->flags & AVFMT_FLAG_NOFILLIN)
904
        return;
905

    
906
    if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
907
        pkt->dts= AV_NOPTS_VALUE;
908

    
909
    if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == FF_B_TYPE)
910
        //FIXME Set low_delay = 0 when has_b_frames = 1
911
        st->codec->has_b_frames = 1;
912

    
913
    /* do we have a video B-frame ? */
914
    delay= st->codec->has_b_frames;
915
    presentation_delayed = 0;
916

    
917
    // ignore delay caused by frame threading so that the mpeg2-without-dts
918
    // warning will not trigger
919
    if (delay && st->codec->active_thread_type&FF_THREAD_FRAME)
920
        delay -= st->codec->thread_count-1;
921

    
922
    /* XXX: need has_b_frame, but cannot get it if the codec is
923
        not initialized */
924
    if (delay &&
925
        pc && pc->pict_type != FF_B_TYPE)
926
        presentation_delayed = 1;
927

    
928
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
929
       /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
930
        pkt->dts -= 1LL<<st->pts_wrap_bits;
931
    }
932

    
933
    // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
934
    // we take the conservative approach and discard both
935
    // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
936
    if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
937
        av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
938
        pkt->dts= pkt->pts= AV_NOPTS_VALUE;
939
    }
940

    
941
    if (pkt->duration == 0) {
942
        compute_frame_duration(&num, &den, st, pc, pkt);
943
        if (den && num) {
944
            pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
945

    
946
            if(pkt->duration != 0 && s->packet_buffer)
947
                update_initial_durations(s, st, pkt);
948
        }
949
    }
950

    
951
    /* correct timestamps with byte offset if demuxers only have timestamps
952
       on packet boundaries */
953
    if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
954
        /* this will estimate bitrate based on this frame's duration and size */
955
        offset = av_rescale(pc->offset, pkt->duration, pkt->size);
956
        if(pkt->pts != AV_NOPTS_VALUE)
957
            pkt->pts += offset;
958
        if(pkt->dts != AV_NOPTS_VALUE)
959
            pkt->dts += offset;
960
    }
961

    
962
    if (pc && pc->dts_sync_point >= 0) {
963
        // we have synchronization info from the parser
964
        int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
965
        if (den > 0) {
966
            int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
967
            if (pkt->dts != AV_NOPTS_VALUE) {
968
                // got DTS from the stream, update reference timestamp
969
                st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
970
                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
971
            } else if (st->reference_dts != AV_NOPTS_VALUE) {
972
                // compute DTS based on reference timestamp
973
                pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
974
                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
975
            }
976
            if (pc->dts_sync_point > 0)
977
                st->reference_dts = pkt->dts; // new reference
978
        }
979
    }
980

    
981
    /* This may be redundant, but it should not hurt. */
982
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
983
        presentation_delayed = 1;
984

    
985
//    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);
986
    /* interpolate PTS and DTS if they are not present */
987
    //We skip H264 currently because delay and has_b_frames are not reliably set
988
    if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){
989
        if (presentation_delayed) {
990
            /* DTS = decompression timestamp */
991
            /* PTS = presentation timestamp */
992
            if (pkt->dts == AV_NOPTS_VALUE)
993
                pkt->dts = st->last_IP_pts;
994
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
995
            if (pkt->dts == AV_NOPTS_VALUE)
996
                pkt->dts = st->cur_dts;
997

    
998
            /* this is tricky: the dts must be incremented by the duration
999
            of the frame we are displaying, i.e. the last I- or P-frame */
1000
            if (st->last_IP_duration == 0)
1001
                st->last_IP_duration = pkt->duration;
1002
            if(pkt->dts != AV_NOPTS_VALUE)
1003
                st->cur_dts = pkt->dts + st->last_IP_duration;
1004
            st->last_IP_duration  = pkt->duration;
1005
            st->last_IP_pts= pkt->pts;
1006
            /* cannot compute PTS if not present (we can compute it only
1007
            by knowing the future */
1008
        } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
1009
            if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
1010
                int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
1011
                int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
1012
                if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
1013
                    pkt->pts += pkt->duration;
1014
    //                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);
1015
                }
1016
            }
1017

    
1018
            /* presentation is not delayed : PTS and DTS are the same */
1019
            if(pkt->pts == AV_NOPTS_VALUE)
1020
                pkt->pts = pkt->dts;
1021
            update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
1022
            if(pkt->pts == AV_NOPTS_VALUE)
1023
                pkt->pts = st->cur_dts;
1024
            pkt->dts = pkt->pts;
1025
            if(pkt->pts != AV_NOPTS_VALUE)
1026
                st->cur_dts = pkt->pts + pkt->duration;
1027
        }
1028
    }
1029

    
1030
    if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
1031
        st->pts_buffer[0]= pkt->pts;
1032
        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
1033
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
1034
        if(pkt->dts == AV_NOPTS_VALUE)
1035
            pkt->dts= st->pts_buffer[0];
1036
        if(st->codec->codec_id == CODEC_ID_H264){ //we skiped it above so we try here
1037
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
1038
        }
1039
        if(pkt->dts > st->cur_dts)
1040
            st->cur_dts = pkt->dts;
1041
    }
1042

    
1043
//    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);
1044

    
1045
    /* update flags */
1046
    if(is_intra_only(st->codec))
1047
        pkt->flags |= AV_PKT_FLAG_KEY;
1048
    else if (pc) {
1049
        pkt->flags = 0;
1050
        /* keyframe computation */
1051
        if (pc->key_frame == 1)
1052
            pkt->flags |= AV_PKT_FLAG_KEY;
1053
        else if (pc->key_frame == -1 && pc->pict_type == FF_I_TYPE)
1054
            pkt->flags |= AV_PKT_FLAG_KEY;
1055
    }
1056
    if (pc)
1057
        pkt->convergence_duration = pc->convergence_duration;
1058
}
1059

    
1060

    
1061
static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1062
{
1063
    AVStream *st;
1064
    int len, ret, i;
1065

    
1066
    av_init_packet(pkt);
1067

    
1068
    for(;;) {
1069
        /* select current input stream component */
1070
        st = s->cur_st;
1071
        if (st) {
1072
            if (!st->need_parsing || !st->parser) {
1073
                /* no parsing needed: we just output the packet as is */
1074
                /* raw data support */
1075
                *pkt = st->cur_pkt; st->cur_pkt.data= NULL;
1076
                compute_pkt_fields(s, st, NULL, pkt);
1077
                s->cur_st = NULL;
1078
                if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1079
                    (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1080
                    ff_reduce_index(s, st->index);
1081
                    av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1082
                }
1083
                break;
1084
            } else if (st->cur_len > 0 && st->discard < AVDISCARD_ALL) {
1085
                len = av_parser_parse2(st->parser, st->codec, &pkt->data, &pkt->size,
1086
                                       st->cur_ptr, st->cur_len,
1087
                                       st->cur_pkt.pts, st->cur_pkt.dts,
1088
                                       st->cur_pkt.pos);
1089
                st->cur_pkt.pts = AV_NOPTS_VALUE;
1090
                st->cur_pkt.dts = AV_NOPTS_VALUE;
1091
                /* increment read pointer */
1092
                st->cur_ptr += len;
1093
                st->cur_len -= len;
1094

    
1095
                /* return packet if any */
1096
                if (pkt->size) {
1097
                got_packet:
1098
                    pkt->duration = 0;
1099
                    pkt->stream_index = st->index;
1100
                    pkt->pts = st->parser->pts;
1101
                    pkt->dts = st->parser->dts;
1102
                    pkt->pos = st->parser->pos;
1103
                    if(pkt->data == st->cur_pkt.data && pkt->size == st->cur_pkt.size){
1104
                        s->cur_st = NULL;
1105
                        pkt->destruct= st->cur_pkt.destruct;
1106
                        st->cur_pkt.destruct= NULL;
1107
                        st->cur_pkt.data    = NULL;
1108
                        assert(st->cur_len == 0);
1109
                    }else{
1110
                    pkt->destruct = NULL;
1111
                    }
1112
                    compute_pkt_fields(s, st, st->parser, pkt);
1113

    
1114
                    if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY){
1115
                        ff_reduce_index(s, st->index);
1116
                        av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
1117
                                           0, 0, AVINDEX_KEYFRAME);
1118
                    }
1119

    
1120
                    break;
1121
                }
1122
            } else {
1123
                /* free packet */
1124
                av_free_packet(&st->cur_pkt);
1125
                s->cur_st = NULL;
1126
            }
1127
        } else {
1128
            AVPacket cur_pkt;
1129
            /* read next packet */
1130
            ret = av_read_packet(s, &cur_pkt);
1131
            if (ret < 0) {
1132
                if (ret == AVERROR(EAGAIN))
1133
                    return ret;
1134
                /* return the last frames, if any */
1135
                for(i = 0; i < s->nb_streams; i++) {
1136
                    st = s->streams[i];
1137
                    if (st->parser && st->need_parsing) {
1138
                        av_parser_parse2(st->parser, st->codec,
1139
                                        &pkt->data, &pkt->size,
1140
                                        NULL, 0,
1141
                                        AV_NOPTS_VALUE, AV_NOPTS_VALUE,
1142
                                        AV_NOPTS_VALUE);
1143
                        if (pkt->size)
1144
                            goto got_packet;
1145
                    }
1146
                }
1147
                /* no more packets: really terminate parsing */
1148
                return ret;
1149
            }
1150
            st = s->streams[cur_pkt.stream_index];
1151
            st->cur_pkt= cur_pkt;
1152

    
1153
            if(st->cur_pkt.pts != AV_NOPTS_VALUE &&
1154
               st->cur_pkt.dts != AV_NOPTS_VALUE &&
1155
               st->cur_pkt.pts < st->cur_pkt.dts){
1156
                av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1157
                    st->cur_pkt.stream_index,
1158
                    st->cur_pkt.pts,
1159
                    st->cur_pkt.dts,
1160
                    st->cur_pkt.size);
1161
//                av_free_packet(&st->cur_pkt);
1162
//                return -1;
1163
            }
1164

    
1165
            if(s->debug & FF_FDEBUG_TS)
1166
                av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1167
                    st->cur_pkt.stream_index,
1168
                    st->cur_pkt.pts,
1169
                    st->cur_pkt.dts,
1170
                    st->cur_pkt.size,
1171
                    st->cur_pkt.duration,
1172
                    st->cur_pkt.flags);
1173

    
1174
            s->cur_st = st;
1175
            st->cur_ptr = st->cur_pkt.data;
1176
            st->cur_len = st->cur_pkt.size;
1177
            if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1178
                st->parser = av_parser_init(st->codec->codec_id);
1179
                if (!st->parser) {
1180
                    /* no parser available: just output the raw packets */
1181
                    st->need_parsing = AVSTREAM_PARSE_NONE;
1182
                }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
1183
                    st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1184
                }else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE){
1185
                    st->parser->flags |= PARSER_FLAG_ONCE;
1186
                }
1187
            }
1188
        }
1189
    }
1190
    if(s->debug & FF_FDEBUG_TS)
1191
        av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1192
            pkt->stream_index,
1193
            pkt->pts,
1194
            pkt->dts,
1195
            pkt->size,
1196
            pkt->duration,
1197
            pkt->flags);
1198

    
1199
    return 0;
1200
}
1201

    
1202
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1203
{
1204
    AVPacketList *pktl;
1205
    int eof=0;
1206
    const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1207

    
1208
    for(;;){
1209
        pktl = s->packet_buffer;
1210
        if (pktl) {
1211
            AVPacket *next_pkt= &pktl->pkt;
1212

    
1213
            if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1214
                int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1215
                while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1216
                    if(   pktl->pkt.stream_index == next_pkt->stream_index
1217
                       && (0 > av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)))
1218
                       && av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
1219
                        next_pkt->pts= pktl->pkt.dts;
1220
                    }
1221
                    pktl= pktl->next;
1222
                }
1223
                pktl = s->packet_buffer;
1224
            }
1225

    
1226
            if(   next_pkt->pts != AV_NOPTS_VALUE
1227
               || next_pkt->dts == AV_NOPTS_VALUE
1228
               || !genpts || eof){
1229
                /* read packet from packet buffer, if there is data */
1230
                *pkt = *next_pkt;
1231
                s->packet_buffer = pktl->next;
1232
                av_free(pktl);
1233
                return 0;
1234
            }
1235
        }
1236
        if(genpts){
1237
            int ret= av_read_frame_internal(s, pkt);
1238
            if(ret<0){
1239
                if(pktl && ret != AVERROR(EAGAIN)){
1240
                    eof=1;
1241
                    continue;
1242
                }else
1243
                    return ret;
1244
            }
1245

    
1246
            if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1247
                                           &s->packet_buffer_end)) < 0)
1248
                return AVERROR(ENOMEM);
1249
        }else{
1250
            assert(!s->packet_buffer);
1251
            return av_read_frame_internal(s, pkt);
1252
        }
1253
    }
1254
}
1255

    
1256
/* XXX: suppress the packet queue */
1257
static void flush_packet_queue(AVFormatContext *s)
1258
{
1259
    AVPacketList *pktl;
1260

    
1261
    for(;;) {
1262
        pktl = s->packet_buffer;
1263
        if (!pktl)
1264
            break;
1265
        s->packet_buffer = pktl->next;
1266
        av_free_packet(&pktl->pkt);
1267
        av_free(pktl);
1268
    }
1269
    while(s->raw_packet_buffer){
1270
        pktl = s->raw_packet_buffer;
1271
        s->raw_packet_buffer = pktl->next;
1272
        av_free_packet(&pktl->pkt);
1273
        av_free(pktl);
1274
    }
1275
    s->packet_buffer_end=
1276
    s->raw_packet_buffer_end= NULL;
1277
    s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1278
}
1279

    
1280
/*******************************************************/
1281
/* seek support */
1282

    
1283
int av_find_default_stream_index(AVFormatContext *s)
1284
{
1285
    int first_audio_index = -1;
1286
    int i;
1287
    AVStream *st;
1288

    
1289
    if (s->nb_streams <= 0)
1290
        return -1;
1291
    for(i = 0; i < s->nb_streams; i++) {
1292
        st = s->streams[i];
1293
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1294
            return i;
1295
        }
1296
        if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1297
            first_audio_index = i;
1298
    }
1299
    return first_audio_index >= 0 ? first_audio_index : 0;
1300
}
1301

    
1302
/**
1303
 * Flush the frame reader.
1304
 */
1305
void ff_read_frame_flush(AVFormatContext *s)
1306
{
1307
    AVStream *st;
1308
    int i, j;
1309

    
1310
    flush_packet_queue(s);
1311

    
1312
    s->cur_st = NULL;
1313

    
1314
    /* for each stream, reset read state */
1315
    for(i = 0; i < s->nb_streams; i++) {
1316
        st = s->streams[i];
1317

    
1318
        if (st->parser) {
1319
            av_parser_close(st->parser);
1320
            st->parser = NULL;
1321
            av_free_packet(&st->cur_pkt);
1322
        }
1323
        st->last_IP_pts = AV_NOPTS_VALUE;
1324
        st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1325
        st->reference_dts = AV_NOPTS_VALUE;
1326
        /* fail safe */
1327
        st->cur_ptr = NULL;
1328
        st->cur_len = 0;
1329

    
1330
        st->probe_packets = MAX_PROBE_PACKETS;
1331

    
1332
        for(j=0; j<MAX_REORDER_DELAY+1; j++)
1333
            st->pts_buffer[j]= AV_NOPTS_VALUE;
1334
    }
1335
}
1336

    
1337
void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1338
    int i;
1339

    
1340
    for(i = 0; i < s->nb_streams; i++) {
1341
        AVStream *st = s->streams[i];
1342

    
1343
        st->cur_dts = av_rescale(timestamp,
1344
                                 st->time_base.den * (int64_t)ref_st->time_base.num,
1345
                                 st->time_base.num * (int64_t)ref_st->time_base.den);
1346
    }
1347
}
1348

    
1349
void ff_reduce_index(AVFormatContext *s, int stream_index)
1350
{
1351
    AVStream *st= s->streams[stream_index];
1352
    unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1353

    
1354
    if((unsigned)st->nb_index_entries >= max_entries){
1355
        int i;
1356
        for(i=0; 2*i<st->nb_index_entries; i++)
1357
            st->index_entries[i]= st->index_entries[2*i];
1358
        st->nb_index_entries= i;
1359
    }
1360
}
1361

    
1362
int ff_add_index_entry(AVIndexEntry **index_entries,
1363
                       int *nb_index_entries,
1364
                       unsigned int *index_entries_allocated_size,
1365
                       int64_t pos, int64_t timestamp, int size, int distance, int flags)
1366
{
1367
    AVIndexEntry *entries, *ie;
1368
    int index;
1369

    
1370
    if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1371
        return -1;
1372

    
1373
    entries = av_fast_realloc(*index_entries,
1374
                              index_entries_allocated_size,
1375
                              (*nb_index_entries + 1) *
1376
                              sizeof(AVIndexEntry));
1377
    if(!entries)
1378
        return -1;
1379

    
1380
    *index_entries= entries;
1381

    
1382
    index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
1383

    
1384
    if(index<0){
1385
        index= (*nb_index_entries)++;
1386
        ie= &entries[index];
1387
        assert(index==0 || ie[-1].timestamp < timestamp);
1388
    }else{
1389
        ie= &entries[index];
1390
        if(ie->timestamp != timestamp){
1391
            if(ie->timestamp <= timestamp)
1392
                return -1;
1393
            memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
1394
            (*nb_index_entries)++;
1395
        }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1396
            distance= ie->min_distance;
1397
    }
1398

    
1399
    ie->pos = pos;
1400
    ie->timestamp = timestamp;
1401
    ie->min_distance= distance;
1402
    ie->size= size;
1403
    ie->flags = flags;
1404

    
1405
    return index;
1406
}
1407

    
1408
int av_add_index_entry(AVStream *st,
1409
                       int64_t pos, int64_t timestamp, int size, int distance, int flags)
1410
{
1411
    return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1412
                              &st->index_entries_allocated_size, pos,
1413
                              timestamp, size, distance, flags);
1414
}
1415

    
1416
int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1417
                              int64_t wanted_timestamp, int flags)
1418
{
1419
    int a, b, m;
1420
    int64_t timestamp;
1421

    
1422
    a = - 1;
1423
    b = nb_entries;
1424

    
1425
    //optimize appending index entries at the end
1426
    if(b && entries[b-1].timestamp < wanted_timestamp)
1427
        a= b-1;
1428

    
1429
    while (b - a > 1) {
1430
        m = (a + b) >> 1;
1431
        timestamp = entries[m].timestamp;
1432
        if(timestamp >= wanted_timestamp)
1433
            b = m;
1434
        if(timestamp <= wanted_timestamp)
1435
            a = m;
1436
    }
1437
    m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1438

    
1439
    if(!(flags & AVSEEK_FLAG_ANY)){
1440
        while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1441
            m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1442
        }
1443
    }
1444

    
1445
    if(m == nb_entries)
1446
        return -1;
1447
    return  m;
1448
}
1449

    
1450
int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1451
                              int flags)
1452
{
1453
    return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1454
                                     wanted_timestamp, flags);
1455
}
1456

    
1457
#define DEBUG_SEEK
1458

    
1459
int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1460
    AVInputFormat *avif= s->iformat;
1461
    int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1462
    int64_t ts_min, ts_max, ts;
1463
    int index;
1464
    int64_t ret;
1465
    AVStream *st;
1466

    
1467
    if (stream_index < 0)
1468
        return -1;
1469

    
1470
#ifdef DEBUG_SEEK
1471
    av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1472
#endif
1473

    
1474
    ts_max=
1475
    ts_min= AV_NOPTS_VALUE;
1476
    pos_limit= -1; //gcc falsely says it may be uninitialized
1477

    
1478
    st= s->streams[stream_index];
1479
    if(st->index_entries){
1480
        AVIndexEntry *e;
1481

    
1482
        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()
1483
        index= FFMAX(index, 0);
1484
        e= &st->index_entries[index];
1485

    
1486
        if(e->timestamp <= target_ts || e->pos == e->min_distance){
1487
            pos_min= e->pos;
1488
            ts_min= e->timestamp;
1489
#ifdef DEBUG_SEEK
1490
            av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1491
                   pos_min,ts_min);
1492
#endif
1493
        }else{
1494
            assert(index==0);
1495
        }
1496

    
1497
        index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1498
        assert(index < st->nb_index_entries);
1499
        if(index >= 0){
1500
            e= &st->index_entries[index];
1501
            assert(e->timestamp >= target_ts);
1502
            pos_max= e->pos;
1503
            ts_max= e->timestamp;
1504
            pos_limit= pos_max - e->min_distance;
1505
#ifdef DEBUG_SEEK
1506
            av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1507
                   pos_max,pos_limit, ts_max);
1508
#endif
1509
        }
1510
    }
1511

    
1512
    pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1513
    if(pos<0)
1514
        return -1;
1515

    
1516
    /* do the seek */
1517
    if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1518
        return ret;
1519

    
1520
    av_update_cur_dts(s, st, ts);
1521

    
1522
    return 0;
1523
}
1524

    
1525
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 )){
1526
    int64_t pos, ts;
1527
    int64_t start_pos, filesize;
1528
    int no_change;
1529

    
1530
#ifdef DEBUG_SEEK
1531
    av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1532
#endif
1533

    
1534
    if(ts_min == AV_NOPTS_VALUE){
1535
        pos_min = s->data_offset;
1536
        ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1537
        if (ts_min == AV_NOPTS_VALUE)
1538
            return -1;
1539
    }
1540

    
1541
    if(ts_max == AV_NOPTS_VALUE){
1542
        int step= 1024;
1543
        filesize = avio_size(s->pb);
1544
        pos_max = filesize - 1;
1545
        do{
1546
            pos_max -= step;
1547
            ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1548
            step += step;
1549
        }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1550
        if (ts_max == AV_NOPTS_VALUE)
1551
            return -1;
1552

    
1553
        for(;;){
1554
            int64_t tmp_pos= pos_max + 1;
1555
            int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1556
            if(tmp_ts == AV_NOPTS_VALUE)
1557
                break;
1558
            ts_max= tmp_ts;
1559
            pos_max= tmp_pos;
1560
            if(tmp_pos >= filesize)
1561
                break;
1562
        }
1563
        pos_limit= pos_max;
1564
    }
1565

    
1566
    if(ts_min > ts_max){
1567
        return -1;
1568
    }else if(ts_min == ts_max){
1569
        pos_limit= pos_min;
1570
    }
1571

    
1572
    no_change=0;
1573
    while (pos_min < pos_limit) {
1574
#ifdef DEBUG_SEEK
1575
        av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1576
               pos_min, pos_max,
1577
               ts_min, ts_max);
1578
#endif
1579
        assert(pos_limit <= pos_max);
1580

    
1581
        if(no_change==0){
1582
            int64_t approximate_keyframe_distance= pos_max - pos_limit;
1583
            // interpolate position (better than dichotomy)
1584
            pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1585
                + pos_min - approximate_keyframe_distance;
1586
        }else if(no_change==1){
1587
            // bisection, if interpolation failed to change min or max pos last time
1588
            pos = (pos_min + pos_limit)>>1;
1589
        }else{
1590
            /* linear search if bisection failed, can only happen if there
1591
               are very few or no keyframes between min/max */
1592
            pos=pos_min;
1593
        }
1594
        if(pos <= pos_min)
1595
            pos= pos_min + 1;
1596
        else if(pos > pos_limit)
1597
            pos= pos_limit;
1598
        start_pos= pos;
1599

    
1600
        ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1601
        if(pos == pos_max)
1602
            no_change++;
1603
        else
1604
            no_change=0;
1605
#ifdef DEBUG_SEEK
1606
        av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1607
               pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit,
1608
               start_pos, no_change);
1609
#endif
1610
        if(ts == AV_NOPTS_VALUE){
1611
            av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1612
            return -1;
1613
        }
1614
        assert(ts != AV_NOPTS_VALUE);
1615
        if (target_ts <= ts) {
1616
            pos_limit = start_pos - 1;
1617
            pos_max = pos;
1618
            ts_max = ts;
1619
        }
1620
        if (target_ts >= ts) {
1621
            pos_min = pos;
1622
            ts_min = ts;
1623
        }
1624
    }
1625

    
1626
    pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1627
    ts  = (flags & AVSEEK_FLAG_BACKWARD) ?  ts_min :  ts_max;
1628
#ifdef DEBUG_SEEK
1629
    pos_min = pos;
1630
    ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1631
    pos_min++;
1632
    ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1633
    av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1634
           pos, ts_min, target_ts, ts_max);
1635
#endif
1636
    *ts_ret= ts;
1637
    return pos;
1638
}
1639

    
1640
static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1641
    int64_t pos_min, pos_max;
1642
#if 0
1643
    AVStream *st;
1644

1645
    if (stream_index < 0)
1646
        return -1;
1647

1648
    st= s->streams[stream_index];
1649
#endif
1650

    
1651
    pos_min = s->data_offset;
1652
    pos_max = avio_size(s->pb) - 1;
1653

    
1654
    if     (pos < pos_min) pos= pos_min;
1655
    else if(pos > pos_max) pos= pos_max;
1656

    
1657
    avio_seek(s->pb, pos, SEEK_SET);
1658

    
1659
#if 0
1660
    av_update_cur_dts(s, st, ts);
1661
#endif
1662
    return 0;
1663
}
1664

    
1665
static int av_seek_frame_generic(AVFormatContext *s,
1666
                                 int stream_index, int64_t timestamp, int flags)
1667
{
1668
    int index;
1669
    int64_t ret;
1670
    AVStream *st;
1671
    AVIndexEntry *ie;
1672

    
1673
    st = s->streams[stream_index];
1674

    
1675
    index = av_index_search_timestamp(st, timestamp, flags);
1676

    
1677
    if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1678
        return -1;
1679

    
1680
    if(index < 0 || index==st->nb_index_entries-1){
1681
        int i;
1682
        AVPacket pkt;
1683

    
1684
        if(st->nb_index_entries){
1685
            assert(st->index_entries);
1686
            ie= &st->index_entries[st->nb_index_entries-1];
1687
            if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1688
                return ret;
1689
            av_update_cur_dts(s, st, ie->timestamp);
1690
        }else{
1691
            if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
1692
                return ret;
1693
        }
1694
        for(i=0;; i++) {
1695
            int ret;
1696
            do{
1697
                ret = av_read_frame(s, &pkt);
1698
            }while(ret == AVERROR(EAGAIN));
1699
            if(ret<0)
1700
                break;
1701
            av_free_packet(&pkt);
1702
            if(stream_index == pkt.stream_index){
1703
                if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
1704
                    break;
1705
            }
1706
        }
1707
        index = av_index_search_timestamp(st, timestamp, flags);
1708
    }
1709
    if (index < 0)
1710
        return -1;
1711

    
1712
    ff_read_frame_flush(s);
1713
    if (s->iformat->read_seek){
1714
        if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1715
            return 0;
1716
    }
1717
    ie = &st->index_entries[index];
1718
    if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1719
        return ret;
1720
    av_update_cur_dts(s, st, ie->timestamp);
1721

    
1722
    return 0;
1723
}
1724

    
1725
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1726
{
1727
    int ret;
1728
    AVStream *st;
1729

    
1730
    ff_read_frame_flush(s);
1731

    
1732
    if(flags & AVSEEK_FLAG_BYTE)
1733
        return av_seek_frame_byte(s, stream_index, timestamp, flags);
1734

    
1735
    if(stream_index < 0){
1736
        stream_index= av_find_default_stream_index(s);
1737
        if(stream_index < 0)
1738
            return -1;
1739

    
1740
        st= s->streams[stream_index];
1741
       /* timestamp for default must be expressed in AV_TIME_BASE units */
1742
        timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1743
    }
1744

    
1745
    /* first, we try the format specific seek */
1746
    if (s->iformat->read_seek)
1747
        ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1748
    else
1749
        ret = -1;
1750
    if (ret >= 0) {
1751
        return 0;
1752
    }
1753

    
1754
    if(s->iformat->read_timestamp)
1755
        return av_seek_frame_binary(s, stream_index, timestamp, flags);
1756
    else
1757
        return av_seek_frame_generic(s, stream_index, timestamp, flags);
1758
}
1759

    
1760
int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1761
{
1762
    if(min_ts > ts || max_ts < ts)
1763
        return -1;
1764

    
1765
    ff_read_frame_flush(s);
1766

    
1767
    if (s->iformat->read_seek2)
1768
        return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1769

    
1770
    if(s->iformat->read_timestamp){
1771
        //try to seek via read_timestamp()
1772
    }
1773

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

    
1779
    // try some generic seek like av_seek_frame_generic() but with new ts semantics
1780
}
1781

    
1782
/*******************************************************/
1783

    
1784
/**
1785
 * Return TRUE if the stream has accurate duration in any stream.
1786
 *
1787
 * @return TRUE if the stream has accurate duration for at least one component.
1788
 */
1789
static int av_has_duration(AVFormatContext *ic)
1790
{
1791
    int i;
1792
    AVStream *st;
1793

    
1794
    for(i = 0;i < ic->nb_streams; i++) {
1795
        st = ic->streams[i];
1796
        if (st->duration != AV_NOPTS_VALUE)
1797
            return 1;
1798
    }
1799
    return 0;
1800
}
1801

    
1802
/**
1803
 * Estimate the stream timings from the one of each components.
1804
 *
1805
 * Also computes the global bitrate if possible.
1806
 */
1807
static void av_update_stream_timings(AVFormatContext *ic)
1808
{
1809
    int64_t start_time, start_time1, end_time, end_time1;
1810
    int64_t duration, duration1;
1811
    int i;
1812
    AVStream *st;
1813

    
1814
    start_time = INT64_MAX;
1815
    end_time = INT64_MIN;
1816
    duration = INT64_MIN;
1817
    for(i = 0;i < ic->nb_streams; i++) {
1818
        st = ic->streams[i];
1819
        if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1820
            start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1821
            if (start_time1 < start_time)
1822
                start_time = start_time1;
1823
            if (st->duration != AV_NOPTS_VALUE) {
1824
                end_time1 = start_time1
1825
                          + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1826
                if (end_time1 > end_time)
1827
                    end_time = end_time1;
1828
            }
1829
        }
1830
        if (st->duration != AV_NOPTS_VALUE) {
1831
            duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1832
            if (duration1 > duration)
1833
                duration = duration1;
1834
        }
1835
    }
1836
    if (start_time != INT64_MAX) {
1837
        ic->start_time = start_time;
1838
        if (end_time != INT64_MIN) {
1839
            if (end_time - start_time > duration)
1840
                duration = end_time - start_time;
1841
        }
1842
    }
1843
    if (duration != INT64_MIN) {
1844
        ic->duration = duration;
1845
        if (ic->file_size > 0) {
1846
            /* compute the bitrate */
1847
            ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1848
                (double)ic->duration;
1849
        }
1850
    }
1851
}
1852

    
1853
static void fill_all_stream_timings(AVFormatContext *ic)
1854
{
1855
    int i;
1856
    AVStream *st;
1857

    
1858
    av_update_stream_timings(ic);
1859
    for(i = 0;i < ic->nb_streams; i++) {
1860
        st = ic->streams[i];
1861
        if (st->start_time == AV_NOPTS_VALUE) {
1862
            if(ic->start_time != AV_NOPTS_VALUE)
1863
                st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1864
            if(ic->duration != AV_NOPTS_VALUE)
1865
                st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1866
        }
1867
    }
1868
}
1869

    
1870
static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1871
{
1872
    int64_t filesize, duration;
1873
    int bit_rate, i;
1874
    AVStream *st;
1875

    
1876
    /* if bit_rate is already set, we believe it */
1877
    if (ic->bit_rate <= 0) {
1878
        bit_rate = 0;
1879
        for(i=0;i<ic->nb_streams;i++) {
1880
            st = ic->streams[i];
1881
            if (st->codec->bit_rate > 0)
1882
            bit_rate += st->codec->bit_rate;
1883
        }
1884
        ic->bit_rate = bit_rate;
1885
    }
1886

    
1887
    /* if duration is already set, we believe it */
1888
    if (ic->duration == AV_NOPTS_VALUE &&
1889
        ic->bit_rate != 0 &&
1890
        ic->file_size != 0)  {
1891
        filesize = ic->file_size;
1892
        if (filesize > 0) {
1893
            for(i = 0; i < ic->nb_streams; i++) {
1894
                st = ic->streams[i];
1895
                duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1896
                if (st->duration == AV_NOPTS_VALUE)
1897
                    st->duration = duration;
1898
            }
1899
        }
1900
    }
1901
}
1902

    
1903
#define DURATION_MAX_READ_SIZE 250000
1904
#define DURATION_MAX_RETRY 3
1905

    
1906
/* only usable for MPEG-PS streams */
1907
static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1908
{
1909
    AVPacket pkt1, *pkt = &pkt1;
1910
    AVStream *st;
1911
    int read_size, i, ret;
1912
    int64_t end_time;
1913
    int64_t filesize, offset, duration;
1914
    int retry=0;
1915

    
1916
    ic->cur_st = NULL;
1917

    
1918
    /* flush packet queue */
1919
    flush_packet_queue(ic);
1920

    
1921
    for (i=0; i<ic->nb_streams; i++) {
1922
        st = ic->streams[i];
1923
        if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
1924
            av_log(st->codec, AV_LOG_WARNING, "start time is not set in av_estimate_timings_from_pts\n");
1925

    
1926
        if (st->parser) {
1927
            av_parser_close(st->parser);
1928
            st->parser= NULL;
1929
            av_free_packet(&st->cur_pkt);
1930
        }
1931
    }
1932

    
1933
    /* estimate the end time (duration) */
1934
    /* XXX: may need to support wrapping */
1935
    filesize = ic->file_size;
1936
    end_time = AV_NOPTS_VALUE;
1937
    do{
1938
    offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
1939
    if (offset < 0)
1940
        offset = 0;
1941

    
1942
    avio_seek(ic->pb, offset, SEEK_SET);
1943
    read_size = 0;
1944
    for(;;) {
1945
        if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
1946
            break;
1947

    
1948
        do{
1949
            ret = av_read_packet(ic, pkt);
1950
        }while(ret == AVERROR(EAGAIN));
1951
        if (ret != 0)
1952
            break;
1953
        read_size += pkt->size;
1954
        st = ic->streams[pkt->stream_index];
1955
        if (pkt->pts != AV_NOPTS_VALUE &&
1956
            (st->start_time != AV_NOPTS_VALUE ||
1957
             st->first_dts  != AV_NOPTS_VALUE)) {
1958
            duration = end_time = pkt->pts;
1959
            if (st->start_time != AV_NOPTS_VALUE)  duration -= st->start_time;
1960
            else                                   duration -= st->first_dts;
1961
            if (duration < 0)
1962
                duration += 1LL<<st->pts_wrap_bits;
1963
            if (duration > 0) {
1964
                if (st->duration == AV_NOPTS_VALUE ||
1965
                    st->duration < duration)
1966
                    st->duration = duration;
1967
            }
1968
        }
1969
        av_free_packet(pkt);
1970
    }
1971
    }while(   end_time==AV_NOPTS_VALUE
1972
           && filesize > (DURATION_MAX_READ_SIZE<<retry)
1973
           && ++retry <= DURATION_MAX_RETRY);
1974

    
1975
    fill_all_stream_timings(ic);
1976

    
1977
    avio_seek(ic->pb, old_offset, SEEK_SET);
1978
    for (i=0; i<ic->nb_streams; i++) {
1979
        st= ic->streams[i];
1980
        st->cur_dts= st->first_dts;
1981
        st->last_IP_pts = AV_NOPTS_VALUE;
1982
    }
1983
}
1984

    
1985
static void av_estimate_timings(AVFormatContext *ic, int64_t old_offset)
1986
{
1987
    int64_t file_size;
1988

    
1989
    /* get the file size, if possible */
1990
    if (ic->iformat->flags & AVFMT_NOFILE) {
1991
        file_size = 0;
1992
    } else {
1993
        file_size = avio_size(ic->pb);
1994
        if (file_size < 0)
1995
            file_size = 0;
1996
    }
1997
    ic->file_size = file_size;
1998

    
1999
    if ((!strcmp(ic->iformat->name, "mpeg") ||
2000
         !strcmp(ic->iformat->name, "mpegts")) &&
2001
        file_size && ic->pb->seekable) {
2002
        /* get accurate estimate from the PTSes */
2003
        av_estimate_timings_from_pts(ic, old_offset);
2004
    } else if (av_has_duration(ic)) {
2005
        /* at least one component has timings - we use them for all
2006
           the components */
2007
        fill_all_stream_timings(ic);
2008
    } else {
2009
        av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
2010
        /* less precise: use bitrate info */
2011
        av_estimate_timings_from_bit_rate(ic);
2012
    }
2013
    av_update_stream_timings(ic);
2014

    
2015
#if 0
2016
    {
2017
        int i;
2018
        AVStream *st;
2019
        for(i = 0;i < ic->nb_streams; i++) {
2020
            st = ic->streams[i];
2021
        printf("%d: start_time: %0.3f duration: %0.3f\n",
2022
               i, (double)st->start_time / AV_TIME_BASE,
2023
               (double)st->duration / AV_TIME_BASE);
2024
        }
2025
        printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2026
               (double)ic->start_time / AV_TIME_BASE,
2027
               (double)ic->duration / AV_TIME_BASE,
2028
               ic->bit_rate / 1000);
2029
    }
2030
#endif
2031
}
2032

    
2033
static int has_codec_parameters(AVCodecContext *enc)
2034
{
2035
    int val;
2036
    switch(enc->codec_type) {
2037
    case AVMEDIA_TYPE_AUDIO:
2038
        val = enc->sample_rate && enc->channels && enc->sample_fmt != AV_SAMPLE_FMT_NONE;
2039
        if(!enc->frame_size &&
2040
           (enc->codec_id == CODEC_ID_VORBIS ||
2041
            enc->codec_id == CODEC_ID_AAC ||
2042
            enc->codec_id == CODEC_ID_MP1 ||
2043
            enc->codec_id == CODEC_ID_MP2 ||
2044
            enc->codec_id == CODEC_ID_MP3 ||
2045
            enc->codec_id == CODEC_ID_SPEEX))
2046
            return 0;
2047
        break;
2048
    case AVMEDIA_TYPE_VIDEO:
2049
        val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
2050
        break;
2051
    default:
2052
        val = 1;
2053
        break;
2054
    }
2055
    return enc->codec_id != CODEC_ID_NONE && val != 0;
2056
}
2057

    
2058
static int has_decode_delay_been_guessed(AVStream *st)
2059
{
2060
    return st->codec->codec_id != CODEC_ID_H264 ||
2061
        st->codec_info_nb_frames >= 6 + st->codec->has_b_frames;
2062
}
2063

    
2064
static int try_decode_frame(AVStream *st, AVPacket *avpkt)
2065
{
2066
    int16_t *samples;
2067
    AVCodec *codec;
2068
    int got_picture, data_size, ret=0;
2069
    AVFrame picture;
2070

    
2071
    if(!st->codec->codec){
2072
        codec = avcodec_find_decoder(st->codec->codec_id);
2073
        if (!codec)
2074
            return -1;
2075
        ret = avcodec_open(st->codec, codec);
2076
        if (ret < 0)
2077
            return ret;
2078
    }
2079

    
2080
    if(!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st)){
2081
        switch(st->codec->codec_type) {
2082
        case AVMEDIA_TYPE_VIDEO:
2083
            avcodec_get_frame_defaults(&picture);
2084
            ret = avcodec_decode_video2(st->codec, &picture,
2085
                                        &got_picture, avpkt);
2086
            break;
2087
        case AVMEDIA_TYPE_AUDIO:
2088
            data_size = FFMAX(avpkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
2089
            samples = av_malloc(data_size);
2090
            if (!samples)
2091
                goto fail;
2092
            ret = avcodec_decode_audio3(st->codec, samples,
2093
                                        &data_size, avpkt);
2094
            av_free(samples);
2095
            break;
2096
        default:
2097
            break;
2098
        }
2099
    }
2100
 fail:
2101
    return ret;
2102
}
2103

    
2104
unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum CodecID id)
2105
{
2106
    while (tags->id != CODEC_ID_NONE) {
2107
        if (tags->id == id)
2108
            return tags->tag;
2109
        tags++;
2110
    }
2111
    return 0;
2112
}
2113

    
2114
enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2115
{
2116
    int i;
2117
    for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
2118
        if(tag == tags[i].tag)
2119
            return tags[i].id;
2120
    }
2121
    for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
2122
        if (ff_toupper4(tag) == ff_toupper4(tags[i].tag))
2123
            return tags[i].id;
2124
    }
2125
    return CODEC_ID_NONE;
2126
}
2127

    
2128
unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
2129
{
2130
    int i;
2131
    for(i=0; tags && tags[i]; i++){
2132
        int tag= ff_codec_get_tag(tags[i], id);
2133
        if(tag) return tag;
2134
    }
2135
    return 0;
2136
}
2137

    
2138
enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2139
{
2140
    int i;
2141
    for(i=0; tags && tags[i]; i++){
2142
        enum CodecID id= ff_codec_get_id(tags[i], tag);
2143
        if(id!=CODEC_ID_NONE) return id;
2144
    }
2145
    return CODEC_ID_NONE;
2146
}
2147

    
2148
static void compute_chapters_end(AVFormatContext *s)
2149
{
2150
    unsigned int i, j;
2151
    int64_t max_time = s->duration + (s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time;
2152

    
2153
    for (i = 0; i < s->nb_chapters; i++)
2154
        if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2155
            AVChapter *ch = s->chapters[i];
2156
            int64_t   end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
2157
                                     : INT64_MAX;
2158

    
2159
            for (j = 0; j < s->nb_chapters; j++) {
2160
                AVChapter *ch1 = s->chapters[j];
2161
                int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
2162
                if (j != i && next_start > ch->start && next_start < end)
2163
                    end = next_start;
2164
            }
2165
            ch->end = (end == INT64_MAX) ? ch->start : end;
2166
        }
2167
}
2168

    
2169
static int get_std_framerate(int i){
2170
    if(i<60*12) return i*1001;
2171
    else        return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2172
}
2173

    
2174
/*
2175
 * Is the time base unreliable.
2176
 * This is a heuristic to balance between quick acceptance of the values in
2177
 * the headers vs. some extra checks.
2178
 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2179
 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2180
 * And there are "variable" fps files this needs to detect as well.
2181
 */
2182
static int tb_unreliable(AVCodecContext *c){
2183
    if(   c->time_base.den >= 101L*c->time_base.num
2184
       || c->time_base.den <    5L*c->time_base.num
2185
/*       || c->codec_tag == AV_RL32("DIVX")
2186
       || c->codec_tag == AV_RL32("XVID")*/
2187
       || c->codec_id == CODEC_ID_MPEG2VIDEO
2188
       || c->codec_id == CODEC_ID_H264
2189
       )
2190
        return 1;
2191
    return 0;
2192
}
2193

    
2194
int av_find_stream_info(AVFormatContext *ic)
2195
{
2196
    int i, count, ret, read_size, j;
2197
    AVStream *st;
2198
    AVPacket pkt1, *pkt;
2199
    int64_t old_offset = avio_tell(ic->pb);
2200

    
2201
    for(i=0;i<ic->nb_streams;i++) {
2202
        AVCodec *codec;
2203
        st = ic->streams[i];
2204
        if (st->codec->codec_id == CODEC_ID_AAC) {
2205
            st->codec->sample_rate = 0;
2206
            st->codec->frame_size = 0;
2207
            st->codec->channels = 0;
2208
        }
2209
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2210
            st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2211
/*            if(!st->time_base.num)
2212
                st->time_base= */
2213
            if(!st->codec->time_base.num)
2214
                st->codec->time_base= st->time_base;
2215
        }
2216
        //only for the split stuff
2217
        if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2218
            st->parser = av_parser_init(st->codec->codec_id);
2219
            if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2220
                st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2221
            }
2222
        }
2223
        assert(!st->codec->codec);
2224
        codec = avcodec_find_decoder(st->codec->codec_id);
2225

    
2226
        /* Force decoding of at least one frame of codec data
2227
         * this makes sure the codec initializes the channel configuration
2228
         * and does not trust the values from the container.
2229
         */
2230
        if (codec && codec->capabilities & CODEC_CAP_CHANNEL_CONF)
2231
            st->codec->channels = 0;
2232

    
2233
        /* Ensure that subtitle_header is properly set. */
2234
        if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
2235
            && codec && !st->codec->codec)
2236
            avcodec_open(st->codec, codec);
2237

    
2238
        //try to just open decoders, in case this is enough to get parameters
2239
        if(!has_codec_parameters(st->codec)){
2240
            if (codec && !st->codec->codec)
2241
                avcodec_open(st->codec, codec);
2242
        }
2243
    }
2244

    
2245
    for (i=0; i<ic->nb_streams; i++) {
2246
        ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
2247
    }
2248

    
2249
    count = 0;
2250
    read_size = 0;
2251
    for(;;) {
2252
        if(url_interrupt_cb()){
2253
            ret= AVERROR_EXIT;
2254
            av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2255
            break;
2256
        }
2257

    
2258
        /* check if one codec still needs to be handled */
2259
        for(i=0;i<ic->nb_streams;i++) {
2260
            st = ic->streams[i];
2261
            if (!has_codec_parameters(st->codec))
2262
                break;
2263
            /* variable fps and no guess at the real fps */
2264
            if(   tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)
2265
               && st->info->duration_count<20 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2266
                break;
2267
            if(st->parser && st->parser->parser->split && !st->codec->extradata)
2268
                break;
2269
            if(st->first_dts == AV_NOPTS_VALUE)
2270
                break;
2271
        }
2272
        if (i == ic->nb_streams) {
2273
            /* NOTE: if the format has no header, then we need to read
2274
               some packets to get most of the streams, so we cannot
2275
               stop here */
2276
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2277
                /* if we found the info for all the codecs, we can stop */
2278
                ret = count;
2279
                av_log(ic, AV_LOG_DEBUG, "All info found\n");
2280
                break;
2281
            }
2282
        }
2283
        /* we did not get all the codec info, but we read too much data */
2284
        if (read_size >= ic->probesize) {
2285
            ret = count;
2286
            av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2287
            break;
2288
        }
2289

    
2290
        /* NOTE: a new stream can be added there if no header in file
2291
           (AVFMTCTX_NOHEADER) */
2292
        ret = av_read_frame_internal(ic, &pkt1);
2293
        if (ret < 0 && ret != AVERROR(EAGAIN)) {
2294
            /* EOF or error */
2295
            ret = -1; /* we could not have all the codec parameters before EOF */
2296
            for(i=0;i<ic->nb_streams;i++) {
2297
                st = ic->streams[i];
2298
                if (!has_codec_parameters(st->codec)){
2299
                    char buf[256];
2300
                    avcodec_string(buf, sizeof(buf), st->codec, 0);
2301
                    av_log(ic, AV_LOG_WARNING, "Could not find codec parameters (%s)\n", buf);
2302
                } else {
2303
                    ret = 0;
2304
                }
2305
            }
2306
            break;
2307
        }
2308

    
2309
        if (ret == AVERROR(EAGAIN))
2310
            continue;
2311

    
2312
        pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
2313
        if ((ret = av_dup_packet(pkt)) < 0)
2314
            goto find_stream_info_err;
2315

    
2316
        read_size += pkt->size;
2317

    
2318
        st = ic->streams[pkt->stream_index];
2319
        if (st->codec_info_nb_frames>1) {
2320
            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) {
2321
                av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2322
                break;
2323
            }
2324
            st->info->codec_info_duration += pkt->duration;
2325
        }
2326
        {
2327
            int64_t last = st->info->last_dts;
2328
            int64_t duration= pkt->dts - last;
2329

    
2330
            if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
2331
                double dur= duration * av_q2d(st->time_base);
2332

    
2333
//                if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2334
//                    av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
2335
                if (st->info->duration_count < 2)
2336
                    memset(st->info->duration_error, 0, sizeof(st->info->duration_error));
2337
                for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error); i++) {
2338
                    int framerate= get_std_framerate(i);
2339
                    int ticks= lrintf(dur*framerate/(1001*12));
2340
                    double error= dur - ticks*1001*12/(double)framerate;
2341
                    st->info->duration_error[i] += error*error;
2342
                }
2343
                st->info->duration_count++;
2344
                // ignore the first 4 values, they might have some random jitter
2345
                if (st->info->duration_count > 3)
2346
                    st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
2347
            }
2348
            if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
2349
                st->info->last_dts = pkt->dts;
2350
        }
2351
        if(st->parser && st->parser->parser->split && !st->codec->extradata){
2352
            int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2353
            if(i){
2354
                st->codec->extradata_size= i;
2355
                st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2356
                memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2357
                memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2358
            }
2359
        }
2360

    
2361
        /* if still no information, we try to open the codec and to
2362
           decompress the frame. We try to avoid that in most cases as
2363
           it takes longer and uses more memory. For MPEG-4, we need to
2364
           decompress for QuickTime. */
2365
        if (!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st))
2366
            try_decode_frame(st, pkt);
2367

    
2368
        st->codec_info_nb_frames++;
2369
        count++;
2370
    }
2371

    
2372
    // close codecs which were opened in try_decode_frame()
2373
    for(i=0;i<ic->nb_streams;i++) {
2374
        st = ic->streams[i];
2375
        if(st->codec->codec)
2376
            avcodec_close(st->codec);
2377
    }
2378
    for(i=0;i<ic->nb_streams;i++) {
2379
        st = ic->streams[i];
2380
        if (st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && st->info->codec_info_duration)
2381
            av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2382
                     (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,
2383
                      st->info->codec_info_duration*(int64_t)st->time_base.num, 60000);
2384
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2385
            if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample)
2386
                st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2387

    
2388
            // the check for tb_unreliable() is not completely correct, since this is not about handling
2389
            // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2390
            // ipmovie.c produces.
2391
            if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > 1 && !st->r_frame_rate.num)
2392
                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);
2393
            if (st->info->duration_count && !st->r_frame_rate.num
2394
               && tb_unreliable(st->codec) /*&&
2395
               //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2396
               st->time_base.num*duration_sum[i]/st->info->duration_count*101LL > st->time_base.den*/){
2397
                int num = 0;
2398
                double best_error= 2*av_q2d(st->time_base);
2399
                best_error = best_error*best_error*st->info->duration_count*1000*12*30;
2400

    
2401
                for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error); j++) {
2402
                    double error = st->info->duration_error[j] * get_std_framerate(j);
2403
//                    if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2404
//                        av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
2405
                    if(error < best_error){
2406
                        best_error= error;
2407
                        num = get_std_framerate(j);
2408
                    }
2409
                }
2410
                // do not increase frame rate by more than 1 % in order to match a standard rate.
2411
                if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
2412
                    av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2413
            }
2414

    
2415
            if (!st->r_frame_rate.num){
2416
                if(    st->codec->time_base.den * (int64_t)st->time_base.num
2417
                    <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){
2418
                    st->r_frame_rate.num = st->codec->time_base.den;
2419
                    st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
2420
                }else{
2421
                    st->r_frame_rate.num = st->time_base.den;
2422
                    st->r_frame_rate.den = st->time_base.num;
2423
                }
2424
            }
2425
        }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2426
            if(!st->codec->bits_per_coded_sample)
2427
                st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2428
            // set stream disposition based on audio service type
2429
            switch (st->codec->audio_service_type) {
2430
            case AV_AUDIO_SERVICE_TYPE_EFFECTS:
2431
                st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;    break;
2432
            case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
2433
                st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;  break;
2434
            case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
2435
                st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
2436
            case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
2437
                st->disposition = AV_DISPOSITION_COMMENT;          break;
2438
            case AV_AUDIO_SERVICE_TYPE_KARAOKE:
2439
                st->disposition = AV_DISPOSITION_KARAOKE;          break;
2440
            }
2441
        }
2442
    }
2443

    
2444
    av_estimate_timings(ic, old_offset);
2445

    
2446
    compute_chapters_end(ic);
2447

    
2448
#if 0
2449
    /* correct DTS for B-frame streams with no timestamps */
2450
    for(i=0;i<ic->nb_streams;i++) {
2451
        st = ic->streams[i];
2452
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2453
            if(b-frames){
2454
                ppktl = &ic->packet_buffer;
2455
                while(ppkt1){
2456
                    if(ppkt1->stream_index != i)
2457
                        continue;
2458
                    if(ppkt1->pkt->dts < 0)
2459
                        break;
2460
                    if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2461
                        break;
2462
                    ppkt1->pkt->dts -= delta;
2463
                    ppkt1= ppkt1->next;
2464
                }
2465
                if(ppkt1)
2466
                    continue;
2467
                st->cur_dts -= delta;
2468
            }
2469
        }
2470
    }
2471
#endif
2472

    
2473
 find_stream_info_err:
2474
    for (i=0; i < ic->nb_streams; i++)
2475
        av_freep(&ic->streams[i]->info);
2476
    return ret;
2477
}
2478

    
2479
static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
2480
{
2481
    int i, j;
2482

    
2483
    for (i = 0; i < ic->nb_programs; i++)
2484
        for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2485
            if (ic->programs[i]->stream_index[j] == s)
2486
                return ic->programs[i];
2487
    return NULL;
2488
}
2489

    
2490
int av_find_best_stream(AVFormatContext *ic,
2491
                        enum AVMediaType type,
2492
                        int wanted_stream_nb,
2493
                        int related_stream,
2494
                        AVCodec **decoder_ret,
2495
                        int flags)
2496
{
2497
    int i, nb_streams = ic->nb_streams, stream_number = 0;
2498
    int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2499
    unsigned *program = NULL;
2500
    AVCodec *decoder = NULL, *best_decoder = NULL;
2501

    
2502
    if (related_stream >= 0 && wanted_stream_nb < 0) {
2503
        AVProgram *p = find_program_from_stream(ic, related_stream);
2504
        if (p) {
2505
            program = p->stream_index;
2506
            nb_streams = p->nb_stream_indexes;
2507
        }
2508
    }
2509
    for (i = 0; i < nb_streams; i++) {
2510
        AVStream *st = ic->streams[program ? program[i] : i];
2511
        AVCodecContext *avctx = st->codec;
2512
        if (avctx->codec_type != type)
2513
            continue;
2514
        if (wanted_stream_nb >= 0 && stream_number++ != wanted_stream_nb)
2515
            continue;
2516
        if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
2517
            continue;
2518
        if (decoder_ret) {
2519
            decoder = avcodec_find_decoder(ic->streams[i]->codec->codec_id);
2520
            if (!decoder) {
2521
                if (ret < 0)
2522
                    ret = AVERROR_DECODER_NOT_FOUND;
2523
                continue;
2524
            }
2525
        }
2526
        if (best_count >= st->codec_info_nb_frames)
2527
            continue;
2528
        best_count = st->codec_info_nb_frames;
2529
        ret = program ? program[i] : i;
2530
        best_decoder = decoder;
2531
        if (program && i == nb_streams - 1 && ret < 0) {
2532
            program = NULL;
2533
            nb_streams = ic->nb_streams;
2534
            i = 0; /* no related stream found, try again with everything */
2535
        }
2536
    }
2537
    if (decoder_ret)
2538
        *decoder_ret = best_decoder;
2539
    return ret;
2540
}
2541

    
2542
/*******************************************************/
2543

    
2544
int av_read_play(AVFormatContext *s)
2545
{
2546
    if (s->iformat->read_play)
2547
        return s->iformat->read_play(s);
2548
    if (s->pb)
2549
        return avio_pause(s->pb, 0);
2550
    return AVERROR(ENOSYS);
2551
}
2552

    
2553
int av_read_pause(AVFormatContext *s)
2554
{
2555
    if (s->iformat->read_pause)
2556
        return s->iformat->read_pause(s);
2557
    if (s->pb)
2558
        return avio_pause(s->pb, 1);
2559
    return AVERROR(ENOSYS);
2560
}
2561

    
2562
void av_close_input_stream(AVFormatContext *s)
2563
{
2564
    flush_packet_queue(s);
2565
    if (s->iformat->read_close)
2566
        s->iformat->read_close(s);
2567
    avformat_free_context(s);
2568
}
2569

    
2570
void avformat_free_context(AVFormatContext *s)
2571
{
2572
    int i;
2573
    AVStream *st;
2574

    
2575
    for(i=0;i<s->nb_streams;i++) {
2576
        /* free all data in a stream component */
2577
        st = s->streams[i];
2578
        if (st->parser) {
2579
            av_parser_close(st->parser);
2580
            av_free_packet(&st->cur_pkt);
2581
        }
2582
        av_metadata_free(&st->metadata);
2583
        av_free(st->index_entries);
2584
        av_free(st->codec->extradata);
2585
        av_free(st->codec->subtitle_header);
2586
        av_free(st->codec);
2587
        av_free(st->priv_data);
2588
        av_free(st->info);
2589
        av_free(st);
2590
    }
2591
    for(i=s->nb_programs-1; i>=0; i--) {
2592
        av_metadata_free(&s->programs[i]->metadata);
2593
        av_freep(&s->programs[i]->stream_index);
2594
        av_freep(&s->programs[i]);
2595
    }
2596
    av_freep(&s->programs);
2597
    av_freep(&s->priv_data);
2598
    while(s->nb_chapters--) {
2599
        av_metadata_free(&s->chapters[s->nb_chapters]->metadata);
2600
        av_free(s->chapters[s->nb_chapters]);
2601
    }
2602
    av_freep(&s->chapters);
2603
    av_metadata_free(&s->metadata);
2604
    av_freep(&s->key);
2605
    av_free(s);
2606
}
2607

    
2608
void av_close_input_file(AVFormatContext *s)
2609
{
2610
    AVIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
2611
    av_close_input_stream(s);
2612
    if (pb)
2613
        avio_close(pb);
2614
}
2615

    
2616
AVStream *av_new_stream(AVFormatContext *s, int id)
2617
{
2618
    AVStream *st;
2619
    int i;
2620
    AVStream **streams;
2621

    
2622
    if (s->nb_streams >= INT_MAX/sizeof(*streams))
2623
        return NULL;
2624
    streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
2625
    if (!streams)
2626
        return NULL;
2627
    s->streams = streams;
2628

    
2629
    st = av_mallocz(sizeof(AVStream));
2630
    if (!st)
2631
        return NULL;
2632
    if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2633
        av_free(st);
2634
        return NULL;
2635
    }
2636

    
2637
    st->codec= avcodec_alloc_context();
2638
    if (s->iformat) {
2639
        /* no default bitrate if decoding */
2640
        st->codec->bit_rate = 0;
2641
    }
2642
    st->index = s->nb_streams;
2643
    st->id = id;
2644
    st->start_time = AV_NOPTS_VALUE;
2645
    st->duration = AV_NOPTS_VALUE;
2646
        /* we set the current DTS to 0 so that formats without any timestamps
2647
           but durations get some timestamps, formats with some unknown
2648
           timestamps have their first few packets buffered and the
2649
           timestamps corrected before they are returned to the user */
2650
    st->cur_dts = 0;
2651
    st->first_dts = AV_NOPTS_VALUE;
2652
    st->probe_packets = MAX_PROBE_PACKETS;
2653

    
2654
    /* default pts setting is MPEG-like */
2655
    av_set_pts_info(st, 33, 1, 90000);
2656
    st->last_IP_pts = AV_NOPTS_VALUE;
2657
    for(i=0; i<MAX_REORDER_DELAY+1; i++)
2658
        st->pts_buffer[i]= AV_NOPTS_VALUE;
2659
    st->reference_dts = AV_NOPTS_VALUE;
2660

    
2661
    st->sample_aspect_ratio = (AVRational){0,1};
2662

    
2663
    s->streams[s->nb_streams++] = st;
2664
    return st;
2665
}
2666

    
2667
AVProgram *av_new_program(AVFormatContext *ac, int id)
2668
{
2669
    AVProgram *program=NULL;
2670
    int i;
2671

    
2672
#ifdef DEBUG_SI
2673
    av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id);
2674
#endif
2675

    
2676
    for(i=0; i<ac->nb_programs; i++)
2677
        if(ac->programs[i]->id == id)
2678
            program = ac->programs[i];
2679

    
2680
    if(!program){
2681
        program = av_mallocz(sizeof(AVProgram));
2682
        if (!program)
2683
            return NULL;
2684
        dynarray_add(&ac->programs, &ac->nb_programs, program);
2685
        program->discard = AVDISCARD_NONE;
2686
    }
2687
    program->id = id;
2688

    
2689
    return program;
2690
}
2691

    
2692
AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2693
{
2694
    AVChapter *chapter = NULL;
2695
    int i;
2696

    
2697
    for(i=0; i<s->nb_chapters; i++)
2698
        if(s->chapters[i]->id == id)
2699
            chapter = s->chapters[i];
2700

    
2701
    if(!chapter){
2702
        chapter= av_mallocz(sizeof(AVChapter));
2703
        if(!chapter)
2704
            return NULL;
2705
        dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2706
    }
2707
    av_metadata_set2(&chapter->metadata, "title", title, 0);
2708
    chapter->id    = id;
2709
    chapter->time_base= time_base;
2710
    chapter->start = start;
2711
    chapter->end   = end;
2712

    
2713
    return chapter;
2714
}
2715

    
2716
/************************************************************/
2717
/* output media file */
2718

    
2719
int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2720
{
2721
    int ret;
2722

    
2723
    if (s->oformat->priv_data_size > 0) {
2724
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
2725
        if (!s->priv_data)
2726
            return AVERROR(ENOMEM);
2727
        if (s->oformat->priv_class) {
2728
            *(const AVClass**)s->priv_data= s->oformat->priv_class;
2729
            av_opt_set_defaults(s->priv_data);
2730
        }
2731
    } else
2732
        s->priv_data = NULL;
2733

    
2734
    if (s->oformat->set_parameters) {
2735
        ret = s->oformat->set_parameters(s, ap);
2736
        if (ret < 0)
2737
            return ret;
2738
    }
2739
    return 0;
2740
}
2741

    
2742
static int validate_codec_tag(AVFormatContext *s, AVStream *st)
2743
{
2744
    const AVCodecTag *avctag;
2745
    int n;
2746
    enum CodecID id = CODEC_ID_NONE;
2747
    unsigned int tag = 0;
2748

    
2749
    /**
2750
     * Check that tag + id is in the table
2751
     * If neither is in the table -> OK
2752
     * If tag is in the table with another id -> FAIL
2753
     * If id is in the table with another tag -> FAIL unless strict < normal
2754
     */
2755
    for (n = 0; s->oformat->codec_tag[n]; n++) {
2756
        avctag = s->oformat->codec_tag[n];
2757
        while (avctag->id != CODEC_ID_NONE) {
2758
            if (ff_toupper4(avctag->tag) == ff_toupper4(st->codec->codec_tag)) {
2759
                id = avctag->id;
2760
                if (id == st->codec->codec_id)
2761
                    return 1;
2762
            }
2763
            if (avctag->id == st->codec->codec_id)
2764
                tag = avctag->tag;
2765
            avctag++;
2766
        }
2767
    }
2768
    if (id != CODEC_ID_NONE)
2769
        return 0;
2770
    if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
2771
        return 0;
2772
    return 1;
2773
}
2774

    
2775
int av_write_header(AVFormatContext *s)
2776
{
2777
    int ret, i;
2778
    AVStream *st;
2779

    
2780
    // some sanity checks
2781
    if (s->nb_streams == 0 && !(s->oformat->flags & AVFMT_NOSTREAMS)) {
2782
        av_log(s, AV_LOG_ERROR, "no streams\n");
2783
        return AVERROR(EINVAL);
2784
    }
2785

    
2786
    for(i=0;i<s->nb_streams;i++) {
2787
        st = s->streams[i];
2788

    
2789
        switch (st->codec->codec_type) {
2790
        case AVMEDIA_TYPE_AUDIO:
2791
            if(st->codec->sample_rate<=0){
2792
                av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2793
                return AVERROR(EINVAL);
2794
            }
2795
            if(!st->codec->block_align)
2796
                st->codec->block_align = st->codec->channels *
2797
                    av_get_bits_per_sample(st->codec->codec_id) >> 3;
2798
            break;
2799
        case AVMEDIA_TYPE_VIDEO:
2800
            if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2801
                av_log(s, AV_LOG_ERROR, "time base not set\n");
2802
                return AVERROR(EINVAL);
2803
            }
2804
            if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){
2805
                av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2806
                return AVERROR(EINVAL);
2807
            }
2808
            if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)){
2809
                av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");
2810
                return AVERROR(EINVAL);
2811
            }
2812
            break;
2813
        }
2814

    
2815
        if(s->oformat->codec_tag){
2816
            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)){
2817
                //the current rawvideo encoding system ends up setting the wrong codec_tag for avi, we override it here
2818
                st->codec->codec_tag= 0;
2819
            }
2820
            if(st->codec->codec_tag){
2821
                if (!validate_codec_tag(s, st)) {
2822
                    char tagbuf[32];
2823
                    av_get_codec_tag_string(tagbuf, sizeof(tagbuf), st->codec->codec_tag);
2824
                    av_log(s, AV_LOG_ERROR,
2825
                           "Tag %s/0x%08x incompatible with output codec id '%d'\n",
2826
                           tagbuf, st->codec->codec_tag, st->codec->codec_id);
2827
                    return AVERROR_INVALIDDATA;
2828
                }
2829
            }else
2830
                st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
2831
        }
2832

    
2833
        if(s->oformat->flags & AVFMT_GLOBALHEADER &&
2834
            !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))
2835
          av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);
2836
    }
2837

    
2838
    if (!s->priv_data && s->oformat->priv_data_size > 0) {
2839
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
2840
        if (!s->priv_data)
2841
            return AVERROR(ENOMEM);
2842
    }
2843

    
2844
    /* set muxer identification string */
2845
    if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
2846
        av_metadata_set2(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
2847
    }
2848

    
2849
    if(s->oformat->write_header){
2850
        ret = s->oformat->write_header(s);
2851
        if (ret < 0)
2852
            return ret;
2853
    }
2854

    
2855
    /* init PTS generation */
2856
    for(i=0;i<s->nb_streams;i++) {
2857
        int64_t den = AV_NOPTS_VALUE;
2858
        st = s->streams[i];
2859

    
2860
        switch (st->codec->codec_type) {
2861
        case AVMEDIA_TYPE_AUDIO:
2862
            den = (int64_t)st->time_base.num * st->codec->sample_rate;
2863
            break;
2864
        case AVMEDIA_TYPE_VIDEO:
2865
            den = (int64_t)st->time_base.num * st->codec->time_base.den;
2866
            break;
2867
        default:
2868
            break;
2869
        }
2870
        if (den != AV_NOPTS_VALUE) {
2871
            if (den <= 0)
2872
                return AVERROR_INVALIDDATA;
2873
            av_frac_init(&st->pts, 0, 0, den);
2874
        }
2875
    }
2876
    return 0;
2877
}
2878

    
2879
//FIXME merge with compute_pkt_fields
2880
static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){
2881
    int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
2882
    int num, den, frame_size, i;
2883

    
2884
    av_dlog(s, "av_write_frame: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n",
2885
            pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
2886

    
2887
/*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2888
        return -1;*/
2889

    
2890
    /* duration field */
2891
    if (pkt->duration == 0) {
2892
        compute_frame_duration(&num, &den, st, NULL, pkt);
2893
        if (den && num) {
2894
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
2895
        }
2896
    }
2897

    
2898
    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
2899
        pkt->pts= pkt->dts;
2900

    
2901
    //XXX/FIXME this is a temporary hack until all encoders output pts
2902
    if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
2903
        pkt->dts=
2904
//        pkt->pts= st->cur_dts;
2905
        pkt->pts= st->pts.val;
2906
    }
2907

    
2908
    //calculate dts from pts
2909
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
2910
        st->pts_buffer[0]= pkt->pts;
2911
        for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
2912
            st->pts_buffer[i]= pkt->pts + (i-delay-1) * pkt->duration;
2913
        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
2914
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
2915

    
2916
        pkt->dts= st->pts_buffer[0];
2917
    }
2918

    
2919
    if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2920
        av_log(s, AV_LOG_ERROR,
2921
               "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %"PRId64" >= %"PRId64"\n",
2922
               st->index, st->cur_dts, pkt->dts);
2923
        return -1;
2924
    }
2925
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2926
        av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
2927
        return -1;
2928
    }
2929

    
2930
//    av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
2931
    st->cur_dts= pkt->dts;
2932
    st->pts.val= pkt->dts;
2933

    
2934
    /* update pts */
2935
    switch (st->codec->codec_type) {
2936
    case AVMEDIA_TYPE_AUDIO:
2937
        frame_size = get_audio_frame_size(st->codec, pkt->size);
2938

    
2939
        /* HACK/FIXME, we skip the initial 0 size packets as they are most
2940
           likely equal to the encoder delay, but it would be better if we
2941
           had the real timestamps from the encoder */
2942
        if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2943
            av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2944
        }
2945
        break;
2946
    case AVMEDIA_TYPE_VIDEO:
2947
        av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
2948
        break;
2949
    default:
2950
        break;
2951
    }
2952
    return 0;
2953
}
2954

    
2955
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2956
{
2957
    int ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
2958

    
2959
    if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2960
        return ret;
2961

    
2962
    ret= s->oformat->write_packet(s, pkt);
2963
    return ret;
2964
}
2965

    
2966
void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
2967
                              int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
2968
{
2969
    AVPacketList **next_point, *this_pktl;
2970

    
2971
    this_pktl = av_mallocz(sizeof(AVPacketList));
2972
    this_pktl->pkt= *pkt;
2973
    pkt->destruct= NULL;             // do not free original but only the copy
2974
    av_dup_packet(&this_pktl->pkt);  // duplicate the packet if it uses non-alloced memory
2975

    
2976
    if(s->streams[pkt->stream_index]->last_in_packet_buffer){
2977
        next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
2978
    }else
2979
        next_point = &s->packet_buffer;
2980

    
2981
    if(*next_point){
2982
        if(compare(s, &s->packet_buffer_end->pkt, pkt)){
2983
            while(!compare(s, &(*next_point)->pkt, pkt)){
2984
                next_point= &(*next_point)->next;
2985
            }
2986
            goto next_non_null;
2987
        }else{
2988
            next_point = &(s->packet_buffer_end->next);
2989
        }
2990
    }
2991
    assert(!*next_point);
2992

    
2993
    s->packet_buffer_end= this_pktl;
2994
next_non_null:
2995

    
2996
    this_pktl->next= *next_point;
2997

    
2998
    s->streams[pkt->stream_index]->last_in_packet_buffer=
2999
    *next_point= this_pktl;
3000
}
3001

    
3002
static int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
3003
{
3004
    AVStream *st = s->streams[ pkt ->stream_index];
3005
    AVStream *st2= s->streams[ next->stream_index];
3006
    int64_t a= st2->time_base.num * (int64_t)st ->time_base.den;
3007
    int64_t b= st ->time_base.num * (int64_t)st2->time_base.den;
3008
    int64_t dts1 = av_rescale_rnd(pkt->dts, b, a, AV_ROUND_DOWN);
3009
    if (dts1 == next->dts)
3010
        return pkt->stream_index < next->stream_index;
3011
    return dts1 < next->dts;
3012
}
3013

    
3014
int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
3015
    AVPacketList *pktl;
3016
    int stream_count=0;
3017
    int i;
3018

    
3019
    if(pkt){
3020
        ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
3021
    }
3022

    
3023
    for(i=0; i < s->nb_streams; i++)
3024
        stream_count+= !!s->streams[i]->last_in_packet_buffer;
3025

    
3026
    if(stream_count && (s->nb_streams == stream_count || flush)){
3027
        pktl= s->packet_buffer;
3028
        *out= pktl->pkt;
3029

    
3030
        s->packet_buffer= pktl->next;
3031
        if(!s->packet_buffer)
3032
            s->packet_buffer_end= NULL;
3033

    
3034
        if(s->streams[out->stream_index]->last_in_packet_buffer == pktl)
3035
            s->streams[out->stream_index]->last_in_packet_buffer= NULL;
3036
        av_freep(&pktl);
3037
        return 1;
3038
    }else{
3039
        av_init_packet(out);
3040
        return 0;
3041
    }
3042
}
3043

    
3044
/**
3045
 * Interleave an AVPacket correctly so it can be muxed.
3046
 * @param out the interleaved packet will be output here
3047
 * @param in the input packet
3048
 * @param flush 1 if no further packets are available as input and all
3049
 *              remaining packets should be output
3050
 * @return 1 if a packet was output, 0 if no packet could be output,
3051
 *         < 0 if an error occurred
3052
 */
3053
static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
3054
    if(s->oformat->interleave_packet)
3055
        return s->oformat->interleave_packet(s, out, in, flush);
3056
    else
3057
        return av_interleave_packet_per_dts(s, out, in, flush);
3058
}
3059

    
3060
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
3061
    AVStream *st= s->streams[ pkt->stream_index];
3062
    int ret;
3063

    
3064
    //FIXME/XXX/HACK drop zero sized packets
3065
    if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size==0)
3066
        return 0;
3067

    
3068
    av_dlog(s, "av_interleaved_write_frame size:%d dts:%"PRId64" pts:%"PRId64"\n",
3069
            pkt->size, pkt->dts, pkt->pts);
3070
    if((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3071
        return ret;
3072

    
3073
    if(pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3074
        return AVERROR(EINVAL);
3075

    
3076
    for(;;){
3077
        AVPacket opkt;
3078
        int ret= av_interleave_packet(s, &opkt, pkt, 0);
3079
        if(ret<=0) //FIXME cleanup needed for ret<0 ?
3080
            return ret;
3081

    
3082
        ret= s->oformat->write_packet(s, &opkt);
3083

    
3084
        av_free_packet(&opkt);
3085
        pkt= NULL;
3086

    
3087
        if(ret<0)
3088
            return ret;
3089
    }
3090
}
3091

    
3092
int av_write_trailer(AVFormatContext *s)
3093
{
3094
    int ret, i;
3095

    
3096
    for(;;){
3097
        AVPacket pkt;
3098
        ret= av_interleave_packet(s, &pkt, NULL, 1);
3099
        if(ret<0) //FIXME cleanup needed for ret<0 ?
3100
            goto fail;
3101
        if(!ret)
3102
            break;
3103

    
3104
        ret= s->oformat->write_packet(s, &pkt);
3105

    
3106
        av_free_packet(&pkt);
3107

    
3108
        if(ret<0)
3109
            goto fail;
3110
    }
3111

    
3112
    if(s->oformat->write_trailer)
3113
        ret = s->oformat->write_trailer(s);
3114
fail:
3115
    for(i=0;i<s->nb_streams;i++) {
3116
        av_freep(&s->streams[i]->priv_data);
3117
        av_freep(&s->streams[i]->index_entries);
3118
    }
3119
    av_freep(&s->priv_data);
3120
    return ret;
3121
}
3122

    
3123
void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
3124
{
3125
    int i, j;
3126
    AVProgram *program=NULL;
3127
    void *tmp;
3128

    
3129
    if (idx >= ac->nb_streams) {
3130
        av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
3131
        return;
3132
    }
3133

    
3134
    for(i=0; i<ac->nb_programs; i++){
3135
        if(ac->programs[i]->id != progid)
3136
            continue;
3137
        program = ac->programs[i];
3138
        for(j=0; j<program->nb_stream_indexes; j++)
3139
            if(program->stream_index[j] == idx)
3140
                return;
3141

    
3142
        tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
3143
        if(!tmp)
3144
            return;
3145
        program->stream_index = tmp;
3146
        program->stream_index[program->nb_stream_indexes++] = idx;
3147
        return;
3148
    }
3149
}
3150

    
3151
static void print_fps(double d, const char *postfix){
3152
    uint64_t v= lrintf(d*100);
3153
    if     (v% 100      ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
3154
    else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
3155
    else                  av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
3156
}
3157

    
3158
static void dump_metadata(void *ctx, AVMetadata *m, const char *indent)
3159
{
3160
    if(m && !(m->count == 1 && av_metadata_get(m, "language", NULL, 0))){
3161
        AVMetadataTag *tag=NULL;
3162

    
3163
        av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
3164
        while((tag=av_metadata_get(m, "", tag, AV_METADATA_IGNORE_SUFFIX))) {
3165
            if(strcmp("language", tag->key))
3166
                av_log(ctx, AV_LOG_INFO, "%s  %-16s: %s\n", indent, tag->key, tag->value);
3167
        }
3168
    }
3169
}
3170

    
3171
/* "user interface" functions */
3172
static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
3173
{
3174
    char buf[256];
3175
    int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
3176
    AVStream *st = ic->streams[i];
3177
    int g = av_gcd(st->time_base.num, st->time_base.den);
3178
    AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL, 0);
3179
    avcodec_string(buf, sizeof(buf), st->codec, is_output);
3180
    av_log(NULL, AV_LOG_INFO, "    Stream #%d.%d", index, i);
3181
    /* the pid is an important information, so we display it */
3182
    /* XXX: add a generic system */
3183
    if (flags & AVFMT_SHOW_IDS)
3184
        av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
3185
    if (lang)
3186
        av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
3187
    av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
3188
    av_log(NULL, AV_LOG_INFO, ": %s", buf);
3189
    if (st->sample_aspect_ratio.num && // default
3190
        av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
3191
        AVRational display_aspect_ratio;
3192
        av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
3193
                  st->codec->width*st->sample_aspect_ratio.num,
3194
                  st->codec->height*st->sample_aspect_ratio.den,
3195
                  1024*1024);
3196
        av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
3197
                 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
3198
                 display_aspect_ratio.num, display_aspect_ratio.den);
3199
    }
3200
    if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
3201
        if(st->avg_frame_rate.den && st->avg_frame_rate.num)
3202
            print_fps(av_q2d(st->avg_frame_rate), "fps");
3203
        if(st->r_frame_rate.den && st->r_frame_rate.num)
3204
            print_fps(av_q2d(st->r_frame_rate), "tbr");
3205
        if(st->time_base.den && st->time_base.num)
3206
            print_fps(1/av_q2d(st->time_base), "tbn");
3207
        if(st->codec->time_base.den && st->codec->time_base.num)
3208
            print_fps(1/av_q2d(st->codec->time_base), "tbc");
3209
    }
3210
    if (st->disposition & AV_DISPOSITION_DEFAULT)
3211
        av_log(NULL, AV_LOG_INFO, " (default)");
3212
    if (st->disposition & AV_DISPOSITION_DUB)
3213
        av_log(NULL, AV_LOG_INFO, " (dub)");
3214
    if (st->disposition & AV_DISPOSITION_ORIGINAL)
3215
        av_log(NULL, AV_LOG_INFO, " (original)");
3216
    if (st->disposition & AV_DISPOSITION_COMMENT)
3217
        av_log(NULL, AV_LOG_INFO, " (comment)");
3218
    if (st->disposition & AV_DISPOSITION_LYRICS)
3219
        av_log(NULL, AV_LOG_INFO, " (lyrics)");
3220
    if (st->disposition & AV_DISPOSITION_KARAOKE)
3221
        av_log(NULL, AV_LOG_INFO, " (karaoke)");
3222
    if (st->disposition & AV_DISPOSITION_FORCED)
3223
        av_log(NULL, AV_LOG_INFO, " (forced)");
3224
    if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
3225
        av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
3226
    if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
3227
        av_log(NULL, AV_LOG_INFO, " (visual impaired)");
3228
    if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
3229
        av_log(NULL, AV_LOG_INFO, " (clean effects)");
3230
    av_log(NULL, AV_LOG_INFO, "\n");
3231
    dump_metadata(NULL, st->metadata, "    ");
3232
}
3233

    
3234
#if FF_API_DUMP_FORMAT
3235
void dump_format(AVFormatContext *ic,
3236
                 int index,
3237
                 const char *url,
3238
                 int is_output)
3239
{
3240
    av_dump_format(ic, index, url, is_output);
3241
}
3242
#endif
3243

    
3244
void av_dump_format(AVFormatContext *ic,
3245
                    int index,
3246
                    const char *url,
3247
                    int is_output)
3248
{
3249
    int i;
3250
    uint8_t *printed = av_mallocz(ic->nb_streams);
3251
    if (ic->nb_streams && !printed)
3252
        return;
3253

    
3254
    av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
3255
            is_output ? "Output" : "Input",
3256
            index,
3257
            is_output ? ic->oformat->name : ic->iformat->name,
3258
            is_output ? "to" : "from", url);
3259
    dump_metadata(NULL, ic->metadata, "  ");
3260
    if (!is_output) {
3261
        av_log(NULL, AV_LOG_INFO, "  Duration: ");
3262
        if (ic->duration != AV_NOPTS_VALUE) {
3263
            int hours, mins, secs, us;
3264
            secs = ic->duration / AV_TIME_BASE;
3265
            us = ic->duration % AV_TIME_BASE;
3266
            mins = secs / 60;
3267
            secs %= 60;
3268
            hours = mins / 60;
3269
            mins %= 60;
3270
            av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
3271
                   (100 * us) / AV_TIME_BASE);
3272
        } else {
3273
            av_log(NULL, AV_LOG_INFO, "N/A");
3274
        }
3275
        if (ic->start_time != AV_NOPTS_VALUE) {
3276
            int secs, us;
3277
            av_log(NULL, AV_LOG_INFO, ", start: ");
3278
            secs = ic->start_time / AV_TIME_BASE;
3279
            us = abs(ic->start_time % AV_TIME_BASE);
3280
            av_log(NULL, AV_LOG_INFO, "%d.%06d",
3281
                   secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
3282
        }
3283
        av_log(NULL, AV_LOG_INFO, ", bitrate: ");
3284
        if (ic->bit_rate) {
3285
            av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
3286
        } else {
3287
            av_log(NULL, AV_LOG_INFO, "N/A");
3288
        }
3289
        av_log(NULL, AV_LOG_INFO, "\n");
3290
    }
3291
    for (i = 0; i < ic->nb_chapters; i++) {
3292
        AVChapter *ch = ic->chapters[i];
3293
        av_log(NULL, AV_LOG_INFO, "    Chapter #%d.%d: ", index, i);
3294
        av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
3295
        av_log(NULL, AV_LOG_INFO, "end %f\n",   ch->end   * av_q2d(ch->time_base));
3296

    
3297
        dump_metadata(NULL, ch->metadata, "    ");
3298
    }
3299
    if(ic->nb_programs) {
3300
        int j, k, total = 0;
3301
        for(j=0; j<ic->nb_programs; j++) {
3302
            AVMetadataTag *name = av_metadata_get(ic->programs[j]->metadata,
3303
                                                  "name", NULL, 0);
3304
            av_log(NULL, AV_LOG_INFO, "  Program %d %s\n", ic->programs[j]->id,
3305
                   name ? name->value : "");
3306
            dump_metadata(NULL, ic->programs[j]->metadata, "    ");
3307
            for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
3308
                dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
3309
                printed[ic->programs[j]->stream_index[k]] = 1;
3310
            }
3311
            total += ic->programs[j]->nb_stream_indexes;
3312
        }
3313
        if (total < ic->nb_streams)
3314
            av_log(NULL, AV_LOG_INFO, "  No Program\n");
3315
    }
3316
    for(i=0;i<ic->nb_streams;i++)
3317
        if (!printed[i])
3318
            dump_stream_format(ic, i, index, is_output);
3319

    
3320
    av_free(printed);
3321
}
3322

    
3323
int64_t av_gettime(void)
3324
{
3325
    struct timeval tv;
3326
    gettimeofday(&tv,NULL);
3327
    return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
3328
}
3329

    
3330
uint64_t ff_ntp_time(void)
3331
{
3332
  return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
3333
}
3334

    
3335
#if FF_API_PARSE_DATE
3336
#include "libavutil/parseutils.h"
3337

    
3338
int64_t parse_date(const char *timestr, int duration)
3339
{
3340
    int64_t timeval;
3341
    av_parse_time(&timeval, timestr, duration);
3342
    return timeval;
3343
}
3344
#endif
3345

    
3346
#if FF_API_FIND_INFO_TAG
3347
#include "libavutil/parseutils.h"
3348

    
3349
int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
3350
{
3351
    return av_find_info_tag(arg, arg_size, tag1, info);
3352
}
3353
#endif
3354

    
3355
int av_get_frame_filename(char *buf, int buf_size,
3356
                          const char *path, int number)
3357
{
3358
    const char *p;
3359
    char *q, buf1[20], c;
3360
    int nd, len, percentd_found;
3361

    
3362
    q = buf;
3363
    p = path;
3364
    percentd_found = 0;
3365
    for(;;) {
3366
        c = *p++;
3367
        if (c == '\0')
3368
            break;
3369
        if (c == '%') {
3370
            do {
3371
                nd = 0;
3372
                while (isdigit(*p)) {
3373
                    nd = nd * 10 + *p++ - '0';
3374
                }
3375
                c = *p++;
3376
            } while (isdigit(c));
3377

    
3378
            switch(c) {
3379
            case '%':
3380
                goto addchar;
3381
            case 'd':
3382
                if (percentd_found)
3383
                    goto fail;
3384
                percentd_found = 1;
3385
                snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3386
                len = strlen(buf1);
3387
                if ((q - buf + len) > buf_size - 1)
3388
                    goto fail;
3389
                memcpy(q, buf1, len);
3390
                q += len;
3391
                break;
3392
            default:
3393
                goto fail;
3394
            }
3395
        } else {
3396
        addchar:
3397
            if ((q - buf) < buf_size - 1)
3398
                *q++ = c;
3399
        }
3400
    }
3401
    if (!percentd_found)
3402
        goto fail;
3403
    *q = '\0';
3404
    return 0;
3405
 fail:
3406
    *q = '\0';
3407
    return -1;
3408
}
3409

    
3410
static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
3411
{
3412
    int len, i, j, c;
3413
#undef fprintf
3414
#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3415

    
3416
    for(i=0;i<size;i+=16) {
3417
        len = size - i;
3418
        if (len > 16)
3419
            len = 16;
3420
        PRINT("%08x ", i);
3421
        for(j=0;j<16;j++) {
3422
            if (j < len)
3423
                PRINT(" %02x", buf[i+j]);
3424
            else
3425
                PRINT("   ");
3426
        }
3427
        PRINT(" ");
3428
        for(j=0;j<len;j++) {
3429
            c = buf[i+j];
3430
            if (c < ' ' || c > '~')
3431
                c = '.';
3432
            PRINT("%c", c);
3433
        }
3434
        PRINT("\n");
3435
    }
3436
#undef PRINT
3437
}
3438

    
3439
void av_hex_dump(FILE *f, uint8_t *buf, int size)
3440
{
3441
    hex_dump_internal(NULL, f, 0, buf, size);
3442
}
3443

    
3444
void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
3445
{
3446
    hex_dump_internal(avcl, NULL, level, buf, size);
3447
}
3448

    
3449
static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
3450
{
3451
#undef fprintf
3452
#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3453
    PRINT("stream #%d:\n", pkt->stream_index);
3454
    PRINT("  keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
3455
    PRINT("  duration=%0.3f\n", pkt->duration * av_q2d(time_base));
3456
    /* DTS is _always_ valid after av_read_frame() */
3457
    PRINT("  dts=");
3458
    if (pkt->dts == AV_NOPTS_VALUE)
3459
        PRINT("N/A");
3460
    else
3461
        PRINT("%0.3f", pkt->dts * av_q2d(time_base));
3462
    /* PTS may not be known if B-frames are present. */
3463
    PRINT("  pts=");
3464
    if (pkt->pts == AV_NOPTS_VALUE)
3465
        PRINT("N/A");
3466
    else
3467
        PRINT("%0.3f", pkt->pts * av_q2d(time_base));
3468
    PRINT("\n");
3469
    PRINT("  size=%d\n", pkt->size);
3470
#undef PRINT
3471
    if (dump_payload)
3472
        av_hex_dump(f, pkt->data, pkt->size);
3473
}
3474

    
3475
#if FF_API_PKT_DUMP
3476
void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3477
{
3478
    AVRational tb = { 1, AV_TIME_BASE };
3479
    pkt_dump_internal(NULL, f, 0, pkt, dump_payload, tb);
3480
}
3481
#endif
3482

    
3483
void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
3484
{
3485
    pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
3486
}
3487

    
3488
#if FF_API_PKT_DUMP
3489
void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
3490
{
3491
    AVRational tb = { 1, AV_TIME_BASE };
3492
    pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, tb);
3493
}
3494
#endif
3495

    
3496
void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
3497
                      AVStream *st)
3498
{
3499
    pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
3500
}
3501

    
3502
void av_url_split(char *proto, int proto_size,
3503
                  char *authorization, int authorization_size,
3504
                  char *hostname, int hostname_size,
3505
                  int *port_ptr,
3506
                  char *path, int path_size,
3507
                  const char *url)
3508
{
3509
    const char *p, *ls, *at, *col, *brk;
3510

    
3511
    if (port_ptr)               *port_ptr = -1;
3512
    if (proto_size > 0)         proto[0] = 0;
3513
    if (authorization_size > 0) authorization[0] = 0;
3514
    if (hostname_size > 0)      hostname[0] = 0;
3515
    if (path_size > 0)          path[0] = 0;
3516

    
3517
    /* parse protocol */
3518
    if ((p = strchr(url, ':'))) {
3519
        av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3520
        p++; /* skip ':' */
3521
        if (*p == '/') p++;
3522
        if (*p == '/') p++;
3523
    } else {
3524
        /* no protocol means plain filename */
3525
        av_strlcpy(path, url, path_size);
3526
        return;
3527
    }
3528

    
3529
    /* separate path from hostname */
3530
    ls = strchr(p, '/');
3531
    if(!ls)
3532
        ls = strchr(p, '?');
3533
    if(ls)
3534
        av_strlcpy(path, ls, path_size);
3535
    else
3536
        ls = &p[strlen(p)]; // XXX
3537

    
3538
    /* the rest is hostname, use that to parse auth/port */
3539
    if (ls != p) {
3540
        /* authorization (user[:pass]@hostname) */
3541
        if ((at = strchr(p, '@')) && at < ls) {
3542
            av_strlcpy(authorization, p,
3543
                       FFMIN(authorization_size, at + 1 - p));
3544
            p = at + 1; /* skip '@' */
3545
        }
3546

    
3547
        if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3548
            /* [host]:port */
3549
            av_strlcpy(hostname, p + 1,
3550
                       FFMIN(hostname_size, brk - p));
3551
            if (brk[1] == ':' && port_ptr)
3552
                *port_ptr = atoi(brk + 2);
3553
        } else if ((col = strchr(p, ':')) && col < ls) {
3554
            av_strlcpy(hostname, p,
3555
                       FFMIN(col + 1 - p, hostname_size));
3556
            if (port_ptr) *port_ptr = atoi(col + 1);
3557
        } else
3558
            av_strlcpy(hostname, p,
3559
                       FFMIN(ls + 1 - p, hostname_size));
3560
    }
3561
}
3562

    
3563
char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3564
{
3565
    int i;
3566
    static const char hex_table_uc[16] = { '0', '1', '2', '3',
3567
                                           '4', '5', '6', '7',
3568
                                           '8', '9', 'A', 'B',
3569
                                           'C', 'D', 'E', 'F' };
3570
    static const char hex_table_lc[16] = { '0', '1', '2', '3',
3571
                                           '4', '5', '6', '7',
3572
                                           '8', '9', 'a', 'b',
3573
                                           'c', 'd', 'e', 'f' };
3574
    const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3575

    
3576
    for(i = 0; i < s; i++) {
3577
        buff[i * 2]     = hex_table[src[i] >> 4];
3578
        buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3579
    }
3580

    
3581
    return buff;
3582
}
3583

    
3584
int ff_hex_to_data(uint8_t *data, const char *p)
3585
{
3586
    int c, len, v;
3587

    
3588
    len = 0;
3589
    v = 1;
3590
    for (;;) {
3591
        p += strspn(p, SPACE_CHARS);
3592
        if (*p == '\0')
3593
            break;
3594
        c = toupper((unsigned char) *p++);
3595
        if (c >= '0' && c <= '9')
3596
            c = c - '0';
3597
        else if (c >= 'A' && c <= 'F')
3598
            c = c - 'A' + 10;
3599
        else
3600
            break;
3601
        v = (v << 4) | c;
3602
        if (v & 0x100) {
3603
            if (data)
3604
                data[len] = v;
3605
            len++;
3606
            v = 1;
3607
        }
3608
    }
3609
    return len;
3610
}
3611

    
3612
void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3613
                     unsigned int pts_num, unsigned int pts_den)
3614
{
3615
    AVRational new_tb;
3616
    if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
3617
        if(new_tb.num != pts_num)
3618
            av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
3619
    }else
3620
        av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3621

    
3622
    if(new_tb.num <= 0 || new_tb.den <= 0) {
3623
        av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
3624
        return;
3625
    }
3626
    s->time_base = new_tb;
3627
    s->pts_wrap_bits = pts_wrap_bits;
3628
}
3629

    
3630
int ff_url_join(char *str, int size, const char *proto,
3631
                const char *authorization, const char *hostname,
3632
                int port, const char *fmt, ...)
3633
{
3634
#if CONFIG_NETWORK
3635
    struct addrinfo hints, *ai;
3636
#endif
3637

    
3638
    str[0] = '\0';
3639
    if (proto)
3640
        av_strlcatf(str, size, "%s://", proto);
3641
    if (authorization && authorization[0])
3642
        av_strlcatf(str, size, "%s@", authorization);
3643
#if CONFIG_NETWORK && defined(AF_INET6)
3644
    /* Determine if hostname is a numerical IPv6 address,
3645
     * properly escape it within [] in that case. */
3646
    memset(&hints, 0, sizeof(hints));
3647
    hints.ai_flags = AI_NUMERICHOST;
3648
    if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
3649
        if (ai->ai_family == AF_INET6) {
3650
            av_strlcat(str, "[", size);
3651
            av_strlcat(str, hostname, size);
3652
            av_strlcat(str, "]", size);
3653
        } else {
3654
            av_strlcat(str, hostname, size);
3655
        }
3656
        freeaddrinfo(ai);
3657
    } else
3658
#endif
3659
        /* Not an IPv6 address, just output the plain string. */
3660
        av_strlcat(str, hostname, size);
3661

    
3662
    if (port >= 0)
3663
        av_strlcatf(str, size, ":%d", port);
3664
    if (fmt) {
3665
        va_list vl;
3666
        int len = strlen(str);
3667

    
3668
        va_start(vl, fmt);
3669
        vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
3670
        va_end(vl);
3671
    }
3672
    return strlen(str);
3673
}
3674

    
3675
int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
3676
                     AVFormatContext *src)
3677
{
3678
    AVPacket local_pkt;
3679

    
3680
    local_pkt = *pkt;
3681
    local_pkt.stream_index = dst_stream;
3682
    if (pkt->pts != AV_NOPTS_VALUE)
3683
        local_pkt.pts = av_rescale_q(pkt->pts,
3684
                                     src->streams[pkt->stream_index]->time_base,
3685
                                     dst->streams[dst_stream]->time_base);
3686
    if (pkt->dts != AV_NOPTS_VALUE)
3687
        local_pkt.dts = av_rescale_q(pkt->dts,
3688
                                     src->streams[pkt->stream_index]->time_base,
3689
                                     dst->streams[dst_stream]->time_base);
3690
    return av_write_frame(dst, &local_pkt);
3691
}
3692

    
3693
void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3694
                        void *context)
3695
{
3696
    const char *ptr = str;
3697

    
3698
    /* Parse key=value pairs. */
3699
    for (;;) {
3700
        const char *key;
3701
        char *dest = NULL, *dest_end;
3702
        int key_len, dest_len = 0;
3703

    
3704
        /* Skip whitespace and potential commas. */
3705
        while (*ptr && (isspace(*ptr) || *ptr == ','))
3706
            ptr++;
3707
        if (!*ptr)
3708
            break;
3709

    
3710
        key = ptr;
3711

    
3712
        if (!(ptr = strchr(key, '=')))
3713
            break;
3714
        ptr++;
3715
        key_len = ptr - key;
3716

    
3717
        callback_get_buf(context, key, key_len, &dest, &dest_len);
3718
        dest_end = dest + dest_len - 1;
3719

    
3720
        if (*ptr == '\"') {
3721
            ptr++;
3722
            while (*ptr && *ptr != '\"') {
3723
                if (*ptr == '\\') {
3724
                    if (!ptr[1])
3725
                        break;
3726
                    if (dest && dest < dest_end)
3727
                        *dest++ = ptr[1];
3728
                    ptr += 2;
3729
                } else {
3730
                    if (dest && dest < dest_end)
3731
                        *dest++ = *ptr;
3732
                    ptr++;
3733
                }
3734
            }
3735
            if (*ptr == '\"')
3736
                ptr++;
3737
        } else {
3738
            for (; *ptr && !(isspace(*ptr) || *ptr == ','); ptr++)
3739
                if (dest && dest < dest_end)
3740
                    *dest++ = *ptr;
3741
        }
3742
        if (dest)
3743
            *dest = 0;
3744
    }
3745
}
3746

    
3747
int ff_find_stream_index(AVFormatContext *s, int id)
3748
{
3749
    int i;
3750
    for (i = 0; i < s->nb_streams; i++) {
3751
        if (s->streams[i]->id == id)
3752
            return i;
3753
    }
3754
    return -1;
3755
}
3756

    
3757
void ff_make_absolute_url(char *buf, int size, const char *base,
3758
                          const char *rel)
3759
{
3760
    char *sep;
3761
    /* Absolute path, relative to the current server */
3762
    if (base && strstr(base, "://") && rel[0] == '/') {
3763
        if (base != buf)
3764
            av_strlcpy(buf, base, size);
3765
        sep = strstr(buf, "://");
3766
        if (sep) {
3767
            sep += 3;
3768
            sep = strchr(sep, '/');
3769
            if (sep)
3770
                *sep = '\0';
3771
        }
3772
        av_strlcat(buf, rel, size);
3773
        return;
3774
    }
3775
    /* If rel actually is an absolute url, just copy it */
3776
    if (!base || strstr(rel, "://") || rel[0] == '/') {
3777
        av_strlcpy(buf, rel, size);
3778
        return;
3779
    }
3780
    if (base != buf)
3781
        av_strlcpy(buf, base, size);
3782
    /* Remove the file name from the base url */
3783
    sep = strrchr(buf, '/');
3784
    if (sep)
3785
        sep[1] = '\0';
3786
    else
3787
        buf[0] = '\0';
3788
    while (av_strstart(rel, "../", NULL) && sep) {
3789
        /* Remove the path delimiter at the end */
3790
        sep[0] = '\0';
3791
        sep = strrchr(buf, '/');
3792
        /* If the next directory name to pop off is "..", break here */
3793
        if (!strcmp(sep ? &sep[1] : buf, "..")) {
3794
            /* Readd the slash we just removed */
3795
            av_strlcat(buf, "/", size);
3796
            break;
3797
        }
3798
        /* Cut off the directory name */
3799
        if (sep)
3800
            sep[1] = '\0';
3801
        else
3802
            buf[0] = '\0';
3803
        rel += 3;
3804
    }
3805
    av_strlcat(buf, rel, size);
3806
}