Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ 5d6e4c16

History | View | Annotate | Download (119 KB)

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

    
38
#undef NDEBUG
39
#include <assert.h>
40

    
41
/**
42
 * @file
43
 * various utility functions for use within FFmpeg
44
 */
45

    
46
unsigned avformat_version(void)
47
{
48
    return LIBAVFORMAT_VERSION_INT;
49
}
50

    
51
const char *avformat_configuration(void)
52
{
53
    return FFMPEG_CONFIGURATION;
54
}
55

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

    
62
/* fraction handling */
63

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

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

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

    
112
/** head of registered input format linked list */
113
#if !FF_API_FIRST_FORMAT
114
static
115
#endif
116
AVInputFormat *first_iformat = NULL;
117
/** head of registered output format linked list */
118
#if !FF_API_FIRST_FORMAT
119
static
120
#endif
121
AVOutputFormat *first_oformat = NULL;
122

    
123
AVInputFormat  *av_iformat_next(AVInputFormat  *f)
124
{
125
    if(f) return f->next;
126
    else  return first_iformat;
127
}
128

    
129
AVOutputFormat *av_oformat_next(AVOutputFormat *f)
130
{
131
    if(f) return f->next;
132
    else  return first_oformat;
133
}
134

    
135
void av_register_input_format(AVInputFormat *format)
136
{
137
    AVInputFormat **p;
138
    p = &first_iformat;
139
    while (*p != NULL) p = &(*p)->next;
140
    *p = format;
141
    format->next = NULL;
142
}
143

    
144
void av_register_output_format(AVOutputFormat *format)
145
{
146
    AVOutputFormat **p;
147
    p = &first_oformat;
148
    while (*p != NULL) p = &(*p)->next;
149
    *p = format;
150
    format->next = NULL;
151
}
152

    
153
int av_match_ext(const char *filename, const char *extensions)
154
{
155
    const char *ext, *p;
156
    char ext1[32], *q;
157

    
158
    if(!filename)
159
        return 0;
160

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

    
180
static int match_format(const char *name, const char *names)
181
{
182
    const char *p;
183
    int len, namelen;
184

    
185
    if (!name || !names)
186
        return 0;
187

    
188
    namelen = strlen(name);
189
    while ((p = strchr(names, ','))) {
190
        len = FFMAX(p - names, namelen);
191
        if (!strncasecmp(name, names, len))
192
            return 1;
193
        names = p+1;
194
    }
195
    return !strcasecmp(name, names);
196
}
197

    
198
#if FF_API_GUESS_FORMAT
199
AVOutputFormat *guess_format(const char *short_name, const char *filename,
200
                             const char *mime_type)
201
{
202
    return av_guess_format(short_name, filename, mime_type);
203
}
204
#endif
205

    
206
AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
207
                                const char *mime_type)
208
{
209
    AVOutputFormat *fmt, *fmt_found;
210
    int score_max, score;
211

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

    
243
#if FF_API_GUESS_FORMAT
244
AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
245
                             const char *mime_type)
246
{
247
    AVOutputFormat *fmt = av_guess_format(short_name, filename, mime_type);
248

    
249
    if (fmt) {
250
        AVOutputFormat *stream_fmt;
251
        char stream_format_name[64];
252

    
253
        snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
254
        stream_fmt = av_guess_format(stream_format_name, NULL, NULL);
255

    
256
        if (stream_fmt)
257
            fmt = stream_fmt;
258
    }
259

    
260
    return fmt;
261
}
262
#endif
263

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

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

    
283
AVInputFormat *av_find_input_format(const char *short_name)
284
{
285
    AVInputFormat *fmt;
286
    for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
287
        if (match_format(short_name, fmt->name))
288
            return fmt;
289
    }
290
    return NULL;
291
}
292

    
293
#if FF_API_SYMVER && CONFIG_SHARED && HAVE_SYMVER
294
FF_SYMVER(void, av_destruct_packet_nofree, (AVPacket *pkt), "LIBAVFORMAT_52")
295
{
296
    av_destruct_packet_nofree(pkt);
297
}
298

    
299
FF_SYMVER(void, av_destruct_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
300
{
301
    av_destruct_packet(pkt);
302
}
303

    
304
FF_SYMVER(int, av_new_packet, (AVPacket *pkt, int size), "LIBAVFORMAT_52")
305
{
306
    return av_new_packet(pkt, size);
307
}
308

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

    
314
FF_SYMVER(void, av_free_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
315
{
316
    av_free_packet(pkt);
317
}
318

    
319
FF_SYMVER(void, av_init_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
320
{
321
    av_log(NULL, AV_LOG_WARNING, "Diverting av_*_packet function calls to libavcodec. Recompile to improve performance\n");
322
    av_init_packet(pkt);
323
}
324
#endif
325

    
326
int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
327
{
328
    int ret= av_new_packet(pkt, size);
329

    
330
    if(ret<0)
331
        return ret;
332

    
333
    pkt->pos= url_ftell(s);
334

    
335
    ret= get_buffer(s, pkt->data, size);
336
    if(ret<=0)
337
        av_free_packet(pkt);
338
    else
339
        av_shrink_packet(pkt, ret);
340

    
341
    return ret;
342
}
343

    
344

    
345
int av_filename_number_test(const char *filename)
346
{
347
    char buf[1024];
348
    return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
349
}
350

    
351
AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
352
{
353
    AVProbeData lpd = *pd;
354
    AVInputFormat *fmt1, *fmt;
355
    int score;
356

    
357
    if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
358
        int id3len = ff_id3v2_tag_len(lpd.buf);
359
        if (lpd.buf_size > id3len + 16) {
360
            lpd.buf += id3len;
361
            lpd.buf_size -= id3len;
362
        }
363
    }
364

    
365
    fmt = NULL;
366
    for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
367
        if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
368
            continue;
369
        score = 0;
370
        if (fmt1->read_probe) {
371
            score = fmt1->read_probe(&lpd);
372
        } else if (fmt1->extensions) {
373
            if (av_match_ext(lpd.filename, fmt1->extensions)) {
374
                score = 50;
375
            }
376
        }
377
        if (score > *score_max) {
378
            *score_max = score;
379
            fmt = fmt1;
380
        }else if (score == *score_max)
381
            fmt = NULL;
382
    }
383
    return fmt;
384
}
385

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

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

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

    
423
/************************************************************/
424
/* input media file */
425

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

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

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

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

    
467
    // e.g. AVFMT_NOFILE formats will not have a ByteIOContext
468
    if (ic->pb)
469
        ff_id3v2_read(ic, ID3v2_DEFAULT_MAGIC);
470

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

    
477
    if (pb && !ic->data_offset)
478
        ic->data_offset = url_ftell(ic->pb);
479

    
480
#if FF_API_OLD_METADATA
481
    ff_metadata_demux_compat(ic);
482
#endif
483

    
484
    ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
485

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

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

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

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

    
528
    if (offset >= max_probe_size) {
529
        return AVERROR(EINVAL);
530
    }
531

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

    
537
        if (probe_size < offset) {
538
            continue;
539
        }
540

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

    
555
        memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
556

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

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

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

    
576
    return ret;
577
}
578

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

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

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

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

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

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

    
641
}
642

    
643
/*******************************************************/
644

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

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

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

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

    
667
    for(;;){
668
        AVPacketList *pktl = s->raw_packet_buffer;
669

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

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

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

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

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

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

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

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

    
738
/**********************************************************/
739

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

    
747
    if(enc->codec_id == CODEC_ID_VORBIS)
748
        return -1;
749

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

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

    
769

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

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

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

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

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

    
843
    st->first_dts= dts - st->cur_dts;
844
    st->cur_dts= dts;
845

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

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

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

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

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

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

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

    
905
    if (s->flags & AVFMT_FLAG_NOFILLIN)
906
        return;
907

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

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

    
915
    /* do we have a video B-frame ? */
916
    delay= st->codec->has_b_frames;
917
    presentation_delayed = 0;
918
    /* XXX: need has_b_frame, but cannot get it if the codec is
919
        not initialized */
920
    if (delay &&
921
        pc && pc->pict_type != FF_B_TYPE)
922
        presentation_delayed = 1;
923

    
924
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
925
       /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
926
        pkt->dts -= 1LL<<st->pts_wrap_bits;
927
    }
928

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

    
937
    if (pkt->duration == 0) {
938
        compute_frame_duration(&num, &den, st, pc, pkt);
939
        if (den && num) {
940
            pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
941

    
942
            if(pkt->duration != 0 && s->packet_buffer)
943
                update_initial_durations(s, st, pkt);
944
        }
945
    }
946

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

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

    
977
    /* This may be redundant, but it should not hurt. */
978
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
979
        presentation_delayed = 1;
980

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

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

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

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

    
1039
//    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);
1040

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

    
1056

    
1057
static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1058
{
1059
    AVStream *st;
1060
    int len, ret, i;
1061

    
1062
    av_init_packet(pkt);
1063

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

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

    
1110
                    if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY){
1111
                        ff_reduce_index(s, st->index);
1112
                        av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
1113
                                           0, 0, AVINDEX_KEYFRAME);
1114
                    }
1115

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

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

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

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

    
1195
    return 0;
1196
}
1197

    
1198
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1199
{
1200
    AVPacketList *pktl;
1201
    int eof=0;
1202
    const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1203

    
1204
    for(;;){
1205
        pktl = s->packet_buffer;
1206
        if (pktl) {
1207
            AVPacket *next_pkt= &pktl->pkt;
1208

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

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

    
1242
            if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1243
                                           &s->packet_buffer_end)) < 0)
1244
                return AVERROR(ENOMEM);
1245
        }else{
1246
            assert(!s->packet_buffer);
1247
            return av_read_frame_internal(s, pkt);
1248
        }
1249
    }
1250
}
1251

    
1252
/* XXX: suppress the packet queue */
1253
static void flush_packet_queue(AVFormatContext *s)
1254
{
1255
    AVPacketList *pktl;
1256

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

    
1276
/*******************************************************/
1277
/* seek support */
1278

    
1279
int av_find_default_stream_index(AVFormatContext *s)
1280
{
1281
    int first_audio_index = -1;
1282
    int i;
1283
    AVStream *st;
1284

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

    
1298
/**
1299
 * Flush the frame reader.
1300
 */
1301
void ff_read_frame_flush(AVFormatContext *s)
1302
{
1303
    AVStream *st;
1304
    int i, j;
1305

    
1306
    flush_packet_queue(s);
1307

    
1308
    s->cur_st = NULL;
1309

    
1310
    /* for each stream, reset read state */
1311
    for(i = 0; i < s->nb_streams; i++) {
1312
        st = s->streams[i];
1313

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

    
1326
        st->probe_packets = MAX_PROBE_PACKETS;
1327

    
1328
        for(j=0; j<MAX_REORDER_DELAY+1; j++)
1329
            st->pts_buffer[j]= AV_NOPTS_VALUE;
1330
    }
1331
}
1332

    
1333
void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1334
    int i;
1335

    
1336
    for(i = 0; i < s->nb_streams; i++) {
1337
        AVStream *st = s->streams[i];
1338

    
1339
        st->cur_dts = av_rescale(timestamp,
1340
                                 st->time_base.den * (int64_t)ref_st->time_base.num,
1341
                                 st->time_base.num * (int64_t)ref_st->time_base.den);
1342
    }
1343
}
1344

    
1345
void ff_reduce_index(AVFormatContext *s, int stream_index)
1346
{
1347
    AVStream *st= s->streams[stream_index];
1348
    unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1349

    
1350
    if((unsigned)st->nb_index_entries >= max_entries){
1351
        int i;
1352
        for(i=0; 2*i<st->nb_index_entries; i++)
1353
            st->index_entries[i]= st->index_entries[2*i];
1354
        st->nb_index_entries= i;
1355
    }
1356
}
1357

    
1358
int av_add_index_entry(AVStream *st,
1359
                            int64_t pos, int64_t timestamp, int size, int distance, int flags)
1360
{
1361
    AVIndexEntry *entries, *ie;
1362
    int index;
1363

    
1364
    if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1365
        return -1;
1366

    
1367
    entries = av_fast_realloc(st->index_entries,
1368
                              &st->index_entries_allocated_size,
1369
                              (st->nb_index_entries + 1) *
1370
                              sizeof(AVIndexEntry));
1371
    if(!entries)
1372
        return -1;
1373

    
1374
    st->index_entries= entries;
1375

    
1376
    index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
1377

    
1378
    if(index<0){
1379
        index= st->nb_index_entries++;
1380
        ie= &entries[index];
1381
        assert(index==0 || ie[-1].timestamp < timestamp);
1382
    }else{
1383
        ie= &entries[index];
1384
        if(ie->timestamp != timestamp){
1385
            if(ie->timestamp <= timestamp)
1386
                return -1;
1387
            memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
1388
            st->nb_index_entries++;
1389
        }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1390
            distance= ie->min_distance;
1391
    }
1392

    
1393
    ie->pos = pos;
1394
    ie->timestamp = timestamp;
1395
    ie->min_distance= distance;
1396
    ie->size= size;
1397
    ie->flags = flags;
1398

    
1399
    return index;
1400
}
1401

    
1402
int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1403
                              int flags)
1404
{
1405
    AVIndexEntry *entries= st->index_entries;
1406
    int nb_entries= st->nb_index_entries;
1407
    int a, b, m;
1408
    int64_t timestamp;
1409

    
1410
    a = - 1;
1411
    b = nb_entries;
1412

    
1413
    //optimize appending index entries at the end
1414
    if(b && entries[b-1].timestamp < wanted_timestamp)
1415
        a= b-1;
1416

    
1417
    while (b - a > 1) {
1418
        m = (a + b) >> 1;
1419
        timestamp = entries[m].timestamp;
1420
        if(timestamp >= wanted_timestamp)
1421
            b = m;
1422
        if(timestamp <= wanted_timestamp)
1423
            a = m;
1424
    }
1425
    m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1426

    
1427
    if(!(flags & AVSEEK_FLAG_ANY)){
1428
        while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1429
            m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1430
        }
1431
    }
1432

    
1433
    if(m == nb_entries)
1434
        return -1;
1435
    return  m;
1436
}
1437

    
1438
#define DEBUG_SEEK
1439

    
1440
int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1441
    AVInputFormat *avif= s->iformat;
1442
    int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1443
    int64_t ts_min, ts_max, ts;
1444
    int index;
1445
    int64_t ret;
1446
    AVStream *st;
1447

    
1448
    if (stream_index < 0)
1449
        return -1;
1450

    
1451
#ifdef DEBUG_SEEK
1452
    av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1453
#endif
1454

    
1455
    ts_max=
1456
    ts_min= AV_NOPTS_VALUE;
1457
    pos_limit= -1; //gcc falsely says it may be uninitialized
1458

    
1459
    st= s->streams[stream_index];
1460
    if(st->index_entries){
1461
        AVIndexEntry *e;
1462

    
1463
        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()
1464
        index= FFMAX(index, 0);
1465
        e= &st->index_entries[index];
1466

    
1467
        if(e->timestamp <= target_ts || e->pos == e->min_distance){
1468
            pos_min= e->pos;
1469
            ts_min= e->timestamp;
1470
#ifdef DEBUG_SEEK
1471
            av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1472
                   pos_min,ts_min);
1473
#endif
1474
        }else{
1475
            assert(index==0);
1476
        }
1477

    
1478
        index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1479
        assert(index < st->nb_index_entries);
1480
        if(index >= 0){
1481
            e= &st->index_entries[index];
1482
            assert(e->timestamp >= target_ts);
1483
            pos_max= e->pos;
1484
            ts_max= e->timestamp;
1485
            pos_limit= pos_max - e->min_distance;
1486
#ifdef DEBUG_SEEK
1487
            av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1488
                   pos_max,pos_limit, ts_max);
1489
#endif
1490
        }
1491
    }
1492

    
1493
    pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1494
    if(pos<0)
1495
        return -1;
1496

    
1497
    /* do the seek */
1498
    if ((ret = url_fseek(s->pb, pos, SEEK_SET)) < 0)
1499
        return ret;
1500

    
1501
    av_update_cur_dts(s, st, ts);
1502

    
1503
    return 0;
1504
}
1505

    
1506
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 )){
1507
    int64_t pos, ts;
1508
    int64_t start_pos, filesize;
1509
    int no_change;
1510

    
1511
#ifdef DEBUG_SEEK
1512
    av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1513
#endif
1514

    
1515
    if(ts_min == AV_NOPTS_VALUE){
1516
        pos_min = s->data_offset;
1517
        ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1518
        if (ts_min == AV_NOPTS_VALUE)
1519
            return -1;
1520
    }
1521

    
1522
    if(ts_max == AV_NOPTS_VALUE){
1523
        int step= 1024;
1524
        filesize = url_fsize(s->pb);
1525
        pos_max = filesize - 1;
1526
        do{
1527
            pos_max -= step;
1528
            ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1529
            step += step;
1530
        }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1531
        if (ts_max == AV_NOPTS_VALUE)
1532
            return -1;
1533

    
1534
        for(;;){
1535
            int64_t tmp_pos= pos_max + 1;
1536
            int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1537
            if(tmp_ts == AV_NOPTS_VALUE)
1538
                break;
1539
            ts_max= tmp_ts;
1540
            pos_max= tmp_pos;
1541
            if(tmp_pos >= filesize)
1542
                break;
1543
        }
1544
        pos_limit= pos_max;
1545
    }
1546

    
1547
    if(ts_min > ts_max){
1548
        return -1;
1549
    }else if(ts_min == ts_max){
1550
        pos_limit= pos_min;
1551
    }
1552

    
1553
    no_change=0;
1554
    while (pos_min < pos_limit) {
1555
#ifdef DEBUG_SEEK
1556
        av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1557
               pos_min, pos_max,
1558
               ts_min, ts_max);
1559
#endif
1560
        assert(pos_limit <= pos_max);
1561

    
1562
        if(no_change==0){
1563
            int64_t approximate_keyframe_distance= pos_max - pos_limit;
1564
            // interpolate position (better than dichotomy)
1565
            pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1566
                + pos_min - approximate_keyframe_distance;
1567
        }else if(no_change==1){
1568
            // bisection, if interpolation failed to change min or max pos last time
1569
            pos = (pos_min + pos_limit)>>1;
1570
        }else{
1571
            /* linear search if bisection failed, can only happen if there
1572
               are very few or no keyframes between min/max */
1573
            pos=pos_min;
1574
        }
1575
        if(pos <= pos_min)
1576
            pos= pos_min + 1;
1577
        else if(pos > pos_limit)
1578
            pos= pos_limit;
1579
        start_pos= pos;
1580

    
1581
        ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1582
        if(pos == pos_max)
1583
            no_change++;
1584
        else
1585
            no_change=0;
1586
#ifdef DEBUG_SEEK
1587
        av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1588
               pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit,
1589
               start_pos, no_change);
1590
#endif
1591
        if(ts == AV_NOPTS_VALUE){
1592
            av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1593
            return -1;
1594
        }
1595
        assert(ts != AV_NOPTS_VALUE);
1596
        if (target_ts <= ts) {
1597
            pos_limit = start_pos - 1;
1598
            pos_max = pos;
1599
            ts_max = ts;
1600
        }
1601
        if (target_ts >= ts) {
1602
            pos_min = pos;
1603
            ts_min = ts;
1604
        }
1605
    }
1606

    
1607
    pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1608
    ts  = (flags & AVSEEK_FLAG_BACKWARD) ?  ts_min :  ts_max;
1609
#ifdef DEBUG_SEEK
1610
    pos_min = pos;
1611
    ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1612
    pos_min++;
1613
    ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1614
    av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1615
           pos, ts_min, target_ts, ts_max);
1616
#endif
1617
    *ts_ret= ts;
1618
    return pos;
1619
}
1620

    
1621
static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1622
    int64_t pos_min, pos_max;
1623
#if 0
1624
    AVStream *st;
1625

1626
    if (stream_index < 0)
1627
        return -1;
1628

1629
    st= s->streams[stream_index];
1630
#endif
1631

    
1632
    pos_min = s->data_offset;
1633
    pos_max = url_fsize(s->pb) - 1;
1634

    
1635
    if     (pos < pos_min) pos= pos_min;
1636
    else if(pos > pos_max) pos= pos_max;
1637

    
1638
    url_fseek(s->pb, pos, SEEK_SET);
1639

    
1640
#if 0
1641
    av_update_cur_dts(s, st, ts);
1642
#endif
1643
    return 0;
1644
}
1645

    
1646
static int av_seek_frame_generic(AVFormatContext *s,
1647
                                 int stream_index, int64_t timestamp, int flags)
1648
{
1649
    int index;
1650
    int64_t ret;
1651
    AVStream *st;
1652
    AVIndexEntry *ie;
1653

    
1654
    st = s->streams[stream_index];
1655

    
1656
    index = av_index_search_timestamp(st, timestamp, flags);
1657

    
1658
    if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1659
        return -1;
1660

    
1661
    if(index < 0 || index==st->nb_index_entries-1){
1662
        int i;
1663
        AVPacket pkt;
1664

    
1665
        if(st->nb_index_entries){
1666
            assert(st->index_entries);
1667
            ie= &st->index_entries[st->nb_index_entries-1];
1668
            if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
1669
                return ret;
1670
            av_update_cur_dts(s, st, ie->timestamp);
1671
        }else{
1672
            if ((ret = url_fseek(s->pb, s->data_offset, SEEK_SET)) < 0)
1673
                return ret;
1674
        }
1675
        for(i=0;; i++) {
1676
            int ret;
1677
            do{
1678
                ret = av_read_frame(s, &pkt);
1679
            }while(ret == AVERROR(EAGAIN));
1680
            if(ret<0)
1681
                break;
1682
            av_free_packet(&pkt);
1683
            if(stream_index == pkt.stream_index){
1684
                if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
1685
                    break;
1686
            }
1687
        }
1688
        index = av_index_search_timestamp(st, timestamp, flags);
1689
    }
1690
    if (index < 0)
1691
        return -1;
1692

    
1693
    ff_read_frame_flush(s);
1694
    if (s->iformat->read_seek){
1695
        if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1696
            return 0;
1697
    }
1698
    ie = &st->index_entries[index];
1699
    if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
1700
        return ret;
1701
    av_update_cur_dts(s, st, ie->timestamp);
1702

    
1703
    return 0;
1704
}
1705

    
1706
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1707
{
1708
    int ret;
1709
    AVStream *st;
1710

    
1711
    ff_read_frame_flush(s);
1712

    
1713
    if(flags & AVSEEK_FLAG_BYTE)
1714
        return av_seek_frame_byte(s, stream_index, timestamp, flags);
1715

    
1716
    if(stream_index < 0){
1717
        stream_index= av_find_default_stream_index(s);
1718
        if(stream_index < 0)
1719
            return -1;
1720

    
1721
        st= s->streams[stream_index];
1722
       /* timestamp for default must be expressed in AV_TIME_BASE units */
1723
        timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1724
    }
1725

    
1726
    /* first, we try the format specific seek */
1727
    if (s->iformat->read_seek)
1728
        ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1729
    else
1730
        ret = -1;
1731
    if (ret >= 0) {
1732
        return 0;
1733
    }
1734

    
1735
    if(s->iformat->read_timestamp)
1736
        return av_seek_frame_binary(s, stream_index, timestamp, flags);
1737
    else
1738
        return av_seek_frame_generic(s, stream_index, timestamp, flags);
1739
}
1740

    
1741
int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1742
{
1743
    if(min_ts > ts || max_ts < ts)
1744
        return -1;
1745

    
1746
    ff_read_frame_flush(s);
1747

    
1748
    if (s->iformat->read_seek2)
1749
        return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1750

    
1751
    if(s->iformat->read_timestamp){
1752
        //try to seek via read_timestamp()
1753
    }
1754

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

    
1760
    // try some generic seek like av_seek_frame_generic() but with new ts semantics
1761
}
1762

    
1763
/*******************************************************/
1764

    
1765
/**
1766
 * Return TRUE if the stream has accurate duration in any stream.
1767
 *
1768
 * @return TRUE if the stream has accurate duration for at least one component.
1769
 */
1770
static int av_has_duration(AVFormatContext *ic)
1771
{
1772
    int i;
1773
    AVStream *st;
1774

    
1775
    for(i = 0;i < ic->nb_streams; i++) {
1776
        st = ic->streams[i];
1777
        if (st->duration != AV_NOPTS_VALUE)
1778
            return 1;
1779
    }
1780
    return 0;
1781
}
1782

    
1783
/**
1784
 * Estimate the stream timings from the one of each components.
1785
 *
1786
 * Also computes the global bitrate if possible.
1787
 */
1788
static void av_update_stream_timings(AVFormatContext *ic)
1789
{
1790
    int64_t start_time, start_time1, end_time, end_time1;
1791
    int64_t duration, duration1;
1792
    int i;
1793
    AVStream *st;
1794

    
1795
    start_time = INT64_MAX;
1796
    end_time = INT64_MIN;
1797
    duration = INT64_MIN;
1798
    for(i = 0;i < ic->nb_streams; i++) {
1799
        st = ic->streams[i];
1800
        if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1801
            start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1802
            if (start_time1 < start_time)
1803
                start_time = start_time1;
1804
            if (st->duration != AV_NOPTS_VALUE) {
1805
                end_time1 = start_time1
1806
                          + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1807
                if (end_time1 > end_time)
1808
                    end_time = end_time1;
1809
            }
1810
        }
1811
        if (st->duration != AV_NOPTS_VALUE) {
1812
            duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1813
            if (duration1 > duration)
1814
                duration = duration1;
1815
        }
1816
    }
1817
    if (start_time != INT64_MAX) {
1818
        ic->start_time = start_time;
1819
        if (end_time != INT64_MIN) {
1820
            if (end_time - start_time > duration)
1821
                duration = end_time - start_time;
1822
        }
1823
    }
1824
    if (duration != INT64_MIN) {
1825
        ic->duration = duration;
1826
        if (ic->file_size > 0) {
1827
            /* compute the bitrate */
1828
            ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1829
                (double)ic->duration;
1830
        }
1831
    }
1832
}
1833

    
1834
static void fill_all_stream_timings(AVFormatContext *ic)
1835
{
1836
    int i;
1837
    AVStream *st;
1838

    
1839
    av_update_stream_timings(ic);
1840
    for(i = 0;i < ic->nb_streams; i++) {
1841
        st = ic->streams[i];
1842
        if (st->start_time == AV_NOPTS_VALUE) {
1843
            if(ic->start_time != AV_NOPTS_VALUE)
1844
                st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1845
            if(ic->duration != AV_NOPTS_VALUE)
1846
                st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1847
        }
1848
    }
1849
}
1850

    
1851
static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1852
{
1853
    int64_t filesize, duration;
1854
    int bit_rate, i;
1855
    AVStream *st;
1856

    
1857
    /* if bit_rate is already set, we believe it */
1858
    if (ic->bit_rate == 0) {
1859
        bit_rate = 0;
1860
        for(i=0;i<ic->nb_streams;i++) {
1861
            st = ic->streams[i];
1862
            bit_rate += st->codec->bit_rate;
1863
        }
1864
        ic->bit_rate = bit_rate;
1865
    }
1866

    
1867
    /* if duration is already set, we believe it */
1868
    if (ic->duration == AV_NOPTS_VALUE &&
1869
        ic->bit_rate != 0 &&
1870
        ic->file_size != 0)  {
1871
        filesize = ic->file_size;
1872
        if (filesize > 0) {
1873
            for(i = 0; i < ic->nb_streams; i++) {
1874
                st = ic->streams[i];
1875
                duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1876
                if (st->duration == AV_NOPTS_VALUE)
1877
                    st->duration = duration;
1878
            }
1879
        }
1880
    }
1881
}
1882

    
1883
#define DURATION_MAX_READ_SIZE 250000
1884
#define DURATION_MAX_RETRY 3
1885

    
1886
/* only usable for MPEG-PS streams */
1887
static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1888
{
1889
    AVPacket pkt1, *pkt = &pkt1;
1890
    AVStream *st;
1891
    int read_size, i, ret;
1892
    int64_t end_time;
1893
    int64_t filesize, offset, duration;
1894
    int retry=0;
1895

    
1896
    ic->cur_st = NULL;
1897

    
1898
    /* flush packet queue */
1899
    flush_packet_queue(ic);
1900

    
1901
    for (i=0; i<ic->nb_streams; i++) {
1902
        st = ic->streams[i];
1903
        if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
1904
            av_log(st->codec, AV_LOG_WARNING, "start time is not set in av_estimate_timings_from_pts\n");
1905

    
1906
        if (st->parser) {
1907
            av_parser_close(st->parser);
1908
            st->parser= NULL;
1909
            av_free_packet(&st->cur_pkt);
1910
        }
1911
    }
1912

    
1913
    /* estimate the end time (duration) */
1914
    /* XXX: may need to support wrapping */
1915
    filesize = ic->file_size;
1916
    end_time = AV_NOPTS_VALUE;
1917
    do{
1918
    offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
1919
    if (offset < 0)
1920
        offset = 0;
1921

    
1922
    url_fseek(ic->pb, offset, SEEK_SET);
1923
    read_size = 0;
1924
    for(;;) {
1925
        if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
1926
            break;
1927

    
1928
        do{
1929
            ret = av_read_packet(ic, pkt);
1930
        }while(ret == AVERROR(EAGAIN));
1931
        if (ret != 0)
1932
            break;
1933
        read_size += pkt->size;
1934
        st = ic->streams[pkt->stream_index];
1935
        if (pkt->pts != AV_NOPTS_VALUE &&
1936
            (st->start_time != AV_NOPTS_VALUE ||
1937
             st->first_dts  != AV_NOPTS_VALUE)) {
1938
            duration = end_time = pkt->pts;
1939
            if (st->start_time != AV_NOPTS_VALUE)  duration -= st->start_time;
1940
            else                                   duration -= st->first_dts;
1941
            if (duration < 0)
1942
                duration += 1LL<<st->pts_wrap_bits;
1943
            if (duration > 0) {
1944
                if (st->duration == AV_NOPTS_VALUE ||
1945
                    st->duration < duration)
1946
                    st->duration = duration;
1947
            }
1948
        }
1949
        av_free_packet(pkt);
1950
    }
1951
    }while(   end_time==AV_NOPTS_VALUE
1952
           && filesize > (DURATION_MAX_READ_SIZE<<retry)
1953
           && ++retry <= DURATION_MAX_RETRY);
1954

    
1955
    fill_all_stream_timings(ic);
1956

    
1957
    url_fseek(ic->pb, old_offset, SEEK_SET);
1958
    for (i=0; i<ic->nb_streams; i++) {
1959
        st= ic->streams[i];
1960
        st->cur_dts= st->first_dts;
1961
        st->last_IP_pts = AV_NOPTS_VALUE;
1962
    }
1963
}
1964

    
1965
static void av_estimate_timings(AVFormatContext *ic, int64_t old_offset)
1966
{
1967
    int64_t file_size;
1968

    
1969
    /* get the file size, if possible */
1970
    if (ic->iformat->flags & AVFMT_NOFILE) {
1971
        file_size = 0;
1972
    } else {
1973
        file_size = url_fsize(ic->pb);
1974
        if (file_size < 0)
1975
            file_size = 0;
1976
    }
1977
    ic->file_size = file_size;
1978

    
1979
    if ((!strcmp(ic->iformat->name, "mpeg") ||
1980
         !strcmp(ic->iformat->name, "mpegts")) &&
1981
        file_size && !url_is_streamed(ic->pb)) {
1982
        /* get accurate estimate from the PTSes */
1983
        av_estimate_timings_from_pts(ic, old_offset);
1984
    } else if (av_has_duration(ic)) {
1985
        /* at least one component has timings - we use them for all
1986
           the components */
1987
        fill_all_stream_timings(ic);
1988
    } else {
1989
        av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
1990
        /* less precise: use bitrate info */
1991
        av_estimate_timings_from_bit_rate(ic);
1992
    }
1993
    av_update_stream_timings(ic);
1994

    
1995
#if 0
1996
    {
1997
        int i;
1998
        AVStream *st;
1999
        for(i = 0;i < ic->nb_streams; i++) {
2000
            st = ic->streams[i];
2001
        printf("%d: start_time: %0.3f duration: %0.3f\n",
2002
               i, (double)st->start_time / AV_TIME_BASE,
2003
               (double)st->duration / AV_TIME_BASE);
2004
        }
2005
        printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2006
               (double)ic->start_time / AV_TIME_BASE,
2007
               (double)ic->duration / AV_TIME_BASE,
2008
               ic->bit_rate / 1000);
2009
    }
2010
#endif
2011
}
2012

    
2013
static int has_codec_parameters(AVCodecContext *enc)
2014
{
2015
    int val;
2016
    switch(enc->codec_type) {
2017
    case AVMEDIA_TYPE_AUDIO:
2018
        val = enc->sample_rate && enc->channels && enc->sample_fmt != AV_SAMPLE_FMT_NONE;
2019
        if(!enc->frame_size &&
2020
           (enc->codec_id == CODEC_ID_VORBIS ||
2021
            enc->codec_id == CODEC_ID_AAC ||
2022
            enc->codec_id == CODEC_ID_MP1 ||
2023
            enc->codec_id == CODEC_ID_MP2 ||
2024
            enc->codec_id == CODEC_ID_MP3 ||
2025
            enc->codec_id == CODEC_ID_SPEEX))
2026
            return 0;
2027
        break;
2028
    case AVMEDIA_TYPE_VIDEO:
2029
        val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
2030
        break;
2031
    default:
2032
        val = 1;
2033
        break;
2034
    }
2035
    return enc->codec_id != CODEC_ID_NONE && val != 0;
2036
}
2037

    
2038
static int has_decode_delay_been_guessed(AVStream *st)
2039
{
2040
    return st->codec->codec_id != CODEC_ID_H264 ||
2041
        st->codec_info_nb_frames >= 4 + st->codec->has_b_frames;
2042
}
2043

    
2044
static int try_decode_frame(AVStream *st, AVPacket *avpkt)
2045
{
2046
    int16_t *samples;
2047
    AVCodec *codec;
2048
    int got_picture, data_size, ret=0;
2049
    AVFrame picture;
2050

    
2051
    if(!st->codec->codec){
2052
        codec = avcodec_find_decoder(st->codec->codec_id);
2053
        if (!codec)
2054
            return -1;
2055
        ret = avcodec_open(st->codec, codec);
2056
        if (ret < 0)
2057
            return ret;
2058
    }
2059

    
2060
    if(!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st)){
2061
        switch(st->codec->codec_type) {
2062
        case AVMEDIA_TYPE_VIDEO:
2063
            avcodec_get_frame_defaults(&picture);
2064
            ret = avcodec_decode_video2(st->codec, &picture,
2065
                                        &got_picture, avpkt);
2066
            break;
2067
        case AVMEDIA_TYPE_AUDIO:
2068
            data_size = FFMAX(avpkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
2069
            samples = av_malloc(data_size);
2070
            if (!samples)
2071
                goto fail;
2072
            ret = avcodec_decode_audio3(st->codec, samples,
2073
                                        &data_size, avpkt);
2074
            av_free(samples);
2075
            break;
2076
        default:
2077
            break;
2078
        }
2079
    }
2080
 fail:
2081
    return ret;
2082
}
2083

    
2084
unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum CodecID id)
2085
{
2086
    while (tags->id != CODEC_ID_NONE) {
2087
        if (tags->id == id)
2088
            return tags->tag;
2089
        tags++;
2090
    }
2091
    return 0;
2092
}
2093

    
2094
enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2095
{
2096
    int i;
2097
    for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
2098
        if(tag == tags[i].tag)
2099
            return tags[i].id;
2100
    }
2101
    for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
2102
        if (ff_toupper4(tag) == ff_toupper4(tags[i].tag))
2103
            return tags[i].id;
2104
    }
2105
    return CODEC_ID_NONE;
2106
}
2107

    
2108
unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
2109
{
2110
    int i;
2111
    for(i=0; tags && tags[i]; i++){
2112
        int tag= ff_codec_get_tag(tags[i], id);
2113
        if(tag) return tag;
2114
    }
2115
    return 0;
2116
}
2117

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

    
2128
static void compute_chapters_end(AVFormatContext *s)
2129
{
2130
    unsigned int i;
2131

    
2132
    for (i=0; i+1<s->nb_chapters; i++)
2133
        if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2134
            assert(s->chapters[i]->start <= s->chapters[i+1]->start);
2135
            assert(!av_cmp_q(s->chapters[i]->time_base, s->chapters[i+1]->time_base));
2136
            s->chapters[i]->end = s->chapters[i+1]->start;
2137
        }
2138

    
2139
    if (s->nb_chapters && s->chapters[i]->end == AV_NOPTS_VALUE) {
2140
        assert(s->start_time != AV_NOPTS_VALUE);
2141
        assert(s->duration > 0);
2142
        s->chapters[i]->end = av_rescale_q(s->start_time + s->duration,
2143
                                           AV_TIME_BASE_Q,
2144
                                           s->chapters[i]->time_base);
2145
    }
2146
}
2147

    
2148
static int get_std_framerate(int i){
2149
    if(i<60*12) return i*1001;
2150
    else        return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2151
}
2152

    
2153
/*
2154
 * Is the time base unreliable.
2155
 * This is a heuristic to balance between quick acceptance of the values in
2156
 * the headers vs. some extra checks.
2157
 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2158
 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2159
 * And there are "variable" fps files this needs to detect as well.
2160
 */
2161
static int tb_unreliable(AVCodecContext *c){
2162
    if(   c->time_base.den >= 101L*c->time_base.num
2163
       || c->time_base.den <    5L*c->time_base.num
2164
/*       || c->codec_tag == AV_RL32("DIVX")
2165
       || c->codec_tag == AV_RL32("XVID")*/
2166
       || c->codec_id == CODEC_ID_MPEG2VIDEO
2167
       || c->codec_id == CODEC_ID_H264
2168
       )
2169
        return 1;
2170
    return 0;
2171
}
2172

    
2173
int av_find_stream_info(AVFormatContext *ic)
2174
{
2175
    int i, count, ret, read_size, j;
2176
    AVStream *st;
2177
    AVPacket pkt1, *pkt;
2178
    int64_t old_offset = url_ftell(ic->pb);
2179

    
2180
    for(i=0;i<ic->nb_streams;i++) {
2181
        AVCodec *codec;
2182
        st = ic->streams[i];
2183
        if (st->codec->codec_id == CODEC_ID_AAC) {
2184
            st->codec->sample_rate = 0;
2185
            st->codec->frame_size = 0;
2186
            st->codec->channels = 0;
2187
        }
2188
        if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
2189
/*            if(!st->time_base.num)
2190
                st->time_base= */
2191
            if(!st->codec->time_base.num)
2192
                st->codec->time_base= st->time_base;
2193
        }
2194
        //only for the split stuff
2195
        if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2196
            st->parser = av_parser_init(st->codec->codec_id);
2197
            if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2198
                st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2199
            }
2200
        }
2201
        assert(!st->codec->codec);
2202
        codec = avcodec_find_decoder(st->codec->codec_id);
2203

    
2204
        /* Force decoding of at least one frame of codec data
2205
         * this makes sure the codec initializes the channel configuration
2206
         * and does not trust the values from the container.
2207
         */
2208
        if (codec && codec->capabilities & CODEC_CAP_CHANNEL_CONF)
2209
            st->codec->channels = 0;
2210

    
2211
        //try to just open decoders, in case this is enough to get parameters
2212
        if(!has_codec_parameters(st->codec)){
2213
            if (codec)
2214
                avcodec_open(st->codec, codec);
2215
        }
2216
    }
2217

    
2218
    for (i=0; i<ic->nb_streams; i++) {
2219
        ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
2220
    }
2221

    
2222
    count = 0;
2223
    read_size = 0;
2224
    for(;;) {
2225
        if(url_interrupt_cb()){
2226
            ret= AVERROR(EINTR);
2227
            av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2228
            break;
2229
        }
2230

    
2231
        /* check if one codec still needs to be handled */
2232
        for(i=0;i<ic->nb_streams;i++) {
2233
            st = ic->streams[i];
2234
            if (!has_codec_parameters(st->codec))
2235
                break;
2236
            /* variable fps and no guess at the real fps */
2237
            if(   tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)
2238
               && st->info->duration_count<20 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2239
                break;
2240
            if(st->parser && st->parser->parser->split && !st->codec->extradata)
2241
                break;
2242
            if(st->first_dts == AV_NOPTS_VALUE)
2243
                break;
2244
        }
2245
        if (i == ic->nb_streams) {
2246
            /* NOTE: if the format has no header, then we need to read
2247
               some packets to get most of the streams, so we cannot
2248
               stop here */
2249
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2250
                /* if we found the info for all the codecs, we can stop */
2251
                ret = count;
2252
                av_log(ic, AV_LOG_DEBUG, "All info found\n");
2253
                break;
2254
            }
2255
        }
2256
        /* we did not get all the codec info, but we read too much data */
2257
        if (read_size >= ic->probesize) {
2258
            ret = count;
2259
            av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2260
            break;
2261
        }
2262

    
2263
        /* NOTE: a new stream can be added there if no header in file
2264
           (AVFMTCTX_NOHEADER) */
2265
        ret = av_read_frame_internal(ic, &pkt1);
2266
        if (ret < 0 && ret != AVERROR(EAGAIN)) {
2267
            /* EOF or error */
2268
            ret = -1; /* we could not have all the codec parameters before EOF */
2269
            for(i=0;i<ic->nb_streams;i++) {
2270
                st = ic->streams[i];
2271
                if (!has_codec_parameters(st->codec)){
2272
                    char buf[256];
2273
                    avcodec_string(buf, sizeof(buf), st->codec, 0);
2274
                    av_log(ic, AV_LOG_WARNING, "Could not find codec parameters (%s)\n", buf);
2275
                } else {
2276
                    ret = 0;
2277
                }
2278
            }
2279
            break;
2280
        }
2281

    
2282
        if (ret == AVERROR(EAGAIN))
2283
            continue;
2284

    
2285
        pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
2286
        if ((ret = av_dup_packet(pkt)) < 0)
2287
            goto find_stream_info_err;
2288

    
2289
        read_size += pkt->size;
2290

    
2291
        st = ic->streams[pkt->stream_index];
2292
        if (st->codec_info_nb_frames>1) {
2293
            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) {
2294
                av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2295
                break;
2296
            }
2297
            st->info->codec_info_duration += pkt->duration;
2298
        }
2299
        {
2300
            int64_t last = st->info->last_dts;
2301
            int64_t duration= pkt->dts - last;
2302

    
2303
            if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
2304
                double dur= duration * av_q2d(st->time_base);
2305

    
2306
//                if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2307
//                    av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
2308
                if (st->info->duration_count < 2)
2309
                    memset(st->info->duration_error, 0, sizeof(st->info->duration_error));
2310
                for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error); i++) {
2311
                    int framerate= get_std_framerate(i);
2312
                    int ticks= lrintf(dur*framerate/(1001*12));
2313
                    double error= dur - ticks*1001*12/(double)framerate;
2314
                    st->info->duration_error[i] += error*error;
2315
                }
2316
                st->info->duration_count++;
2317
                // ignore the first 4 values, they might have some random jitter
2318
                if (st->info->duration_count > 3)
2319
                    st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
2320
            }
2321
            if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
2322
                st->info->last_dts = pkt->dts;
2323
        }
2324
        if(st->parser && st->parser->parser->split && !st->codec->extradata){
2325
            int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2326
            if(i){
2327
                st->codec->extradata_size= i;
2328
                st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2329
                memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2330
                memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2331
            }
2332
        }
2333

    
2334
        /* if still no information, we try to open the codec and to
2335
           decompress the frame. We try to avoid that in most cases as
2336
           it takes longer and uses more memory. For MPEG-4, we need to
2337
           decompress for QuickTime. */
2338
        if (!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st))
2339
            try_decode_frame(st, pkt);
2340

    
2341
        st->codec_info_nb_frames++;
2342
        count++;
2343
    }
2344

    
2345
    // close codecs which were opened in try_decode_frame()
2346
    for(i=0;i<ic->nb_streams;i++) {
2347
        st = ic->streams[i];
2348
        if(st->codec->codec)
2349
            avcodec_close(st->codec);
2350
    }
2351
    for(i=0;i<ic->nb_streams;i++) {
2352
        st = ic->streams[i];
2353
        if (st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && st->info->codec_info_duration)
2354
            av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2355
                     (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,
2356
                      st->info->codec_info_duration*(int64_t)st->time_base.num, 60000);
2357
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2358
            if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample)
2359
                st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2360

    
2361
            // the check for tb_unreliable() is not completely correct, since this is not about handling
2362
            // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2363
            // ipmovie.c produces.
2364
            if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > 1 && !st->r_frame_rate.num)
2365
                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);
2366
            if (st->info->duration_count && !st->r_frame_rate.num
2367
               && tb_unreliable(st->codec) /*&&
2368
               //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2369
               st->time_base.num*duration_sum[i]/st->info->duration_count*101LL > st->time_base.den*/){
2370
                int num = 0;
2371
                double best_error= 2*av_q2d(st->time_base);
2372
                best_error = best_error*best_error*st->info->duration_count*1000*12*30;
2373

    
2374
                for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error); j++) {
2375
                    double error = st->info->duration_error[j] * get_std_framerate(j);
2376
//                    if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2377
//                        av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
2378
                    if(error < best_error){
2379
                        best_error= error;
2380
                        num = get_std_framerate(j);
2381
                    }
2382
                }
2383
                // do not increase frame rate by more than 1 % in order to match a standard rate.
2384
                if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
2385
                    av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2386
            }
2387

    
2388
            if (!st->r_frame_rate.num){
2389
                if(    st->codec->time_base.den * (int64_t)st->time_base.num
2390
                    <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){
2391
                    st->r_frame_rate.num = st->codec->time_base.den;
2392
                    st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
2393
                }else{
2394
                    st->r_frame_rate.num = st->time_base.den;
2395
                    st->r_frame_rate.den = st->time_base.num;
2396
                }
2397
            }
2398
        }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2399
            if(!st->codec->bits_per_coded_sample)
2400
                st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2401
        }
2402
    }
2403

    
2404
    av_estimate_timings(ic, old_offset);
2405

    
2406
    compute_chapters_end(ic);
2407

    
2408
#if 0
2409
    /* correct DTS for B-frame streams with no timestamps */
2410
    for(i=0;i<ic->nb_streams;i++) {
2411
        st = ic->streams[i];
2412
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2413
            if(b-frames){
2414
                ppktl = &ic->packet_buffer;
2415
                while(ppkt1){
2416
                    if(ppkt1->stream_index != i)
2417
                        continue;
2418
                    if(ppkt1->pkt->dts < 0)
2419
                        break;
2420
                    if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2421
                        break;
2422
                    ppkt1->pkt->dts -= delta;
2423
                    ppkt1= ppkt1->next;
2424
                }
2425
                if(ppkt1)
2426
                    continue;
2427
                st->cur_dts -= delta;
2428
            }
2429
        }
2430
    }
2431
#endif
2432

    
2433
 find_stream_info_err:
2434
    for (i=0; i < ic->nb_streams; i++)
2435
        av_freep(&ic->streams[i]->info);
2436
    return ret;
2437
}
2438

    
2439
/*******************************************************/
2440

    
2441
int av_read_play(AVFormatContext *s)
2442
{
2443
    if (s->iformat->read_play)
2444
        return s->iformat->read_play(s);
2445
    if (s->pb)
2446
        return av_url_read_fpause(s->pb, 0);
2447
    return AVERROR(ENOSYS);
2448
}
2449

    
2450
int av_read_pause(AVFormatContext *s)
2451
{
2452
    if (s->iformat->read_pause)
2453
        return s->iformat->read_pause(s);
2454
    if (s->pb)
2455
        return av_url_read_fpause(s->pb, 1);
2456
    return AVERROR(ENOSYS);
2457
}
2458

    
2459
void av_close_input_stream(AVFormatContext *s)
2460
{
2461
    int i;
2462
    AVStream *st;
2463

    
2464
    if (s->iformat->read_close)
2465
        s->iformat->read_close(s);
2466
    for(i=0;i<s->nb_streams;i++) {
2467
        /* free all data in a stream component */
2468
        st = s->streams[i];
2469
        if (st->parser) {
2470
            av_parser_close(st->parser);
2471
            av_free_packet(&st->cur_pkt);
2472
        }
2473
        av_metadata_free(&st->metadata);
2474
        av_free(st->index_entries);
2475
        av_free(st->codec->extradata);
2476
        av_free(st->codec);
2477
#if FF_API_OLD_METADATA
2478
        av_free(st->filename);
2479
#endif
2480
        av_free(st->priv_data);
2481
        av_free(st->info);
2482
        av_free(st);
2483
    }
2484
    for(i=s->nb_programs-1; i>=0; i--) {
2485
#if FF_API_OLD_METADATA
2486
        av_freep(&s->programs[i]->provider_name);
2487
        av_freep(&s->programs[i]->name);
2488
#endif
2489
        av_metadata_free(&s->programs[i]->metadata);
2490
        av_freep(&s->programs[i]->stream_index);
2491
        av_freep(&s->programs[i]);
2492
    }
2493
    av_freep(&s->programs);
2494
    flush_packet_queue(s);
2495
    av_freep(&s->priv_data);
2496
    while(s->nb_chapters--) {
2497
#if FF_API_OLD_METADATA
2498
        av_free(s->chapters[s->nb_chapters]->title);
2499
#endif
2500
        av_metadata_free(&s->chapters[s->nb_chapters]->metadata);
2501
        av_free(s->chapters[s->nb_chapters]);
2502
    }
2503
    av_freep(&s->chapters);
2504
    av_metadata_free(&s->metadata);
2505
    av_freep(&s->key);
2506
    av_free(s);
2507
}
2508

    
2509
void av_close_input_file(AVFormatContext *s)
2510
{
2511
    ByteIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
2512
    av_close_input_stream(s);
2513
    if (pb)
2514
        url_fclose(pb);
2515
}
2516

    
2517
AVStream *av_new_stream(AVFormatContext *s, int id)
2518
{
2519
    AVStream *st;
2520
    int i;
2521

    
2522
#if FF_API_MAX_STREAMS
2523
    if (s->nb_streams >= MAX_STREAMS){
2524
        av_log(s, AV_LOG_ERROR, "Too many streams\n");
2525
        return NULL;
2526
    }
2527
#else
2528
    AVStream **streams;
2529

    
2530
    if (s->nb_streams >= INT_MAX/sizeof(*streams))
2531
        return NULL;
2532
    streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
2533
    if (!streams)
2534
        return NULL;
2535
    s->streams = streams;
2536
#endif
2537

    
2538
    st = av_mallocz(sizeof(AVStream));
2539
    if (!st)
2540
        return NULL;
2541
    if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2542
        av_free(st);
2543
        return NULL;
2544
    }
2545

    
2546
    st->codec= avcodec_alloc_context();
2547
    if (s->iformat) {
2548
        /* no default bitrate if decoding */
2549
        st->codec->bit_rate = 0;
2550
    }
2551
    st->index = s->nb_streams;
2552
    st->id = id;
2553
    st->start_time = AV_NOPTS_VALUE;
2554
    st->duration = AV_NOPTS_VALUE;
2555
        /* we set the current DTS to 0 so that formats without any timestamps
2556
           but durations get some timestamps, formats with some unknown
2557
           timestamps have their first few packets buffered and the
2558
           timestamps corrected before they are returned to the user */
2559
    st->cur_dts = 0;
2560
    st->first_dts = AV_NOPTS_VALUE;
2561
    st->probe_packets = MAX_PROBE_PACKETS;
2562

    
2563
    /* default pts setting is MPEG-like */
2564
    av_set_pts_info(st, 33, 1, 90000);
2565
    st->last_IP_pts = AV_NOPTS_VALUE;
2566
    for(i=0; i<MAX_REORDER_DELAY+1; i++)
2567
        st->pts_buffer[i]= AV_NOPTS_VALUE;
2568
    st->reference_dts = AV_NOPTS_VALUE;
2569

    
2570
    st->sample_aspect_ratio = (AVRational){0,1};
2571

    
2572
    s->streams[s->nb_streams++] = st;
2573
    return st;
2574
}
2575

    
2576
AVProgram *av_new_program(AVFormatContext *ac, int id)
2577
{
2578
    AVProgram *program=NULL;
2579
    int i;
2580

    
2581
#ifdef DEBUG_SI
2582
    av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id);
2583
#endif
2584

    
2585
    for(i=0; i<ac->nb_programs; i++)
2586
        if(ac->programs[i]->id == id)
2587
            program = ac->programs[i];
2588

    
2589
    if(!program){
2590
        program = av_mallocz(sizeof(AVProgram));
2591
        if (!program)
2592
            return NULL;
2593
        dynarray_add(&ac->programs, &ac->nb_programs, program);
2594
        program->discard = AVDISCARD_NONE;
2595
    }
2596
    program->id = id;
2597

    
2598
    return program;
2599
}
2600

    
2601
AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2602
{
2603
    AVChapter *chapter = NULL;
2604
    int i;
2605

    
2606
    for(i=0; i<s->nb_chapters; i++)
2607
        if(s->chapters[i]->id == id)
2608
            chapter = s->chapters[i];
2609

    
2610
    if(!chapter){
2611
        chapter= av_mallocz(sizeof(AVChapter));
2612
        if(!chapter)
2613
            return NULL;
2614
        dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2615
    }
2616
#if FF_API_OLD_METADATA
2617
    av_free(chapter->title);
2618
#endif
2619
    av_metadata_set2(&chapter->metadata, "title", title, 0);
2620
    chapter->id    = id;
2621
    chapter->time_base= time_base;
2622
    chapter->start = start;
2623
    chapter->end   = end;
2624

    
2625
    return chapter;
2626
}
2627

    
2628
/************************************************************/
2629
/* output media file */
2630

    
2631
int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2632
{
2633
    int ret;
2634

    
2635
    if (s->oformat->priv_data_size > 0) {
2636
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
2637
        if (!s->priv_data)
2638
            return AVERROR(ENOMEM);
2639
    } else
2640
        s->priv_data = NULL;
2641

    
2642
    if (s->oformat->set_parameters) {
2643
        ret = s->oformat->set_parameters(s, ap);
2644
        if (ret < 0)
2645
            return ret;
2646
    }
2647
    return 0;
2648
}
2649

    
2650
static int validate_codec_tag(AVFormatContext *s, AVStream *st)
2651
{
2652
    const AVCodecTag *avctag;
2653
    int n;
2654
    enum CodecID id = CODEC_ID_NONE;
2655
    unsigned int tag = 0;
2656

    
2657
    /**
2658
     * Check that tag + id is in the table
2659
     * If neither is in the table -> OK
2660
     * If tag is in the table with another id -> FAIL
2661
     * If id is in the table with another tag -> FAIL unless strict < normal
2662
     */
2663
    for (n = 0; s->oformat->codec_tag[n]; n++) {
2664
        avctag = s->oformat->codec_tag[n];
2665
        while (avctag->id != CODEC_ID_NONE) {
2666
            if (ff_toupper4(avctag->tag) == ff_toupper4(st->codec->codec_tag)) {
2667
                id = avctag->id;
2668
                if (id == st->codec->codec_id)
2669
                    return 1;
2670
            }
2671
            if (avctag->id == st->codec->codec_id)
2672
                tag = avctag->tag;
2673
            avctag++;
2674
        }
2675
    }
2676
    if (id != CODEC_ID_NONE)
2677
        return 0;
2678
    if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
2679
        return 0;
2680
    return 1;
2681
}
2682

    
2683
int av_write_header(AVFormatContext *s)
2684
{
2685
    int ret, i;
2686
    AVStream *st;
2687

    
2688
    // some sanity checks
2689
    if (s->nb_streams == 0) {
2690
        av_log(s, AV_LOG_ERROR, "no streams\n");
2691
        return AVERROR(EINVAL);
2692
    }
2693

    
2694
    for(i=0;i<s->nb_streams;i++) {
2695
        st = s->streams[i];
2696

    
2697
        switch (st->codec->codec_type) {
2698
        case AVMEDIA_TYPE_AUDIO:
2699
            if(st->codec->sample_rate<=0){
2700
                av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2701
                return AVERROR(EINVAL);
2702
            }
2703
            if(!st->codec->block_align)
2704
                st->codec->block_align = st->codec->channels *
2705
                    av_get_bits_per_sample(st->codec->codec_id) >> 3;
2706
            break;
2707
        case AVMEDIA_TYPE_VIDEO:
2708
            if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2709
                av_log(s, AV_LOG_ERROR, "time base not set\n");
2710
                return AVERROR(EINVAL);
2711
            }
2712
            if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){
2713
                av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2714
                return AVERROR(EINVAL);
2715
            }
2716
            if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)){
2717
                av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");
2718
                return AVERROR(EINVAL);
2719
            }
2720
            break;
2721
        }
2722

    
2723
        if(s->oformat->codec_tag){
2724
            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)){
2725
                //the current rawvideo encoding system ends up setting the wrong codec_tag for avi, we override it here
2726
                st->codec->codec_tag= 0;
2727
            }
2728
            if(st->codec->codec_tag){
2729
                if (!validate_codec_tag(s, st)) {
2730
                    char tagbuf[32];
2731
                    av_get_codec_tag_string(tagbuf, sizeof(tagbuf), st->codec->codec_tag);
2732
                    av_log(s, AV_LOG_ERROR,
2733
                           "Tag %s/0x%08x incompatible with output codec id '%d'\n",
2734
                           tagbuf, st->codec->codec_tag, st->codec->codec_id);
2735
                    return AVERROR_INVALIDDATA;
2736
                }
2737
            }else
2738
                st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
2739
        }
2740

    
2741
        if(s->oformat->flags & AVFMT_GLOBALHEADER &&
2742
            !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))
2743
          av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);
2744
    }
2745

    
2746
    if (!s->priv_data && s->oformat->priv_data_size > 0) {
2747
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
2748
        if (!s->priv_data)
2749
            return AVERROR(ENOMEM);
2750
    }
2751

    
2752
#if FF_API_OLD_METADATA
2753
    ff_metadata_mux_compat(s);
2754
#endif
2755

    
2756
    /* set muxer identification string */
2757
    if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
2758
        av_metadata_set2(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
2759
    }
2760

    
2761
    if(s->oformat->write_header){
2762
        ret = s->oformat->write_header(s);
2763
        if (ret < 0)
2764
            return ret;
2765
    }
2766

    
2767
    /* init PTS generation */
2768
    for(i=0;i<s->nb_streams;i++) {
2769
        int64_t den = AV_NOPTS_VALUE;
2770
        st = s->streams[i];
2771

    
2772
        switch (st->codec->codec_type) {
2773
        case AVMEDIA_TYPE_AUDIO:
2774
            den = (int64_t)st->time_base.num * st->codec->sample_rate;
2775
            break;
2776
        case AVMEDIA_TYPE_VIDEO:
2777
            den = (int64_t)st->time_base.num * st->codec->time_base.den;
2778
            break;
2779
        default:
2780
            break;
2781
        }
2782
        if (den != AV_NOPTS_VALUE) {
2783
            if (den <= 0)
2784
                return AVERROR_INVALIDDATA;
2785
            av_frac_init(&st->pts, 0, 0, den);
2786
        }
2787
    }
2788
    return 0;
2789
}
2790

    
2791
//FIXME merge with compute_pkt_fields
2792
static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){
2793
    int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
2794
    int num, den, frame_size, i;
2795

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

    
2798
/*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2799
        return -1;*/
2800

    
2801
    /* duration field */
2802
    if (pkt->duration == 0) {
2803
        compute_frame_duration(&num, &den, st, NULL, pkt);
2804
        if (den && num) {
2805
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
2806
        }
2807
    }
2808

    
2809
    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
2810
        pkt->pts= pkt->dts;
2811

    
2812
    //XXX/FIXME this is a temporary hack until all encoders output pts
2813
    if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
2814
        pkt->dts=
2815
//        pkt->pts= st->cur_dts;
2816
        pkt->pts= st->pts.val;
2817
    }
2818

    
2819
    //calculate dts from pts
2820
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
2821
        st->pts_buffer[0]= pkt->pts;
2822
        for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
2823
            st->pts_buffer[i]= pkt->pts + (i-delay-1) * pkt->duration;
2824
        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
2825
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
2826

    
2827
        pkt->dts= st->pts_buffer[0];
2828
    }
2829

    
2830
    if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2831
        av_log(s, AV_LOG_ERROR,
2832
               "st:%d error, non monotone timestamps %"PRId64" >= %"PRId64"\n",
2833
               st->index, st->cur_dts, pkt->dts);
2834
        return -1;
2835
    }
2836
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2837
        av_log(s, AV_LOG_ERROR, "st:%d error, pts < dts\n", st->index);
2838
        return -1;
2839
    }
2840

    
2841
//    av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
2842
    st->cur_dts= pkt->dts;
2843
    st->pts.val= pkt->dts;
2844

    
2845
    /* update pts */
2846
    switch (st->codec->codec_type) {
2847
    case AVMEDIA_TYPE_AUDIO:
2848
        frame_size = get_audio_frame_size(st->codec, pkt->size);
2849

    
2850
        /* HACK/FIXME, we skip the initial 0 size packets as they are most
2851
           likely equal to the encoder delay, but it would be better if we
2852
           had the real timestamps from the encoder */
2853
        if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2854
            av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2855
        }
2856
        break;
2857
    case AVMEDIA_TYPE_VIDEO:
2858
        av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
2859
        break;
2860
    default:
2861
        break;
2862
    }
2863
    return 0;
2864
}
2865

    
2866
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2867
{
2868
    int ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
2869

    
2870
    if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2871
        return ret;
2872

    
2873
    ret= s->oformat->write_packet(s, pkt);
2874
    if(!ret)
2875
        ret= url_ferror(s->pb);
2876
    return ret;
2877
}
2878

    
2879
void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
2880
                              int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
2881
{
2882
    AVPacketList **next_point, *this_pktl;
2883

    
2884
    this_pktl = av_mallocz(sizeof(AVPacketList));
2885
    this_pktl->pkt= *pkt;
2886
    pkt->destruct= NULL;             // do not free original but only the copy
2887
    av_dup_packet(&this_pktl->pkt);  // duplicate the packet if it uses non-alloced memory
2888

    
2889
    if(s->streams[pkt->stream_index]->last_in_packet_buffer){
2890
        next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
2891
    }else
2892
        next_point = &s->packet_buffer;
2893

    
2894
    if(*next_point){
2895
        if(compare(s, &s->packet_buffer_end->pkt, pkt)){
2896
            while(!compare(s, &(*next_point)->pkt, pkt)){
2897
                next_point= &(*next_point)->next;
2898
            }
2899
            goto next_non_null;
2900
        }else{
2901
            next_point = &(s->packet_buffer_end->next);
2902
        }
2903
    }
2904
    assert(!*next_point);
2905

    
2906
    s->packet_buffer_end= this_pktl;
2907
next_non_null:
2908

    
2909
    this_pktl->next= *next_point;
2910

    
2911
    s->streams[pkt->stream_index]->last_in_packet_buffer=
2912
    *next_point= this_pktl;
2913
}
2914

    
2915
int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
2916
{
2917
    AVStream *st = s->streams[ pkt ->stream_index];
2918
    AVStream *st2= s->streams[ next->stream_index];
2919
    int64_t a= st2->time_base.num * (int64_t)st ->time_base.den;
2920
    int64_t b= st ->time_base.num * (int64_t)st2->time_base.den;
2921
    return av_rescale_rnd(pkt->dts, b, a, AV_ROUND_DOWN) < next->dts;
2922
}
2923

    
2924
int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2925
    AVPacketList *pktl;
2926
    int stream_count=0;
2927
    int i;
2928

    
2929
    if(pkt){
2930
        ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
2931
    }
2932

    
2933
    for(i=0; i < s->nb_streams; i++)
2934
        stream_count+= !!s->streams[i]->last_in_packet_buffer;
2935

    
2936
    if(stream_count && (s->nb_streams == stream_count || flush)){
2937
        pktl= s->packet_buffer;
2938
        *out= pktl->pkt;
2939

    
2940
        s->packet_buffer= pktl->next;
2941
        if(!s->packet_buffer)
2942
            s->packet_buffer_end= NULL;
2943

    
2944
        if(s->streams[out->stream_index]->last_in_packet_buffer == pktl)
2945
            s->streams[out->stream_index]->last_in_packet_buffer= NULL;
2946
        av_freep(&pktl);
2947
        return 1;
2948
    }else{
2949
        av_init_packet(out);
2950
        return 0;
2951
    }
2952
}
2953

    
2954
/**
2955
 * Interleave an AVPacket correctly so it can be muxed.
2956
 * @param out the interleaved packet will be output here
2957
 * @param in the input packet
2958
 * @param flush 1 if no further packets are available as input and all
2959
 *              remaining packets should be output
2960
 * @return 1 if a packet was output, 0 if no packet could be output,
2961
 *         < 0 if an error occurred
2962
 */
2963
static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2964
    if(s->oformat->interleave_packet)
2965
        return s->oformat->interleave_packet(s, out, in, flush);
2966
    else
2967
        return av_interleave_packet_per_dts(s, out, in, flush);
2968
}
2969

    
2970
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2971
    AVStream *st= s->streams[ pkt->stream_index];
2972

    
2973
    //FIXME/XXX/HACK drop zero sized packets
2974
    if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size==0)
2975
        return 0;
2976

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

    
2981
    if(pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2982
        return -1;
2983

    
2984
    for(;;){
2985
        AVPacket opkt;
2986
        int ret= av_interleave_packet(s, &opkt, pkt, 0);
2987
        if(ret<=0) //FIXME cleanup needed for ret<0 ?
2988
            return ret;
2989

    
2990
        ret= s->oformat->write_packet(s, &opkt);
2991

    
2992
        av_free_packet(&opkt);
2993
        pkt= NULL;
2994

    
2995
        if(ret<0)
2996
            return ret;
2997
        if(url_ferror(s->pb))
2998
            return url_ferror(s->pb);
2999
    }
3000
}
3001

    
3002
int av_write_trailer(AVFormatContext *s)
3003
{
3004
    int ret, i;
3005

    
3006
    for(;;){
3007
        AVPacket pkt;
3008
        ret= av_interleave_packet(s, &pkt, NULL, 1);
3009
        if(ret<0) //FIXME cleanup needed for ret<0 ?
3010
            goto fail;
3011
        if(!ret)
3012
            break;
3013

    
3014
        ret= s->oformat->write_packet(s, &pkt);
3015

    
3016
        av_free_packet(&pkt);
3017

    
3018
        if(ret<0)
3019
            goto fail;
3020
        if(url_ferror(s->pb))
3021
            goto fail;
3022
    }
3023

    
3024
    if(s->oformat->write_trailer)
3025
        ret = s->oformat->write_trailer(s);
3026
fail:
3027
    if(ret == 0)
3028
       ret=url_ferror(s->pb);
3029
    for(i=0;i<s->nb_streams;i++) {
3030
        av_freep(&s->streams[i]->priv_data);
3031
        av_freep(&s->streams[i]->index_entries);
3032
    }
3033
    av_freep(&s->priv_data);
3034
    return ret;
3035
}
3036

    
3037
void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
3038
{
3039
    int i, j;
3040
    AVProgram *program=NULL;
3041
    void *tmp;
3042

    
3043
    if (idx >= ac->nb_streams) {
3044
        av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
3045
        return;
3046
    }
3047

    
3048
    for(i=0; i<ac->nb_programs; i++){
3049
        if(ac->programs[i]->id != progid)
3050
            continue;
3051
        program = ac->programs[i];
3052
        for(j=0; j<program->nb_stream_indexes; j++)
3053
            if(program->stream_index[j] == idx)
3054
                return;
3055

    
3056
        tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
3057
        if(!tmp)
3058
            return;
3059
        program->stream_index = tmp;
3060
        program->stream_index[program->nb_stream_indexes++] = idx;
3061
        return;
3062
    }
3063
}
3064

    
3065
static void print_fps(double d, const char *postfix){
3066
    uint64_t v= lrintf(d*100);
3067
    if     (v% 100      ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
3068
    else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
3069
    else                  av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
3070
}
3071

    
3072
static void dump_metadata(void *ctx, AVMetadata *m, const char *indent)
3073
{
3074
    if(m && !(m->count == 1 && av_metadata_get(m, "language", NULL, 0))){
3075
        AVMetadataTag *tag=NULL;
3076

    
3077
        av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
3078
        while((tag=av_metadata_get(m, "", tag, AV_METADATA_IGNORE_SUFFIX))) {
3079
            if(strcmp("language", tag->key))
3080
                av_log(ctx, AV_LOG_INFO, "%s  %-16s: %s\n", indent, tag->key, tag->value);
3081
        }
3082
    }
3083
}
3084

    
3085
/* "user interface" functions */
3086
static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
3087
{
3088
    char buf[256];
3089
    int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
3090
    AVStream *st = ic->streams[i];
3091
    int g = av_gcd(st->time_base.num, st->time_base.den);
3092
    AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL, 0);
3093
    avcodec_string(buf, sizeof(buf), st->codec, is_output);
3094
    av_log(NULL, AV_LOG_INFO, "    Stream #%d.%d", index, i);
3095
    /* the pid is an important information, so we display it */
3096
    /* XXX: add a generic system */
3097
    if (flags & AVFMT_SHOW_IDS)
3098
        av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
3099
    if (lang)
3100
        av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
3101
    av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
3102
    av_log(NULL, AV_LOG_INFO, ": %s", buf);
3103
    if (st->sample_aspect_ratio.num && // default
3104
        av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
3105
        AVRational display_aspect_ratio;
3106
        av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
3107
                  st->codec->width*st->sample_aspect_ratio.num,
3108
                  st->codec->height*st->sample_aspect_ratio.den,
3109
                  1024*1024);
3110
        av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
3111
                 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
3112
                 display_aspect_ratio.num, display_aspect_ratio.den);
3113
    }
3114
    if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
3115
        if(st->avg_frame_rate.den && st->avg_frame_rate.num)
3116
            print_fps(av_q2d(st->avg_frame_rate), "fps");
3117
        if(st->r_frame_rate.den && st->r_frame_rate.num)
3118
            print_fps(av_q2d(st->r_frame_rate), "tbr");
3119
        if(st->time_base.den && st->time_base.num)
3120
            print_fps(1/av_q2d(st->time_base), "tbn");
3121
        if(st->codec->time_base.den && st->codec->time_base.num)
3122
            print_fps(1/av_q2d(st->codec->time_base), "tbc");
3123
    }
3124
    av_log(NULL, AV_LOG_INFO, "\n");
3125
    dump_metadata(NULL, st->metadata, "    ");
3126
}
3127

    
3128
void dump_format(AVFormatContext *ic,
3129
                 int index,
3130
                 const char *url,
3131
                 int is_output)
3132
{
3133
    int i;
3134
    uint8_t *printed = av_mallocz(ic->nb_streams);
3135
    if (ic->nb_streams && !printed)
3136
        return;
3137

    
3138
    av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
3139
            is_output ? "Output" : "Input",
3140
            index,
3141
            is_output ? ic->oformat->name : ic->iformat->name,
3142
            is_output ? "to" : "from", url);
3143
    dump_metadata(NULL, ic->metadata, "  ");
3144
    if (!is_output) {
3145
        av_log(NULL, AV_LOG_INFO, "  Duration: ");
3146
        if (ic->duration != AV_NOPTS_VALUE) {
3147
            int hours, mins, secs, us;
3148
            secs = ic->duration / AV_TIME_BASE;
3149
            us = ic->duration % AV_TIME_BASE;
3150
            mins = secs / 60;
3151
            secs %= 60;
3152
            hours = mins / 60;
3153
            mins %= 60;
3154
            av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
3155
                   (100 * us) / AV_TIME_BASE);
3156
        } else {
3157
            av_log(NULL, AV_LOG_INFO, "N/A");
3158
        }
3159
        if (ic->start_time != AV_NOPTS_VALUE) {
3160
            int secs, us;
3161
            av_log(NULL, AV_LOG_INFO, ", start: ");
3162
            secs = ic->start_time / AV_TIME_BASE;
3163
            us = abs(ic->start_time % AV_TIME_BASE);
3164
            av_log(NULL, AV_LOG_INFO, "%d.%06d",
3165
                   secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
3166
        }
3167
        av_log(NULL, AV_LOG_INFO, ", bitrate: ");
3168
        if (ic->bit_rate) {
3169
            av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
3170
        } else {
3171
            av_log(NULL, AV_LOG_INFO, "N/A");
3172
        }
3173
        av_log(NULL, AV_LOG_INFO, "\n");
3174
    }
3175
    for (i = 0; i < ic->nb_chapters; i++) {
3176
        AVChapter *ch = ic->chapters[i];
3177
        av_log(NULL, AV_LOG_INFO, "    Chapter #%d.%d: ", index, i);
3178
        av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
3179
        av_log(NULL, AV_LOG_INFO, "end %f\n",   ch->end   * av_q2d(ch->time_base));
3180

    
3181
        dump_metadata(NULL, ch->metadata, "    ");
3182
    }
3183
    if(ic->nb_programs) {
3184
        int j, k, total = 0;
3185
        for(j=0; j<ic->nb_programs; j++) {
3186
            AVMetadataTag *name = av_metadata_get(ic->programs[j]->metadata,
3187
                                                  "name", NULL, 0);
3188
            av_log(NULL, AV_LOG_INFO, "  Program %d %s\n", ic->programs[j]->id,
3189
                   name ? name->value : "");
3190
            dump_metadata(NULL, ic->programs[j]->metadata, "    ");
3191
            for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
3192
                dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
3193
                printed[ic->programs[j]->stream_index[k]] = 1;
3194
            }
3195
            total += ic->programs[j]->nb_stream_indexes;
3196
        }
3197
        if (total < ic->nb_streams)
3198
            av_log(NULL, AV_LOG_INFO, "  No Program\n");
3199
    }
3200
    for(i=0;i<ic->nb_streams;i++)
3201
        if (!printed[i])
3202
            dump_stream_format(ic, i, index, is_output);
3203

    
3204
    av_free(printed);
3205
}
3206

    
3207
#if FF_API_PARSE_FRAME_PARAM
3208
#include "libavcore/parseutils.h"
3209

    
3210
int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
3211
{
3212
    return av_parse_video_size(width_ptr, height_ptr, str);
3213
}
3214

    
3215
int parse_frame_rate(int *frame_rate_num, int *frame_rate_den, const char *arg)
3216
{
3217
    AVRational frame_rate;
3218
    int ret = av_parse_video_rate(&frame_rate, arg);
3219
    *frame_rate_num= frame_rate.num;
3220
    *frame_rate_den= frame_rate.den;
3221
    return ret;
3222
}
3223
#endif
3224

    
3225
int64_t av_gettime(void)
3226
{
3227
    struct timeval tv;
3228
    gettimeofday(&tv,NULL);
3229
    return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
3230
}
3231

    
3232
uint64_t ff_ntp_time(void)
3233
{
3234
  return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
3235
}
3236

    
3237
int64_t parse_date(const char *datestr, int duration)
3238
{
3239
    const char *p;
3240
    int64_t t;
3241
    struct tm dt;
3242
    int i;
3243
    static const char * const date_fmt[] = {
3244
        "%Y-%m-%d",
3245
        "%Y%m%d",
3246
    };
3247
    static const char * const time_fmt[] = {
3248
        "%H:%M:%S",
3249
        "%H%M%S",
3250
    };
3251
    const char *q;
3252
    int is_utc, len;
3253
    char lastch;
3254
    int negative = 0;
3255

    
3256
#undef time
3257
    time_t now = time(0);
3258

    
3259
    len = strlen(datestr);
3260
    if (len > 0)
3261
        lastch = datestr[len - 1];
3262
    else
3263
        lastch = '\0';
3264
    is_utc = (lastch == 'z' || lastch == 'Z');
3265

    
3266
    memset(&dt, 0, sizeof(dt));
3267

    
3268
    p = datestr;
3269
    q = NULL;
3270
    if (!duration) {
3271
        if (!strncasecmp(datestr, "now", len))
3272
            return (int64_t) now * 1000000;
3273

    
3274
        /* parse the year-month-day part */
3275
        for (i = 0; i < FF_ARRAY_ELEMS(date_fmt); i++) {
3276
            q = small_strptime(p, date_fmt[i], &dt);
3277
            if (q) {
3278
                break;
3279
            }
3280
        }
3281

    
3282
        /* if the year-month-day part is missing, then take the
3283
         * current year-month-day time */
3284
        if (!q) {
3285
            if (is_utc) {
3286
                dt = *gmtime(&now);
3287
            } else {
3288
                dt = *localtime(&now);
3289
            }
3290
            dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
3291
        } else {
3292
            p = q;
3293
        }
3294

    
3295
        if (*p == 'T' || *p == 't' || *p == ' ')
3296
            p++;
3297

    
3298
        /* parse the hour-minute-second part */
3299
        for (i = 0; i < FF_ARRAY_ELEMS(time_fmt); i++) {
3300
            q = small_strptime(p, time_fmt[i], &dt);
3301
            if (q) {
3302
                break;
3303
            }
3304
        }
3305
    } else {
3306
        /* parse datestr as a duration */
3307
        if (p[0] == '-') {
3308
            negative = 1;
3309
            ++p;
3310
        }
3311
        /* parse datestr as HH:MM:SS */
3312
        q = small_strptime(p, time_fmt[0], &dt);
3313
        if (!q) {
3314
            /* parse datestr as S+ */
3315
            dt.tm_sec = strtol(p, (char **)&q, 10);
3316
            if (q == p)
3317
                /* the parsing didn't succeed */
3318
                return INT64_MIN;
3319
            dt.tm_min = 0;
3320
            dt.tm_hour = 0;
3321
        }
3322
    }
3323

    
3324
    /* Now we have all the fields that we can get */
3325
    if (!q) {
3326
        return INT64_MIN;
3327
    }
3328

    
3329
    if (duration) {
3330
        t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
3331
    } else {
3332
        dt.tm_isdst = -1;       /* unknown */
3333
        if (is_utc) {
3334
            t = mktimegm(&dt);
3335
        } else {
3336
            t = mktime(&dt);
3337
        }
3338
    }
3339

    
3340
    t *= 1000000;
3341

    
3342
    /* parse the .m... part */
3343
    if (*q == '.') {
3344
        int val, n;
3345
        q++;
3346
        for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
3347
            if (!isdigit(*q))
3348
                break;
3349
            val += n * (*q - '0');
3350
        }
3351
        t += val;
3352
    }
3353
    return negative ? -t : t;
3354
}
3355

    
3356
int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
3357
{
3358
    const char *p;
3359
    char tag[128], *q;
3360

    
3361
    p = info;
3362
    if (*p == '?')
3363
        p++;
3364
    for(;;) {
3365
        q = tag;
3366
        while (*p != '\0' && *p != '=' && *p != '&') {
3367
            if ((q - tag) < sizeof(tag) - 1)
3368
                *q++ = *p;
3369
            p++;
3370
        }
3371
        *q = '\0';
3372
        q = arg;
3373
        if (*p == '=') {
3374
            p++;
3375
            while (*p != '&' && *p != '\0') {
3376
                if ((q - arg) < arg_size - 1) {
3377
                    if (*p == '+')
3378
                        *q++ = ' ';
3379
                    else
3380
                        *q++ = *p;
3381
                }
3382
                p++;
3383
            }
3384
        }
3385
        *q = '\0';
3386
        if (!strcmp(tag, tag1))
3387
            return 1;
3388
        if (*p != '&')
3389
            break;
3390
        p++;
3391
    }
3392
    return 0;
3393
}
3394

    
3395
int av_get_frame_filename(char *buf, int buf_size,
3396
                          const char *path, int number)
3397
{
3398
    const char *p;
3399
    char *q, buf1[20], c;
3400
    int nd, len, percentd_found;
3401

    
3402
    q = buf;
3403
    p = path;
3404
    percentd_found = 0;
3405
    for(;;) {
3406
        c = *p++;
3407
        if (c == '\0')
3408
            break;
3409
        if (c == '%') {
3410
            do {
3411
                nd = 0;
3412
                while (isdigit(*p)) {
3413
                    nd = nd * 10 + *p++ - '0';
3414
                }
3415
                c = *p++;
3416
            } while (isdigit(c));
3417

    
3418
            switch(c) {
3419
            case '%':
3420
                goto addchar;
3421
            case 'd':
3422
                if (percentd_found)
3423
                    goto fail;
3424
                percentd_found = 1;
3425
                snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3426
                len = strlen(buf1);
3427
                if ((q - buf + len) > buf_size - 1)
3428
                    goto fail;
3429
                memcpy(q, buf1, len);
3430
                q += len;
3431
                break;
3432
            default:
3433
                goto fail;
3434
            }
3435
        } else {
3436
        addchar:
3437
            if ((q - buf) < buf_size - 1)
3438
                *q++ = c;
3439
        }
3440
    }
3441
    if (!percentd_found)
3442
        goto fail;
3443
    *q = '\0';
3444
    return 0;
3445
 fail:
3446
    *q = '\0';
3447
    return -1;
3448
}
3449

    
3450
static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
3451
{
3452
    int len, i, j, c;
3453
#undef fprintf
3454
#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3455

    
3456
    for(i=0;i<size;i+=16) {
3457
        len = size - i;
3458
        if (len > 16)
3459
            len = 16;
3460
        PRINT("%08x ", i);
3461
        for(j=0;j<16;j++) {
3462
            if (j < len)
3463
                PRINT(" %02x", buf[i+j]);
3464
            else
3465
                PRINT("   ");
3466
        }
3467
        PRINT(" ");
3468
        for(j=0;j<len;j++) {
3469
            c = buf[i+j];
3470
            if (c < ' ' || c > '~')
3471
                c = '.';
3472
            PRINT("%c", c);
3473
        }
3474
        PRINT("\n");
3475
    }
3476
#undef PRINT
3477
}
3478

    
3479
void av_hex_dump(FILE *f, uint8_t *buf, int size)
3480
{
3481
    hex_dump_internal(NULL, f, 0, buf, size);
3482
}
3483

    
3484
void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
3485
{
3486
    hex_dump_internal(avcl, NULL, level, buf, size);
3487
}
3488

    
3489
 //FIXME needs to know the time_base
3490
static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload)
3491
{
3492
#undef fprintf
3493
#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3494
    PRINT("stream #%d:\n", pkt->stream_index);
3495
    PRINT("  keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
3496
    PRINT("  duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
3497
    /* DTS is _always_ valid after av_read_frame() */
3498
    PRINT("  dts=");
3499
    if (pkt->dts == AV_NOPTS_VALUE)
3500
        PRINT("N/A");
3501
    else
3502
        PRINT("%0.3f", (double)pkt->dts / AV_TIME_BASE);
3503
    /* PTS may not be known if B-frames are present. */
3504
    PRINT("  pts=");
3505
    if (pkt->pts == AV_NOPTS_VALUE)
3506
        PRINT("N/A");
3507
    else
3508
        PRINT("%0.3f", (double)pkt->pts / AV_TIME_BASE);
3509
    PRINT("\n");
3510
    PRINT("  size=%d\n", pkt->size);
3511
#undef PRINT
3512
    if (dump_payload)
3513
        av_hex_dump(f, pkt->data, pkt->size);
3514
}
3515

    
3516
void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3517
{
3518
    pkt_dump_internal(NULL, f, 0, pkt, dump_payload);
3519
}
3520

    
3521
void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
3522
{
3523
    pkt_dump_internal(avcl, NULL, level, pkt, dump_payload);
3524
}
3525

    
3526
#if FF_API_URL_SPLIT
3527
attribute_deprecated
3528
void ff_url_split(char *proto, int proto_size,
3529
                  char *authorization, int authorization_size,
3530
                  char *hostname, int hostname_size,
3531
                  int *port_ptr,
3532
                  char *path, int path_size,
3533
                  const char *url)
3534
{
3535
    av_url_split(proto, proto_size,
3536
                 authorization, authorization_size,
3537
                 hostname, hostname_size,
3538
                 port_ptr,
3539
                 path, path_size,
3540
                 url);
3541
}
3542
#endif
3543

    
3544
void av_url_split(char *proto, int proto_size,
3545
                  char *authorization, int authorization_size,
3546
                  char *hostname, int hostname_size,
3547
                  int *port_ptr,
3548
                  char *path, int path_size,
3549
                  const char *url)
3550
{
3551
    const char *p, *ls, *at, *col, *brk;
3552

    
3553
    if (port_ptr)               *port_ptr = -1;
3554
    if (proto_size > 0)         proto[0] = 0;
3555
    if (authorization_size > 0) authorization[0] = 0;
3556
    if (hostname_size > 0)      hostname[0] = 0;
3557
    if (path_size > 0)          path[0] = 0;
3558

    
3559
    /* parse protocol */
3560
    if ((p = strchr(url, ':'))) {
3561
        av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3562
        p++; /* skip ':' */
3563
        if (*p == '/') p++;
3564
        if (*p == '/') p++;
3565
    } else {
3566
        /* no protocol means plain filename */
3567
        av_strlcpy(path, url, path_size);
3568
        return;
3569
    }
3570

    
3571
    /* separate path from hostname */
3572
    ls = strchr(p, '/');
3573
    if(!ls)
3574
        ls = strchr(p, '?');
3575
    if(ls)
3576
        av_strlcpy(path, ls, path_size);
3577
    else
3578
        ls = &p[strlen(p)]; // XXX
3579

    
3580
    /* the rest is hostname, use that to parse auth/port */
3581
    if (ls != p) {
3582
        /* authorization (user[:pass]@hostname) */
3583
        if ((at = strchr(p, '@')) && at < ls) {
3584
            av_strlcpy(authorization, p,
3585
                       FFMIN(authorization_size, at + 1 - p));
3586
            p = at + 1; /* skip '@' */
3587
        }
3588

    
3589
        if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3590
            /* [host]:port */
3591
            av_strlcpy(hostname, p + 1,
3592
                       FFMIN(hostname_size, brk - p));
3593
            if (brk[1] == ':' && port_ptr)
3594
                *port_ptr = atoi(brk + 2);
3595
        } else if ((col = strchr(p, ':')) && col < ls) {
3596
            av_strlcpy(hostname, p,
3597
                       FFMIN(col + 1 - p, hostname_size));
3598
            if (port_ptr) *port_ptr = atoi(col + 1);
3599
        } else
3600
            av_strlcpy(hostname, p,
3601
                       FFMIN(ls + 1 - p, hostname_size));
3602
    }
3603
}
3604

    
3605
char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3606
{
3607
    int i;
3608
    static const char hex_table_uc[16] = { '0', '1', '2', '3',
3609
                                           '4', '5', '6', '7',
3610
                                           '8', '9', 'A', 'B',
3611
                                           'C', 'D', 'E', 'F' };
3612
    static const char hex_table_lc[16] = { '0', '1', '2', '3',
3613
                                           '4', '5', '6', '7',
3614
                                           '8', '9', 'a', 'b',
3615
                                           'c', 'd', 'e', 'f' };
3616
    const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3617

    
3618
    for(i = 0; i < s; i++) {
3619
        buff[i * 2]     = hex_table[src[i] >> 4];
3620
        buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3621
    }
3622

    
3623
    return buff;
3624
}
3625

    
3626
int ff_hex_to_data(uint8_t *data, const char *p)
3627
{
3628
    int c, len, v;
3629

    
3630
    len = 0;
3631
    v = 1;
3632
    for (;;) {
3633
        p += strspn(p, SPACE_CHARS);
3634
        if (*p == '\0')
3635
            break;
3636
        c = toupper((unsigned char) *p++);
3637
        if (c >= '0' && c <= '9')
3638
            c = c - '0';
3639
        else if (c >= 'A' && c <= 'F')
3640
            c = c - 'A' + 10;
3641
        else
3642
            break;
3643
        v = (v << 4) | c;
3644
        if (v & 0x100) {
3645
            if (data)
3646
                data[len] = v;
3647
            len++;
3648
            v = 1;
3649
        }
3650
    }
3651
    return len;
3652
}
3653

    
3654
void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3655
                     unsigned int pts_num, unsigned int pts_den)
3656
{
3657
    s->pts_wrap_bits = pts_wrap_bits;
3658

    
3659
    if(av_reduce(&s->time_base.num, &s->time_base.den, pts_num, pts_den, INT_MAX)){
3660
        if(s->time_base.num != pts_num)
3661
            av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/s->time_base.num);
3662
    }else
3663
        av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3664

    
3665
    if(!s->time_base.num || !s->time_base.den)
3666
        s->time_base.num= s->time_base.den= 0;
3667
}
3668

    
3669
int ff_url_join(char *str, int size, const char *proto,
3670
                const char *authorization, const char *hostname,
3671
                int port, const char *fmt, ...)
3672
{
3673
#if CONFIG_NETWORK
3674
    struct addrinfo hints, *ai;
3675
#endif
3676

    
3677
    str[0] = '\0';
3678
    if (proto)
3679
        av_strlcatf(str, size, "%s://", proto);
3680
    if (authorization && authorization[0])
3681
        av_strlcatf(str, size, "%s@", authorization);
3682
#if CONFIG_NETWORK && defined(AF_INET6)
3683
    /* Determine if hostname is a numerical IPv6 address,
3684
     * properly escape it within [] in that case. */
3685
    memset(&hints, 0, sizeof(hints));
3686
    hints.ai_flags = AI_NUMERICHOST;
3687
    if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
3688
        if (ai->ai_family == AF_INET6) {
3689
            av_strlcat(str, "[", size);
3690
            av_strlcat(str, hostname, size);
3691
            av_strlcat(str, "]", size);
3692
        } else {
3693
            av_strlcat(str, hostname, size);
3694
        }
3695
        freeaddrinfo(ai);
3696
    } else
3697
#endif
3698
        /* Not an IPv6 address, just output the plain string. */
3699
        av_strlcat(str, hostname, size);
3700

    
3701
    if (port >= 0)
3702
        av_strlcatf(str, size, ":%d", port);
3703
    if (fmt) {
3704
        va_list vl;
3705
        int len = strlen(str);
3706

    
3707
        va_start(vl, fmt);
3708
        vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
3709
        va_end(vl);
3710
    }
3711
    return strlen(str);
3712
}
3713

    
3714
int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
3715
                     AVFormatContext *src)
3716
{
3717
    AVPacket local_pkt;
3718

    
3719
    local_pkt = *pkt;
3720
    local_pkt.stream_index = dst_stream;
3721
    if (pkt->pts != AV_NOPTS_VALUE)
3722
        local_pkt.pts = av_rescale_q(pkt->pts,
3723
                                     src->streams[pkt->stream_index]->time_base,
3724
                                     dst->streams[dst_stream]->time_base);
3725
    if (pkt->dts != AV_NOPTS_VALUE)
3726
        local_pkt.dts = av_rescale_q(pkt->dts,
3727
                                     src->streams[pkt->stream_index]->time_base,
3728
                                     dst->streams[dst_stream]->time_base);
3729
    return av_write_frame(dst, &local_pkt);
3730
}
3731

    
3732
void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3733
                        void *context)
3734
{
3735
    const char *ptr = str;
3736

    
3737
    /* Parse key=value pairs. */
3738
    for (;;) {
3739
        const char *key;
3740
        char *dest = NULL, *dest_end;
3741
        int key_len, dest_len = 0;
3742

    
3743
        /* Skip whitespace and potential commas. */
3744
        while (*ptr && (isspace(*ptr) || *ptr == ','))
3745
            ptr++;
3746
        if (!*ptr)
3747
            break;
3748

    
3749
        key = ptr;
3750

    
3751
        if (!(ptr = strchr(key, '=')))
3752
            break;
3753
        ptr++;
3754
        key_len = ptr - key;
3755

    
3756
        callback_get_buf(context, key, key_len, &dest, &dest_len);
3757
        dest_end = dest + dest_len - 1;
3758

    
3759
        if (*ptr == '\"') {
3760
            ptr++;
3761
            while (*ptr && *ptr != '\"') {
3762
                if (*ptr == '\\') {
3763
                    if (!ptr[1])
3764
                        break;
3765
                    if (dest && dest < dest_end)
3766
                        *dest++ = ptr[1];
3767
                    ptr += 2;
3768
                } else {
3769
                    if (dest && dest < dest_end)
3770
                        *dest++ = *ptr;
3771
                    ptr++;
3772
                }
3773
            }
3774
            if (*ptr == '\"')
3775
                ptr++;
3776
        } else {
3777
            for (; *ptr && !(isspace(*ptr) || *ptr == ','); ptr++)
3778
                if (dest && dest < dest_end)
3779
                    *dest++ = *ptr;
3780
        }
3781
        if (dest)
3782
            *dest = 0;
3783
    }
3784
}
3785