Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ 58d5ff0a

History | View | Annotate | Download (122 KB)

1 de6d9b64 Fabrice Bellard
/*
2 2912e87a Mans Rullgard
 * various utility functions for use within Libav
3 19720f15 Fabrice Bellard
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4 de6d9b64 Fabrice Bellard
 *
5 2912e87a Mans Rullgard
 * This file is part of Libav.
6 b78e7197 Diego Biurrun
 *
7 2912e87a Mans Rullgard
 * Libav is free software; you can redistribute it and/or
8 19720f15 Fabrice Bellard
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10 b78e7197 Diego Biurrun
 * version 2.1 of the License, or (at your option) any later version.
11 de6d9b64 Fabrice Bellard
 *
12 2912e87a Mans Rullgard
 * Libav is distributed in the hope that it will be useful,
13 de6d9b64 Fabrice Bellard
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 19720f15 Fabrice Bellard
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16 de6d9b64 Fabrice Bellard
 *
17 19720f15 Fabrice Bellard
 * You should have received a copy of the GNU Lesser General Public
18 2912e87a Mans Rullgard
 * License along with Libav; if not, write to the Free Software
19 5509bffa Diego Biurrun
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 de6d9b64 Fabrice Bellard
 */
21 79f43a8c Stefano Sabatini
22
/* #define DEBUG */
23
24 8be1c656 Fabrice Bellard
#include "avformat.h"
25 f1ef2cd9 Anton Khirnov
#include "avio_internal.h"
26 f1c80e35 Ronald S. Bultje
#include "internal.h"
27 603a5f04 Francesco Lavra
#include "libavcodec/internal.h"
28 6ed04040 Michael Niedermayer
#include "libavutil/opt.h"
29 06a7bd9a Michael Niedermayer
#include "metadata.h"
30 6612d8cf Reimar Döffinger
#include "id3v2.h"
31 245976da Diego Biurrun
#include "libavutil/avstring.h"
32 45da8124 Aurelien Jacobs
#include "riff.h"
33 c26e58e3 Måns Rullgård
#include "audiointerleave.h"
34 5cec8971 Anton Khirnov
#include "url.h"
35 82e4ac2c Ramiro Polla
#include <sys/time.h>
36
#include <time.h>
37 ea452b54 Aurelien Jacobs
#include <strings.h>
38 780d7897 Martin Storsjö
#include <stdarg.h>
39
#if CONFIG_NETWORK
40
#include "network.h"
41
#endif
42 c5510dd6 Philip Gladstone
43 b754978a Michael Niedermayer
#undef NDEBUG
44
#include <assert.h>
45
46 e36bdf8b Daniel Kristjansson
/**
47 ba87f080 Diego Biurrun
 * @file
48 2912e87a Mans Rullgard
 * various utility functions for use within Libav
49 e36bdf8b Daniel Kristjansson
 */
50
51 c97429e2 Stefano Sabatini
unsigned avformat_version(void)
52
{
53
    return LIBAVFORMAT_VERSION_INT;
54
}
55
56 41600690 Stefano Sabatini
const char *avformat_configuration(void)
57 c1736936 Diego Biurrun
{
58 29ba0911 Janne Grunau
    return LIBAV_CONFIGURATION;
59 c1736936 Diego Biurrun
}
60
61 41600690 Stefano Sabatini
const char *avformat_license(void)
62 c1736936 Diego Biurrun
{
63
#define LICENSE_PREFIX "libavformat license: "
64 a03be6e1 Janne Grunau
    return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
65 c1736936 Diego Biurrun
}
66
67 8163c870 Stefano Sabatini
/* fraction handling */
68
69
/**
70
 * f = val + (num / den) + 0.5.
71
 *
72
 * 'num' is normalized so that it is such as 0 <= num < den.
73
 *
74
 * @param f fractional number
75
 * @param val integer value
76
 * @param num must be >= 0
77
 * @param den must be >= 1
78
 */
79
static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
80
{
81
    num += (den >> 1);
82
    if (num >= den) {
83
        val += num / den;
84
        num = num % den;
85
    }
86
    f->val = val;
87
    f->num = num;
88
    f->den = den;
89
}
90
91
/**
92
 * Fractional addition to f: f = f + (incr / f->den).
93
 *
94
 * @param f fractional number
95
 * @param incr increment, can be positive or negative
96
 */
97
static void av_frac_add(AVFrac *f, int64_t incr)
98
{
99
    int64_t num, den;
100
101
    num = f->num + incr;
102
    den = f->den;
103
    if (num < 0) {
104
        f->val += num / den;
105
        num = num % den;
106
        if (num < 0) {
107
            num += den;
108
            f->val--;
109
        }
110
    } else if (num >= den) {
111
        f->val += num / den;
112
        num = num % den;
113
    }
114
    f->num = num;
115
}
116 f3a30e3a Luca Barbato
117 a85736f2 Diego Biurrun
/** head of registered input format linked list */
118 114c9a59 Aurelien Jacobs
#if !FF_API_FIRST_FORMAT
119
static
120
#endif
121 8b69867f Michael Niedermayer
AVInputFormat *first_iformat = NULL;
122 a85736f2 Diego Biurrun
/** head of registered output format linked list */
123 114c9a59 Aurelien Jacobs
#if !FF_API_FIRST_FORMAT
124
static
125
#endif
126 8b69867f Michael Niedermayer
AVOutputFormat *first_oformat = NULL;
127 de6d9b64 Fabrice Bellard
128 84be6e72 Michael Niedermayer
AVInputFormat  *av_iformat_next(AVInputFormat  *f)
129
{
130
    if(f) return f->next;
131
    else  return first_iformat;
132
}
133
134
AVOutputFormat *av_oformat_next(AVOutputFormat *f)
135
{
136
    if(f) return f->next;
137
    else  return first_oformat;
138
}
139
140 b9a281db Fabrice Bellard
void av_register_input_format(AVInputFormat *format)
141 de6d9b64 Fabrice Bellard
{
142 b9a281db Fabrice Bellard
    AVInputFormat **p;
143
    p = &first_iformat;
144
    while (*p != NULL) p = &(*p)->next;
145
    *p = format;
146
    format->next = NULL;
147
}
148
149
void av_register_output_format(AVOutputFormat *format)
150
{
151
    AVOutputFormat **p;
152
    p = &first_oformat;
153 de6d9b64 Fabrice Bellard
    while (*p != NULL) p = &(*p)->next;
154
    *p = format;
155
    format->next = NULL;
156
}
157
158 8eb631fa Stefano Sabatini
int av_match_ext(const char *filename, const char *extensions)
159
{
160 de6d9b64 Fabrice Bellard
    const char *ext, *p;
161
    char ext1[32], *q;
162
163 293ed23f Michael Niedermayer
    if(!filename)
164
        return 0;
165 115329f1 Diego Biurrun
166 de6d9b64 Fabrice Bellard
    ext = strrchr(filename, '.');
167
    if (ext) {
168
        ext++;
169
        p = extensions;
170
        for(;;) {
171
            q = ext1;
172 115329f1 Diego Biurrun
            while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
173 de6d9b64 Fabrice Bellard
                *q++ = *p++;
174
            *q = '\0';
175 115329f1 Diego Biurrun
            if (!strcasecmp(ext1, ext))
176 de6d9b64 Fabrice Bellard
                return 1;
177 115329f1 Diego Biurrun
            if (*p == '\0')
178 de6d9b64 Fabrice Bellard
                break;
179
            p++;
180
        }
181
    }
182
    return 0;
183
}
184
185 2323ac01 Baptiste Coudurier
static int match_format(const char *name, const char *names)
186
{
187
    const char *p;
188
    int len, namelen;
189
190
    if (!name || !names)
191
        return 0;
192
193
    namelen = strlen(name);
194
    while ((p = strchr(names, ','))) {
195
        len = FFMAX(p - names, namelen);
196
        if (!strncasecmp(name, names, len))
197
            return 1;
198
        names = p+1;
199
    }
200
    return !strcasecmp(name, names);
201
}
202
203 a1f547b9 Stefano Sabatini
AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
204
                                const char *mime_type)
205
{
206 27323146 Anton Khirnov
    AVOutputFormat *fmt = NULL, *fmt_found;
207 de6d9b64 Fabrice Bellard
    int score_max, score;
208
209 87a0a681 Fabrice Bellard
    /* specific test for image sequences */
210 b250f9c6 Aurelien Jacobs
#if CONFIG_IMAGE2_MUXER
211 115329f1 Diego Biurrun
    if (!short_name && filename &&
212 5c07cf53 Michel Bardiaux
        av_filename_number_test(filename) &&
213 a9bf9d8e Anton Khirnov
        ff_guess_image2_codec(filename) != CODEC_ID_NONE) {
214 0f52ef1a Stefano Sabatini
        return av_guess_format("image2", NULL, NULL);
215 5b6d5596 Michael Niedermayer
    }
216 ff70e601 Måns Rullgård
#endif
217 a85736f2 Diego Biurrun
    /* Find the proper file type. */
218 de6d9b64 Fabrice Bellard
    fmt_found = NULL;
219
    score_max = 0;
220 27323146 Anton Khirnov
    while ((fmt = av_oformat_next(fmt))) {
221 de6d9b64 Fabrice Bellard
        score = 0;
222
        if (fmt->name && short_name && !strcmp(fmt->name, short_name))
223
            score += 100;
224
        if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
225
            score += 10;
226 115329f1 Diego Biurrun
        if (filename && fmt->extensions &&
227 aa13b573 Stefano Sabatini
            av_match_ext(filename, fmt->extensions)) {
228 de6d9b64 Fabrice Bellard
            score += 5;
229
        }
230
        if (score > score_max) {
231
            score_max = score;
232
            fmt_found = fmt;
233
        }
234
    }
235
    return fmt_found;
236 115329f1 Diego Biurrun
}
237 de6d9b64 Fabrice Bellard
238 115329f1 Diego Biurrun
enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
239 72415b2a Stefano Sabatini
                            const char *filename, const char *mime_type, enum AVMediaType type){
240
    if(type == AVMEDIA_TYPE_VIDEO){
241 5b6d5596 Michael Niedermayer
        enum CodecID codec_id= CODEC_ID_NONE;
242
243 b250f9c6 Aurelien Jacobs
#if CONFIG_IMAGE2_MUXER
244 ae214ac3 Michael Niedermayer
        if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
245 a9bf9d8e Anton Khirnov
            codec_id= ff_guess_image2_codec(filename);
246 5b6d5596 Michael Niedermayer
        }
247 ff70e601 Måns Rullgård
#endif
248 5b6d5596 Michael Niedermayer
        if(codec_id == CODEC_ID_NONE)
249
            codec_id= fmt->video_codec;
250
        return codec_id;
251 72415b2a Stefano Sabatini
    }else if(type == AVMEDIA_TYPE_AUDIO)
252 5b6d5596 Michael Niedermayer
        return fmt->audio_codec;
253 118ccae0 Aurelien Jacobs
    else if (type == AVMEDIA_TYPE_SUBTITLE)
254
        return fmt->subtitle_codec;
255 5b6d5596 Michael Niedermayer
    else
256
        return CODEC_ID_NONE;
257
}
258
259 b9a281db Fabrice Bellard
AVInputFormat *av_find_input_format(const char *short_name)
260
{
261 27323146 Anton Khirnov
    AVInputFormat *fmt = NULL;
262
    while ((fmt = av_iformat_next(fmt))) {
263 2323ac01 Baptiste Coudurier
        if (match_format(short_name, fmt->name))
264 b9a281db Fabrice Bellard
            return fmt;
265
    }
266
    return NULL;
267
}
268
269 13728334 Aurelien Jacobs
#if FF_API_SYMVER && CONFIG_SHARED && HAVE_SYMVER
270 b462d132 Måns Rullgård
FF_SYMVER(void, av_destruct_packet_nofree, (AVPacket *pkt), "LIBAVFORMAT_52")
271
{
272
    av_destruct_packet_nofree(pkt);
273
}
274
275
FF_SYMVER(void, av_destruct_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
276
{
277
    av_destruct_packet(pkt);
278
}
279 de6d9b64 Fabrice Bellard
280 b462d132 Måns Rullgård
FF_SYMVER(int, av_new_packet, (AVPacket *pkt, int size), "LIBAVFORMAT_52")
281
{
282
    return av_new_packet(pkt, size);
283
}
284
285
FF_SYMVER(int, av_dup_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
286
{
287
    return av_dup_packet(pkt);
288
}
289
290
FF_SYMVER(void, av_free_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
291
{
292
    av_free_packet(pkt);
293
}
294
295
FF_SYMVER(void, av_init_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
296
{
297
    av_log(NULL, AV_LOG_WARNING, "Diverting av_*_packet function calls to libavcodec. Recompile to improve performance\n");
298
    av_init_packet(pkt);
299
}
300
#endif
301 de6d9b64 Fabrice Bellard
302 ae628ec1 Anton Khirnov
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
303 2692067a Michael Niedermayer
{
304
    int ret= av_new_packet(pkt, size);
305
306
    if(ret<0)
307
        return ret;
308
309 a2704c97 Anton Khirnov
    pkt->pos= avio_tell(s);
310 2692067a Michael Niedermayer
311 b7effd4e Anton Khirnov
    ret= avio_read(s, pkt->data, size);
312 2692067a Michael Niedermayer
    if(ret<=0)
313
        av_free_packet(pkt);
314
    else
315 feb993e5 Reimar Döffinger
        av_shrink_packet(pkt, ret);
316 2692067a Michael Niedermayer
317
    return ret;
318
}
319
320 ae628ec1 Anton Khirnov
int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
321 6bfc2683 Reimar Döffinger
{
322
    int ret;
323
    int old_size;
324
    if (!pkt->size)
325
        return av_get_packet(s, pkt, size);
326
    old_size = pkt->size;
327
    ret = av_grow_packet(pkt, size);
328
    if (ret < 0)
329
        return ret;
330 b7effd4e Anton Khirnov
    ret = avio_read(s, pkt->data + old_size, size);
331 6bfc2683 Reimar Döffinger
    av_shrink_packet(pkt, old_size + FFMAX(ret, 0));
332
    return ret;
333
}
334
335 fb2758c8 Fabrice Bellard
336 5c07cf53 Michel Bardiaux
int av_filename_number_test(const char *filename)
337 b9a281db Fabrice Bellard
{
338
    char buf[1024];
339 5c07cf53 Michel Bardiaux
    return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
340 b9a281db Fabrice Bellard
}
341
342 8e2ee182 Reimar Döffinger
AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
343 b9a281db Fabrice Bellard
{
344 6612d8cf Reimar Döffinger
    AVProbeData lpd = *pd;
345 27323146 Anton Khirnov
    AVInputFormat *fmt1 = NULL, *fmt;
346 56a10009 Anton Khirnov
    int score, id3 = 0;
347 b9a281db Fabrice Bellard
348 6612d8cf Reimar Döffinger
    if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
349
        int id3len = ff_id3v2_tag_len(lpd.buf);
350
        if (lpd.buf_size > id3len + 16) {
351
            lpd.buf += id3len;
352
            lpd.buf_size -= id3len;
353
        }
354 56a10009 Anton Khirnov
        id3 = 1;
355 6612d8cf Reimar Döffinger
    }
356
357 b9a281db Fabrice Bellard
    fmt = NULL;
358 27323146 Anton Khirnov
    while ((fmt1 = av_iformat_next(fmt1))) {
359 b8e705ec Reimar Döffinger
        if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
360 b9a281db Fabrice Bellard
            continue;
361
        score = 0;
362 a8dbe951 Philip Gladstone
        if (fmt1->read_probe) {
363 6612d8cf Reimar Döffinger
            score = fmt1->read_probe(&lpd);
364 a8dbe951 Philip Gladstone
        } else if (fmt1->extensions) {
365 6612d8cf Reimar Döffinger
            if (av_match_ext(lpd.filename, fmt1->extensions)) {
366 b9a281db Fabrice Bellard
                score = 50;
367
            }
368 115329f1 Diego Biurrun
        }
369 79750486 Michael Niedermayer
        if (score > *score_max) {
370
            *score_max = score;
371 b9a281db Fabrice Bellard
            fmt = fmt1;
372 4b3cca36 Michael Niedermayer
        }else if (score == *score_max)
373
            fmt = NULL;
374 b9a281db Fabrice Bellard
    }
375 56a10009 Anton Khirnov
376
    /* a hack for files with huge id3v2 tags -- try to guess by file extension. */
377
    if (!fmt && id3 && *score_max < AVPROBE_SCORE_MAX/4) {
378
        while ((fmt = av_iformat_next(fmt)))
379
            if (fmt->extensions && av_match_ext(lpd.filename, fmt->extensions)) {
380
                *score_max = AVPROBE_SCORE_MAX/4;
381
                break;
382
            }
383
    }
384
385 b9a281db Fabrice Bellard
    return fmt;
386
}
387
388 79750486 Michael Niedermayer
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
389
    int score=0;
390
    return av_probe_input_format2(pd, is_opened, &score);
391
}
392
393 db46c4e1 Baptiste Coudurier
static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
394 64cd3108 Michael Niedermayer
{
395 cf5b33d9 Stefano Sabatini
    static const struct {
396
        const char *name; enum CodecID id; enum AVMediaType type;
397
    } fmt_id_type[] = {
398
        { "aac"      , CODEC_ID_AAC       , AVMEDIA_TYPE_AUDIO },
399
        { "ac3"      , CODEC_ID_AC3       , AVMEDIA_TYPE_AUDIO },
400
        { "dts"      , CODEC_ID_DTS       , AVMEDIA_TYPE_AUDIO },
401
        { "eac3"     , CODEC_ID_EAC3      , AVMEDIA_TYPE_AUDIO },
402
        { "h264"     , CODEC_ID_H264      , AVMEDIA_TYPE_VIDEO },
403
        { "m4v"      , CODEC_ID_MPEG4     , AVMEDIA_TYPE_VIDEO },
404
        { "mp3"      , CODEC_ID_MP3       , AVMEDIA_TYPE_AUDIO },
405
        { "mpegvideo", CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
406
        { 0 }
407
    };
408
    AVInputFormat *fmt = av_probe_input_format2(pd, 1, &score);
409 64cd3108 Michael Niedermayer
410
    if (fmt) {
411 cf5b33d9 Stefano Sabatini
        int i;
412 db46c4e1 Baptiste Coudurier
        av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
413
               pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
414 cf5b33d9 Stefano Sabatini
        for (i = 0; fmt_id_type[i].name; i++) {
415
            if (!strcmp(fmt->name, fmt_id_type[i].name)) {
416
                st->codec->codec_id   = fmt_id_type[i].id;
417
                st->codec->codec_type = fmt_id_type[i].type;
418
                break;
419
            }
420 f1588ed5 Andreas Öman
        }
421 64cd3108 Michael Niedermayer
    }
422
    return !!fmt;
423
}
424
425 b9a281db Fabrice Bellard
/************************************************************/
426
/* input media file */
427 96baaa6a Fabrice Bellard
428 da24c5e3 Fabrice Bellard
/**
429 e36bdf8b Daniel Kristjansson
 * Open a media file from an IO stream. 'fmt' must be specified.
430 da24c5e3 Fabrice Bellard
 */
431 115329f1 Diego Biurrun
int av_open_input_stream(AVFormatContext **ic_ptr,
432 ae628ec1 Anton Khirnov
                         AVIOContext *pb, const char *filename,
433 da24c5e3 Fabrice Bellard
                         AVInputFormat *fmt, AVFormatParameters *ap)
434
{
435
    int err;
436
    AVFormatContext *ic;
437 c04c3282 Michael Niedermayer
    AVFormatParameters default_ap;
438
439
    if(!ap){
440
        ap=&default_ap;
441
        memset(ap, 0, sizeof(default_ap));
442
    }
443 da24c5e3 Fabrice Bellard
444 4eb72c6b Nico Sabbi
    if(!ap->prealloced_context)
445 8e2fd8e1 Stefano Sabatini
        ic = avformat_alloc_context();
446 4eb72c6b Nico Sabbi
    else
447
        ic = *ic_ptr;
448 da24c5e3 Fabrice Bellard
    if (!ic) {
449 769e10f0 Panagiotis Issaris
        err = AVERROR(ENOMEM);
450 da24c5e3 Fabrice Bellard
        goto fail;
451
    }
452
    ic->iformat = fmt;
453 899681cd Björn Axelsson
    ic->pb = pb;
454 da24c5e3 Fabrice Bellard
    ic->duration = AV_NOPTS_VALUE;
455
    ic->start_time = AV_NOPTS_VALUE;
456 75e61b0e Måns Rullgård
    av_strlcpy(ic->filename, filename, sizeof(ic->filename));
457 da24c5e3 Fabrice Bellard
458
    /* allocate private data */
459
    if (fmt->priv_data_size > 0) {
460
        ic->priv_data = av_mallocz(fmt->priv_data_size);
461
        if (!ic->priv_data) {
462 769e10f0 Panagiotis Issaris
            err = AVERROR(ENOMEM);
463 da24c5e3 Fabrice Bellard
            goto fail;
464
        }
465
    } else {
466
        ic->priv_data = NULL;
467
    }
468
469 ae628ec1 Anton Khirnov
    // e.g. AVFMT_NOFILE formats will not have a AVIOContext
470 6612d8cf Reimar Döffinger
    if (ic->pb)
471
        ff_id3v2_read(ic, ID3v2_DEFAULT_MAGIC);
472
473 e145ce20 Ronald S. Bultje
    if (ic->iformat->read_header) {
474 1e2802c5 Ronald S. Bultje
        err = ic->iformat->read_header(ic, ap);
475
        if (err < 0)
476
            goto fail;
477 e145ce20 Ronald S. Bultje
    }
478 fb2758c8 Fabrice Bellard
479 faf7cbf1 Michael Niedermayer
    if (pb && !ic->data_offset)
480 a2704c97 Anton Khirnov
        ic->data_offset = avio_tell(ic->pb);
481 fb2758c8 Fabrice Bellard
482 af122d6a Baptiste Coudurier
    ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
483
484 da24c5e3 Fabrice Bellard
    *ic_ptr = ic;
485
    return 0;
486
 fail:
487
    if (ic) {
488 ccafd472 Baptiste Coudurier
        int i;
489 da24c5e3 Fabrice Bellard
        av_freep(&ic->priv_data);
490 ccafd472 Baptiste Coudurier
        for(i=0;i<ic->nb_streams;i++) {
491
            AVStream *st = ic->streams[i];
492
            if (st) {
493
                av_free(st->priv_data);
494
                av_free(st->codec->extradata);
495 ec973f45 Przemysław Sobala
                av_free(st->codec);
496 fd0368e7 Aurelien Jacobs
                av_free(st->info);
497 ccafd472 Baptiste Coudurier
            }
498
            av_free(st);
499
        }
500 da24c5e3 Fabrice Bellard
    }
501
    av_free(ic);
502
    *ic_ptr = NULL;
503
    return err;
504
}
505
506 a85736f2 Diego Biurrun
/** size of probe buffer, for guessing file type from file contents */
507 a877eedc Michael Niedermayer
#define PROBE_BUF_MIN 2048
508 329b1e75 Michael Niedermayer
#define PROBE_BUF_MAX (1<<20)
509 b9a281db Fabrice Bellard
510 ae628ec1 Anton Khirnov
int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
511 eadd495d Micah F. Galizia
                          const char *filename, void *logctx,
512
                          unsigned int offset, unsigned int max_probe_size)
513
{
514
    AVProbeData pd = { filename ? filename : "", NULL, -offset };
515
    unsigned char *buf = NULL;
516
    int ret = 0, probe_size;
517
518
    if (!max_probe_size) {
519
        max_probe_size = PROBE_BUF_MAX;
520
    } else if (max_probe_size > PROBE_BUF_MAX) {
521
        max_probe_size = PROBE_BUF_MAX;
522
    } else if (max_probe_size < PROBE_BUF_MIN) {
523
        return AVERROR(EINVAL);
524
    }
525
526
    if (offset >= max_probe_size) {
527
        return AVERROR(EINVAL);
528
    }
529
530 532aa889 Micah F. Galizia
    for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt && ret >= 0;
531
        probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
532 eadd495d Micah F. Galizia
        int ret, score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
533
        int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;
534
535
        if (probe_size < offset) {
536
            continue;
537
        }
538
539
        /* read probe data */
540
        buf = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
541 b7effd4e Anton Khirnov
        if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
542 eadd495d Micah F. Galizia
            /* fail if error was not end of file, otherwise, lower score */
543
            if (ret != AVERROR_EOF) {
544
                av_free(buf);
545
                return ret;
546
            }
547
            score = 0;
548 c7f625ee Måns Rullgård
            ret = 0;            /* error was end of file, nothing read */
549 eadd495d Micah F. Galizia
        }
550
        pd.buf_size += ret;
551
        pd.buf = &buf[offset];
552
553
        memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
554
555
        /* guess file format */
556
        *fmt = av_probe_input_format2(&pd, 1, &score);
557
        if(*fmt){
558
            if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
559
                av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);
560
            }else
561
                av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);
562
        }
563
    }
564
565 532aa889 Micah F. Galizia
    if (!*fmt) {
566 01d91b9b Tomas Härdin
        av_free(buf);
567 532aa889 Micah F. Galizia
        return AVERROR_INVALIDDATA;
568
    }
569
570 01d91b9b Tomas Härdin
    /* rewind. reuse probe buffer to avoid seeking */
571 f1ef2cd9 Anton Khirnov
    if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
572 01d91b9b Tomas Härdin
        av_free(buf);
573 eadd495d Micah F. Galizia
574 01d91b9b Tomas Härdin
    return ret;
575 eadd495d Micah F. Galizia
}
576
577 115329f1 Diego Biurrun
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
578 b9a281db Fabrice Bellard
                       AVInputFormat *fmt,
579
                       int buf_size,
580
                       AVFormatParameters *ap)
581 de6d9b64 Fabrice Bellard
{
582 eadd495d Micah F. Galizia
    int err;
583 b9a281db Fabrice Bellard
    AVProbeData probe_data, *pd = &probe_data;
584 ae628ec1 Anton Khirnov
    AVIOContext *pb = NULL;
585 e9b06816 Michael Niedermayer
    void *logctx= ap && ap->prealloced_context ? *ic_ptr : NULL;
586 115329f1 Diego Biurrun
587 da24c5e3 Fabrice Bellard
    pd->filename = "";
588
    if (filename)
589
        pd->filename = filename;
590 a877eedc Michael Niedermayer
    pd->buf = NULL;
591 b9a281db Fabrice Bellard
    pd->buf_size = 0;
592
593
    if (!fmt) {
594 a85736f2 Diego Biurrun
        /* guess format if no file can be opened */
595 a25e098d Fabrice Bellard
        fmt = av_probe_input_format(pd, 0);
596 de6d9b64 Fabrice Bellard
    }
597
598 a85736f2 Diego Biurrun
    /* Do not open file if the format does not need it. XXX: specific
599 b6892136 Fabrice Bellard
       hack needed to handle RTSP/TCP */
600 17acc63a Reimar Döffinger
    if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
601 87a0a681 Fabrice Bellard
        /* if no file needed do not try to open one */
602 f87b1b37 Anton Khirnov
        if ((err=avio_open(&pb, filename, AVIO_RDONLY)) < 0) {
603 96baaa6a Fabrice Bellard
            goto fail;
604 b9a281db Fabrice Bellard
        }
605 96baaa6a Fabrice Bellard
        if (buf_size > 0) {
606 59f65d95 Anton Khirnov
            ffio_set_buf_size(pb, buf_size);
607 96baaa6a Fabrice Bellard
        }
608 3940caad Anssi Hannula
        if (!fmt && (err = av_probe_input_buffer(pb, &fmt, filename, logctx, 0, logctx ? (*ic_ptr)->probesize : 0)) < 0) {
609 eadd495d Micah F. Galizia
            goto fail;
610 5b25dfa7 Fabrice Bellard
        }
611 b9a281db Fabrice Bellard
    }
612
613
    /* if still no format found, error */
614
    if (!fmt) {
615 2928b83c Stefano Sabatini
        err = AVERROR_INVALIDDATA;
616 da24c5e3 Fabrice Bellard
        goto fail;
617 de6d9b64 Fabrice Bellard
    }
618 115329f1 Diego Biurrun
619 a85736f2 Diego Biurrun
    /* check filename in case an image number is expected */
620 da24c5e3 Fabrice Bellard
    if (fmt->flags & AVFMT_NEEDNUMBER) {
621 5c07cf53 Michel Bardiaux
        if (!av_filename_number_test(filename)) {
622 87a0a681 Fabrice Bellard
            err = AVERROR_NUMEXPECTED;
623 da24c5e3 Fabrice Bellard
            goto fail;
624 87a0a681 Fabrice Bellard
        }
625
    }
626 da24c5e3 Fabrice Bellard
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
627
    if (err)
628
        goto fail;
629 b9a281db Fabrice Bellard
    return 0;
630 de6d9b64 Fabrice Bellard
 fail:
631 a877eedc Michael Niedermayer
    av_freep(&pd->buf);
632 17acc63a Reimar Döffinger
    if (pb)
633 22a3212e Anton Khirnov
        avio_close(pb);
634 ebb82604 Art Clarke
    if (ap && ap->prealloced_context)
635
        av_free(*ic_ptr);
636
    *ic_ptr = NULL;
637 b9a281db Fabrice Bellard
    return err;
638 115329f1 Diego Biurrun
639 de6d9b64 Fabrice Bellard
}
640
641 da24c5e3 Fabrice Bellard
/*******************************************************/
642
643 5c5b1731 Måns Rullgård
static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
644
                               AVPacketList **plast_pktl){
645
    AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
646 9d3b9f2c Michael Niedermayer
    if (!pktl)
647
        return NULL;
648
649 5c5b1731 Måns Rullgård
    if (*packet_buffer)
650
        (*plast_pktl)->next = pktl;
651
    else
652
        *packet_buffer = pktl;
653
654 9d3b9f2c Michael Niedermayer
    /* add the packet in the buffered packet list */
655
    *plast_pktl = pktl;
656
    pktl->pkt= *pkt;
657
    return &pktl->pkt;
658
}
659
660 de6d9b64 Fabrice Bellard
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
661
{
662 86cb7e33 Baptiste Coudurier
    int ret, i;
663 62600469 Michael Niedermayer
    AVStream *st;
664 0bef08e5 Michael Niedermayer
665
    for(;;){
666
        AVPacketList *pktl = s->raw_packet_buffer;
667
668
        if (pktl) {
669
            *pkt = pktl->pkt;
670 86cb7e33 Baptiste Coudurier
            if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||
671 af122d6a Baptiste Coudurier
               !s->streams[pkt->stream_index]->probe_packets ||
672
               s->raw_packet_buffer_remaining_size < pkt->size){
673
                AVProbeData *pd = &s->streams[pkt->stream_index]->probe_data;
674
                av_freep(&pd->buf);
675
                pd->buf_size = 0;
676 0bef08e5 Michael Niedermayer
                s->raw_packet_buffer = pktl->next;
677 af122d6a Baptiste Coudurier
                s->raw_packet_buffer_remaining_size += pkt->size;
678 0bef08e5 Michael Niedermayer
                av_free(pktl);
679
                return 0;
680
            }
681
        }
682
683 55823964 Michael Niedermayer
        av_init_packet(pkt);
684
        ret= s->iformat->read_packet(s, pkt);
685 86cb7e33 Baptiste Coudurier
        if (ret < 0) {
686
            if (!pktl || ret == AVERROR(EAGAIN))
687
                return ret;
688
            for (i = 0; i < s->nb_streams; i++)
689
                s->streams[i]->probe_packets = 0;
690
            continue;
691
        }
692 55823964 Michael Niedermayer
        st= s->streams[pkt->stream_index];
693 62600469 Michael Niedermayer
694 55823964 Michael Niedermayer
        switch(st->codec->codec_type){
695 72415b2a Stefano Sabatini
        case AVMEDIA_TYPE_VIDEO:
696 55823964 Michael Niedermayer
            if(s->video_codec_id)   st->codec->codec_id= s->video_codec_id;
697
            break;
698 72415b2a Stefano Sabatini
        case AVMEDIA_TYPE_AUDIO:
699 55823964 Michael Niedermayer
            if(s->audio_codec_id)   st->codec->codec_id= s->audio_codec_id;
700
            break;
701 72415b2a Stefano Sabatini
        case AVMEDIA_TYPE_SUBTITLE:
702 55823964 Michael Niedermayer
            if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
703
            break;
704
        }
705 62600469 Michael Niedermayer
706 86cb7e33 Baptiste Coudurier
        if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||
707
                     !st->probe_packets))
708 744b4c02 Michael Niedermayer
            return ret;
709
710 5c5b1731 Måns Rullgård
        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
711 af122d6a Baptiste Coudurier
        s->raw_packet_buffer_remaining_size -= pkt->size;
712 744b4c02 Michael Niedermayer
713 0bef08e5 Michael Niedermayer
        if(st->codec->codec_id == CODEC_ID_PROBE){
714
            AVProbeData *pd = &st->probe_data;
715 0e500e0d Michael Niedermayer
            av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
716 86cb7e33 Baptiste Coudurier
            --st->probe_packets;
717
718 0bef08e5 Michael Niedermayer
            pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
719
            memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
720
            pd->buf_size += pkt->size;
721
            memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
722
723 942de2f4 Michael Niedermayer
            if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
724 0f1f4816 Michael Niedermayer
                //FIXME we dont reduce score to 0 for the case of running out of buffer space in bytes
725
                set_codec_from_probe_data(s, st, pd, st->probe_packets > 0 ? AVPROBE_SCORE_MAX/4 : 0);
726 25d3fb73 Michael Niedermayer
                if(st->codec->codec_id != CODEC_ID_PROBE){
727
                    pd->buf_size=0;
728
                    av_freep(&pd->buf);
729 0e500e0d Michael Niedermayer
                    av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
730 25d3fb73 Michael Niedermayer
                }
731 942de2f4 Michael Niedermayer
            }
732 0bef08e5 Michael Niedermayer
        }
733
    }
734 fb2758c8 Fabrice Bellard
}
735
736
/**********************************************************/
737
738 e36bdf8b Daniel Kristjansson
/**
739 a85736f2 Diego Biurrun
 * Get the number of samples of an audio frame. Return -1 on error.
740 e36bdf8b Daniel Kristjansson
 */
741 fb2758c8 Fabrice Bellard
static int get_audio_frame_size(AVCodecContext *enc, int size)
742
{
743
    int frame_size;
744
745 c924ca78 Michael Niedermayer
    if(enc->codec_id == CODEC_ID_VORBIS)
746
        return -1;
747
748 fb2758c8 Fabrice Bellard
    if (enc->frame_size <= 1) {
749 ac3e1834 Baptiste Coudurier
        int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
750
751
        if (bits_per_sample) {
752 fb2758c8 Fabrice Bellard
            if (enc->channels == 0)
753
                return -1;
754 f1b163e0 Aurelien Jacobs
            frame_size = (size << 3) / (bits_per_sample * enc->channels);
755 ac3e1834 Baptiste Coudurier
        } else {
756 fb2758c8 Fabrice Bellard
            /* used for example by ADPCM codecs */
757
            if (enc->bit_rate == 0)
758
                return -1;
759 db5dc02b Baptiste Coudurier
            frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
760 fb2758c8 Fabrice Bellard
        }
761
    } else {
762
        frame_size = enc->frame_size;
763
    }
764
    return frame_size;
765
}
766
767
768 e36bdf8b Daniel Kristjansson
/**
769 a85736f2 Diego Biurrun
 * Return the frame duration in seconds. Return 0 if not available.
770 e36bdf8b Daniel Kristjansson
 */
771 115329f1 Diego Biurrun
static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
772 fb2758c8 Fabrice Bellard
                                   AVCodecParserContext *pc, AVPacket *pkt)
773
{
774
    int frame_size;
775
776
    *pnum = 0;
777
    *pden = 0;
778 01f4895c Michael Niedermayer
    switch(st->codec->codec_type) {
779 72415b2a Stefano Sabatini
    case AVMEDIA_TYPE_VIDEO:
780 1677155d Michael Niedermayer
        if(st->time_base.num*1000LL > st->time_base.den){
781 c0df9d75 Michael Niedermayer
            *pnum = st->time_base.num;
782
            *pden = st->time_base.den;
783 01f4895c Michael Niedermayer
        }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
784
            *pnum = st->codec->time_base.num;
785
            *pden = st->codec->time_base.den;
786 327c4076 Michael Niedermayer
            if (pc && pc->repeat_pict) {
787 810c451b Ivan Schreter
                *pnum = (*pnum) * (1 + pc->repeat_pict);
788 327c4076 Michael Niedermayer
            }
789 497431a5 Michael Niedermayer
            //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
790
            //Thus if we have no parser in such case leave duration undefined.
791
            if(st->codec->ticks_per_frame>1 && !pc){
792
                *pnum = *pden = 0;
793
            }
794 fb2758c8 Fabrice Bellard
        }
795
        break;
796 72415b2a Stefano Sabatini
    case AVMEDIA_TYPE_AUDIO:
797 01f4895c Michael Niedermayer
        frame_size = get_audio_frame_size(st->codec, pkt->size);
798 6cbce636 Daniel Kang
        if (frame_size <= 0 || st->codec->sample_rate <= 0)
799 fb2758c8 Fabrice Bellard
            break;
800
        *pnum = frame_size;
801 01f4895c Michael Niedermayer
        *pden = st->codec->sample_rate;
802 fb2758c8 Fabrice Bellard
        break;
803
    default:
804
        break;
805
    }
806
}
807
808 5ba7c3d7 Michael Niedermayer
static int is_intra_only(AVCodecContext *enc){
809 72415b2a Stefano Sabatini
    if(enc->codec_type == AVMEDIA_TYPE_AUDIO){
810 5ba7c3d7 Michael Niedermayer
        return 1;
811 72415b2a Stefano Sabatini
    }else if(enc->codec_type == AVMEDIA_TYPE_VIDEO){
812 5ba7c3d7 Michael Niedermayer
        switch(enc->codec_id){
813
        case CODEC_ID_MJPEG:
814
        case CODEC_ID_MJPEGB:
815
        case CODEC_ID_LJPEG:
816
        case CODEC_ID_RAWVIDEO:
817
        case CODEC_ID_DVVIDEO:
818
        case CODEC_ID_HUFFYUV:
819 f37b9768 Loren Merritt
        case CODEC_ID_FFVHUFF:
820 5ba7c3d7 Michael Niedermayer
        case CODEC_ID_ASV1:
821
        case CODEC_ID_ASV2:
822
        case CODEC_ID_VCR1:
823 b774fdd7 Baptiste Coudurier
        case CODEC_ID_DNXHD:
824 aa915625 Baptiste Coudurier
        case CODEC_ID_JPEG2000:
825 5ba7c3d7 Michael Niedermayer
            return 1;
826
        default: break;
827
        }
828
    }
829
    return 0;
830
}
831
832 9fcbcca6 Neil Brown
static void update_initial_timestamps(AVFormatContext *s, int stream_index,
833
                                      int64_t dts, int64_t pts)
834
{
835 82583548 Michael Niedermayer
    AVStream *st= s->streams[stream_index];
836
    AVPacketList *pktl= s->packet_buffer;
837
838 7efeb73a Michael Niedermayer
    if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
839 82583548 Michael Niedermayer
        return;
840
841
    st->first_dts= dts - st->cur_dts;
842
    st->cur_dts= dts;
843
844
    for(; pktl; pktl= pktl->next){
845
        if(pktl->pkt.stream_index != stream_index)
846
            continue;
847
        //FIXME think more about this check
848
        if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
849
            pktl->pkt.pts += st->first_dts;
850
851
        if(pktl->pkt.dts != AV_NOPTS_VALUE)
852
            pktl->pkt.dts += st->first_dts;
853 48a59dfe Michael Niedermayer
854
        if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
855
            st->start_time= pktl->pkt.pts;
856 82583548 Michael Niedermayer
    }
857 9fcbcca6 Neil Brown
    if (st->start_time == AV_NOPTS_VALUE)
858
        st->start_time = pts;
859 82583548 Michael Niedermayer
}
860
861 83a9db42 Michael Niedermayer
static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
862
{
863
    AVPacketList *pktl= s->packet_buffer;
864 820ad60c Michael Niedermayer
    int64_t cur_dts= 0;
865
866
    if(st->first_dts != AV_NOPTS_VALUE){
867
        cur_dts= st->first_dts;
868
        for(; pktl; pktl= pktl->next){
869
            if(pktl->pkt.stream_index == pkt->stream_index){
870
                if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
871
                    break;
872
                cur_dts -= pkt->duration;
873
            }
874
        }
875
        pktl= s->packet_buffer;
876
        st->first_dts = cur_dts;
877
    }else if(st->cur_dts)
878
        return;
879 83a9db42 Michael Niedermayer
880
    for(; pktl; pktl= pktl->next){
881
        if(pktl->pkt.stream_index != pkt->stream_index)
882
            continue;
883 91acf9a8 Michael Niedermayer
        if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
884
           && !pktl->pkt.duration){
885 820ad60c Michael Niedermayer
            pktl->pkt.dts= cur_dts;
886 5853423c Michael Niedermayer
            if(!st->codec->has_b_frames)
887 820ad60c Michael Niedermayer
                pktl->pkt.pts= cur_dts;
888
            cur_dts += pkt->duration;
889 83a9db42 Michael Niedermayer
            pktl->pkt.duration= pkt->duration;
890
        }else
891
            break;
892
    }
893 820ad60c Michael Niedermayer
    if(st->first_dts == AV_NOPTS_VALUE)
894
        st->cur_dts= cur_dts;
895 83a9db42 Michael Niedermayer
}
896
897 115329f1 Diego Biurrun
static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
898 fb2758c8 Fabrice Bellard
                               AVCodecParserContext *pc, AVPacket *pkt)
899
{
900 d9e1efb7 Michael Niedermayer
    int num, den, presentation_delayed, delay, i;
901 a74008a4 Joakim Plate
    int64_t offset;
902 115329f1 Diego Biurrun
903 fe8344a2 Michael Niedermayer
    if (s->flags & AVFMT_FLAG_NOFILLIN)
904
        return;
905
906 c55806e3 Michael Niedermayer
    if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
907
        pkt->dts= AV_NOPTS_VALUE;
908
909 f4a4be3f Wallak
    if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == FF_B_TYPE)
910 e18027ac Carl Eugen Hoyos
        //FIXME Set low_delay = 0 when has_b_frames = 1
911 818062f2 Baptiste Coudurier
        st->codec->has_b_frames = 1;
912
913 f781f748 Michael Niedermayer
    /* do we have a video B-frame ? */
914
    delay= st->codec->has_b_frames;
915
    presentation_delayed = 0;
916 37b00b47 Alexander Strange
917
    // ignore delay caused by frame threading so that the mpeg2-without-dts
918
    // warning will not trigger
919
    if (delay && st->codec->active_thread_type&FF_THREAD_FRAME)
920
        delay -= st->codec->thread_count-1;
921
922 f781f748 Michael Niedermayer
    /* XXX: need has_b_frame, but cannot get it if the codec is
923
        not initialized */
924
    if (delay &&
925
        pc && pc->pict_type != FF_B_TYPE)
926
        presentation_delayed = 1;
927
928 10a7571b Michael Niedermayer
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
929
       /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
930
        pkt->dts -= 1LL<<st->pts_wrap_bits;
931
    }
932
933 9806f846 Michael Niedermayer
    // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
934
    // we take the conservative approach and discard both
935
    // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
936
    if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
937 b0a18c2f XBMC
        av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
938 9806f846 Michael Niedermayer
        pkt->dts= pkt->pts= AV_NOPTS_VALUE;
939
    }
940
941 fb2758c8 Fabrice Bellard
    if (pkt->duration == 0) {
942 3c895fc0 Michael Niedermayer
        compute_frame_duration(&num, &den, st, pc, pkt);
943 fb2758c8 Fabrice Bellard
        if (den && num) {
944 0e1f78f9 Michael Niedermayer
            pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
945 83a9db42 Michael Niedermayer
946 820ad60c Michael Niedermayer
            if(pkt->duration != 0 && s->packet_buffer)
947 83a9db42 Michael Niedermayer
                update_initial_durations(s, st, pkt);
948 fb2758c8 Fabrice Bellard
        }
949
    }
950
951 a85736f2 Diego Biurrun
    /* correct timestamps with byte offset if demuxers only have timestamps
952
       on packet boundaries */
953 a74008a4 Joakim Plate
    if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
954
        /* this will estimate bitrate based on this frame's duration and size */
955
        offset = av_rescale(pc->offset, pkt->duration, pkt->size);
956
        if(pkt->pts != AV_NOPTS_VALUE)
957
            pkt->pts += offset;
958
        if(pkt->dts != AV_NOPTS_VALUE)
959
            pkt->dts += offset;
960
    }
961
962 27ca0a79 Ivan Schreter
    if (pc && pc->dts_sync_point >= 0) {
963
        // we have synchronization info from the parser
964
        int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
965
        if (den > 0) {
966
            int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
967
            if (pkt->dts != AV_NOPTS_VALUE) {
968
                // got DTS from the stream, update reference timestamp
969
                st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
970
                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
971
            } else if (st->reference_dts != AV_NOPTS_VALUE) {
972
                // compute DTS based on reference timestamp
973
                pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
974
                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
975
            }
976
            if (pc->dts_sync_point > 0)
977
                st->reference_dts = pkt->dts; // new reference
978
        }
979
    }
980
981 755bfeab Diego Biurrun
    /* This may be redundant, but it should not hurt. */
982 7e4baa66 Michael Niedermayer
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
983
        presentation_delayed = 1;
984 115329f1 Diego Biurrun
985 949b1a13 Steve L'Homme
//    av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
986 fb2758c8 Fabrice Bellard
    /* interpolate PTS and DTS if they are not present */
987 9e6c124a Michael Niedermayer
    //We skip H264 currently because delay and has_b_frames are not reliably set
988
    if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){
989 7e4baa66 Michael Niedermayer
        if (presentation_delayed) {
990 a85736f2 Diego Biurrun
            /* DTS = decompression timestamp */
991
            /* PTS = presentation timestamp */
992 7e4baa66 Michael Niedermayer
            if (pkt->dts == AV_NOPTS_VALUE)
993 635fbcb1 Michael Niedermayer
                pkt->dts = st->last_IP_pts;
994 9fcbcca6 Neil Brown
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
995 7e4baa66 Michael Niedermayer
            if (pkt->dts == AV_NOPTS_VALUE)
996
                pkt->dts = st->cur_dts;
997
998
            /* this is tricky: the dts must be incremented by the duration
999 a85736f2 Diego Biurrun
            of the frame we are displaying, i.e. the last I- or P-frame */
1000 635fbcb1 Michael Niedermayer
            if (st->last_IP_duration == 0)
1001
                st->last_IP_duration = pkt->duration;
1002 7efeb73a Michael Niedermayer
            if(pkt->dts != AV_NOPTS_VALUE)
1003 cdb5af79 Michael Niedermayer
                st->cur_dts = pkt->dts + st->last_IP_duration;
1004 635fbcb1 Michael Niedermayer
            st->last_IP_duration  = pkt->duration;
1005
            st->last_IP_pts= pkt->pts;
1006 7e4baa66 Michael Niedermayer
            /* cannot compute PTS if not present (we can compute it only
1007 a85736f2 Diego Biurrun
            by knowing the future */
1008 028d6f3e Michael Niedermayer
        } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
1009 7e4baa66 Michael Niedermayer
            if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
1010
                int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
1011
                int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
1012
                if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
1013
                    pkt->pts += pkt->duration;
1014
    //                av_log(NULL, AV_LOG_DEBUG, "id:%d old:%"PRId64" new:%"PRId64" dur:%d cur:%"PRId64" size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
1015
                }
1016 90bb394d Michael Niedermayer
            }
1017 115329f1 Diego Biurrun
1018 7e4baa66 Michael Niedermayer
            /* presentation is not delayed : PTS and DTS are the same */
1019
            if(pkt->pts == AV_NOPTS_VALUE)
1020
                pkt->pts = pkt->dts;
1021 9fcbcca6 Neil Brown
            update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
1022 7e4baa66 Michael Niedermayer
            if(pkt->pts == AV_NOPTS_VALUE)
1023
                pkt->pts = st->cur_dts;
1024
            pkt->dts = pkt->pts;
1025 7efeb73a Michael Niedermayer
            if(pkt->pts != AV_NOPTS_VALUE)
1026 cdb5af79 Michael Niedermayer
                st->cur_dts = pkt->pts + pkt->duration;
1027 7e4baa66 Michael Niedermayer
        }
1028 fb2758c8 Fabrice Bellard
    }
1029 d9e1efb7 Michael Niedermayer
1030 cb5b96cd Baptiste Coudurier
    if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
1031 d9e1efb7 Michael Niedermayer
        st->pts_buffer[0]= pkt->pts;
1032
        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
1033
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
1034
        if(pkt->dts == AV_NOPTS_VALUE)
1035
            pkt->dts= st->pts_buffer[0];
1036 9e6c124a Michael Niedermayer
        if(st->codec->codec_id == CODEC_ID_H264){ //we skiped it above so we try here
1037 9fcbcca6 Neil Brown
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
1038 82583548 Michael Niedermayer
        }
1039 d9e1efb7 Michael Niedermayer
        if(pkt->dts > st->cur_dts)
1040
            st->cur_dts = pkt->dts;
1041
    }
1042
1043
//    av_log(NULL, AV_LOG_ERROR, "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n", presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
1044 115329f1 Diego Biurrun
1045 fb2758c8 Fabrice Bellard
    /* update flags */
1046 3a1d3588 Jeff Downs
    if(is_intra_only(st->codec))
1047 cc947f04 Jean-Daniel Dupas
        pkt->flags |= AV_PKT_FLAG_KEY;
1048 3a1d3588 Jeff Downs
    else if (pc) {
1049 fb2758c8 Fabrice Bellard
        pkt->flags = 0;
1050 a85736f2 Diego Biurrun
        /* keyframe computation */
1051 6363af44 Ivan Schreter
        if (pc->key_frame == 1)
1052 cc947f04 Jean-Daniel Dupas
            pkt->flags |= AV_PKT_FLAG_KEY;
1053 6363af44 Ivan Schreter
        else if (pc->key_frame == -1 && pc->pict_type == FF_I_TYPE)
1054 cc947f04 Jean-Daniel Dupas
            pkt->flags |= AV_PKT_FLAG_KEY;
1055 fb2758c8 Fabrice Bellard
    }
1056 b1fa4942 Ivan Schreter
    if (pc)
1057
        pkt->convergence_duration = pc->convergence_duration;
1058 fb2758c8 Fabrice Bellard
}
1059
1060
1061
static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1062
{
1063
    AVStream *st;
1064 37353960 Fabrice Bellard
    int len, ret, i;
1065 fb2758c8 Fabrice Bellard
1066 b237eb80 Michael Niedermayer
    av_init_packet(pkt);
1067
1068 fb2758c8 Fabrice Bellard
    for(;;) {
1069
        /* select current input stream component */
1070
        st = s->cur_st;
1071
        if (st) {
1072 90ad92b3 Michael Niedermayer
            if (!st->need_parsing || !st->parser) {
1073 fb2758c8 Fabrice Bellard
                /* no parsing needed: we just output the packet as is */
1074
                /* raw data support */
1075 3a41c2f7 Michael Niedermayer
                *pkt = st->cur_pkt; st->cur_pkt.data= NULL;
1076 fb2758c8 Fabrice Bellard
                compute_pkt_fields(s, st, NULL, pkt);
1077
                s->cur_st = NULL;
1078 74f5ae84 Reimar Döffinger
                if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1079 cc947f04 Jean-Daniel Dupas
                    (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1080 74f5ae84 Reimar Döffinger
                    ff_reduce_index(s, st->index);
1081
                    av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1082
                }
1083 434cab9e Michael Niedermayer
                break;
1084 3a41c2f7 Michael Niedermayer
            } else if (st->cur_len > 0 && st->discard < AVDISCARD_ALL) {
1085 61c23c15 Ivan Schreter
                len = av_parser_parse2(st->parser, st->codec, &pkt->data, &pkt->size,
1086
                                       st->cur_ptr, st->cur_len,
1087
                                       st->cur_pkt.pts, st->cur_pkt.dts,
1088
                                       st->cur_pkt.pos);
1089 3a41c2f7 Michael Niedermayer
                st->cur_pkt.pts = AV_NOPTS_VALUE;
1090
                st->cur_pkt.dts = AV_NOPTS_VALUE;
1091 fb2758c8 Fabrice Bellard
                /* increment read pointer */
1092 3a41c2f7 Michael Niedermayer
                st->cur_ptr += len;
1093
                st->cur_len -= len;
1094 115329f1 Diego Biurrun
1095 fb2758c8 Fabrice Bellard
                /* return packet if any */
1096
                if (pkt->size) {
1097 37353960 Fabrice Bellard
                got_packet:
1098 fb2758c8 Fabrice Bellard
                    pkt->duration = 0;
1099
                    pkt->stream_index = st->index;
1100 6ec87caa Fabrice Bellard
                    pkt->pts = st->parser->pts;
1101
                    pkt->dts = st->parser->dts;
1102 61c23c15 Ivan Schreter
                    pkt->pos = st->parser->pos;
1103 a5266a47 Michael Niedermayer
                    if(pkt->data == st->cur_pkt.data && pkt->size == st->cur_pkt.size){
1104
                        s->cur_st = NULL;
1105
                        pkt->destruct= st->cur_pkt.destruct;
1106 22d78b05 Eli Friedman
                        st->cur_pkt.destruct= NULL;
1107 a5266a47 Michael Niedermayer
                        st->cur_pkt.data    = NULL;
1108
                        assert(st->cur_len == 0);
1109
                    }else{
1110 80d403fc Reimar Döffinger
                    pkt->destruct = NULL;
1111 a5266a47 Michael Niedermayer
                    }
1112 fb2758c8 Fabrice Bellard
                    compute_pkt_fields(s, st, st->parser, pkt);
1113 e9b78eeb Michael Niedermayer
1114 cc947f04 Jean-Daniel Dupas
                    if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY){
1115 3dea63bd Paul Kelly
                        ff_reduce_index(s, st->index);
1116 e9b78eeb Michael Niedermayer
                        av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
1117
                                           0, 0, AVINDEX_KEYFRAME);
1118
                    }
1119
1120 434cab9e Michael Niedermayer
                    break;
1121 fb2758c8 Fabrice Bellard
                }
1122
            } else {
1123 bcbecff1 Fabrice Bellard
                /* free packet */
1124 3a41c2f7 Michael Niedermayer
                av_free_packet(&st->cur_pkt);
1125 fb2758c8 Fabrice Bellard
                s->cur_st = NULL;
1126
            }
1127
        } else {
1128 3a41c2f7 Michael Niedermayer
            AVPacket cur_pkt;
1129 fb2758c8 Fabrice Bellard
            /* read next packet */
1130 3a41c2f7 Michael Niedermayer
            ret = av_read_packet(s, &cur_pkt);
1131 37353960 Fabrice Bellard
            if (ret < 0) {
1132 8fa36ae0 François Revol
                if (ret == AVERROR(EAGAIN))
1133 37353960 Fabrice Bellard
                    return ret;
1134
                /* return the last frames, if any */
1135
                for(i = 0; i < s->nb_streams; i++) {
1136
                    st = s->streams[i];
1137 90ad92b3 Michael Niedermayer
                    if (st->parser && st->need_parsing) {
1138 61c23c15 Ivan Schreter
                        av_parser_parse2(st->parser, st->codec,
1139 115329f1 Diego Biurrun
                                        &pkt->data, &pkt->size,
1140
                                        NULL, 0,
1141 61c23c15 Ivan Schreter
                                        AV_NOPTS_VALUE, AV_NOPTS_VALUE,
1142
                                        AV_NOPTS_VALUE);
1143 37353960 Fabrice Bellard
                        if (pkt->size)
1144
                            goto got_packet;
1145
                    }
1146
                }
1147 a85736f2 Diego Biurrun
                /* no more packets: really terminate parsing */
1148 fb2758c8 Fabrice Bellard
                return ret;
1149 37353960 Fabrice Bellard
            }
1150 3a41c2f7 Michael Niedermayer
            st = s->streams[cur_pkt.stream_index];
1151
            st->cur_pkt= cur_pkt;
1152 115329f1 Diego Biurrun
1153 3a41c2f7 Michael Niedermayer
            if(st->cur_pkt.pts != AV_NOPTS_VALUE &&
1154
               st->cur_pkt.dts != AV_NOPTS_VALUE &&
1155
               st->cur_pkt.pts < st->cur_pkt.dts){
1156 b18a4ab2 Michael Niedermayer
                av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1157 3a41c2f7 Michael Niedermayer
                    st->cur_pkt.stream_index,
1158
                    st->cur_pkt.pts,
1159
                    st->cur_pkt.dts,
1160
                    st->cur_pkt.size);
1161
//                av_free_packet(&st->cur_pkt);
1162 b18a4ab2 Michael Niedermayer
//                return -1;
1163
            }
1164
1165 45b2b05f Michael Niedermayer
            if(s->debug & FF_FDEBUG_TS)
1166 050ba6f4 Baptiste Coudurier
                av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1167 3a41c2f7 Michael Niedermayer
                    st->cur_pkt.stream_index,
1168
                    st->cur_pkt.pts,
1169
                    st->cur_pkt.dts,
1170
                    st->cur_pkt.size,
1171 050ba6f4 Baptiste Coudurier
                    st->cur_pkt.duration,
1172 3a41c2f7 Michael Niedermayer
                    st->cur_pkt.flags);
1173 fb2758c8 Fabrice Bellard
1174
            s->cur_st = st;
1175 3a41c2f7 Michael Niedermayer
            st->cur_ptr = st->cur_pkt.data;
1176
            st->cur_len = st->cur_pkt.size;
1177 fe8344a2 Michael Niedermayer
            if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1178 01f4895c Michael Niedermayer
                st->parser = av_parser_init(st->codec->codec_id);
1179 fb2758c8 Fabrice Bellard
                if (!st->parser) {
1180 a85736f2 Diego Biurrun
                    /* no parser available: just output the raw packets */
1181 57004ff1 Aurelien Jacobs
                    st->need_parsing = AVSTREAM_PARSE_NONE;
1182
                }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
1183 7cbaa7ba Michael Niedermayer
                    st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1184 74a6df59 Alex Converse
                }else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE){
1185
                    st->parser->flags |= PARSER_FLAG_ONCE;
1186 fb2758c8 Fabrice Bellard
                }
1187
            }
1188
        }
1189
    }
1190 45b2b05f Michael Niedermayer
    if(s->debug & FF_FDEBUG_TS)
1191 050ba6f4 Baptiste Coudurier
        av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1192 434cab9e Michael Niedermayer
            pkt->stream_index,
1193
            pkt->pts,
1194
            pkt->dts,
1195 3041a4a1 Michael Niedermayer
            pkt->size,
1196 050ba6f4 Baptiste Coudurier
            pkt->duration,
1197 3041a4a1 Michael Niedermayer
            pkt->flags);
1198 434cab9e Michael Niedermayer
1199
    return 0;
1200 fb2758c8 Fabrice Bellard
}
1201
1202
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1203
{
1204 de6d9b64 Fabrice Bellard
    AVPacketList *pktl;
1205 30bc6613 Michael Niedermayer
    int eof=0;
1206
    const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1207
1208
    for(;;){
1209
        pktl = s->packet_buffer;
1210
        if (pktl) {
1211
            AVPacket *next_pkt= &pktl->pkt;
1212
1213
            if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1214 5be5d28c Stephen Dredge
                int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1215 30bc6613 Michael Niedermayer
                while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1216 115329f1 Diego Biurrun
                    if(   pktl->pkt.stream_index == next_pkt->stream_index
1217 5be5d28c Stephen Dredge
                       && (0 > av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)))
1218
                       && av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
1219 30bc6613 Michael Niedermayer
                        next_pkt->pts= pktl->pkt.dts;
1220
                    }
1221
                    pktl= pktl->next;
1222
                }
1223
                pktl = s->packet_buffer;
1224
            }
1225 115329f1 Diego Biurrun
1226
            if(   next_pkt->pts != AV_NOPTS_VALUE
1227
               || next_pkt->dts == AV_NOPTS_VALUE
1228 30bc6613 Michael Niedermayer
               || !genpts || eof){
1229
                /* read packet from packet buffer, if there is data */
1230
                *pkt = *next_pkt;
1231
                s->packet_buffer = pktl->next;
1232
                av_free(pktl);
1233
                return 0;
1234
            }
1235
        }
1236
        if(genpts){
1237
            int ret= av_read_frame_internal(s, pkt);
1238
            if(ret<0){
1239 8fa36ae0 François Revol
                if(pktl && ret != AVERROR(EAGAIN)){
1240 30bc6613 Michael Niedermayer
                    eof=1;
1241
                    continue;
1242
                }else
1243
                    return ret;
1244
            }
1245 115329f1 Diego Biurrun
1246 5c5b1731 Måns Rullgård
            if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1247
                                           &s->packet_buffer_end)) < 0)
1248 769e10f0 Panagiotis Issaris
                return AVERROR(ENOMEM);
1249 30bc6613 Michael Niedermayer
        }else{
1250
            assert(!s->packet_buffer);
1251
            return av_read_frame_internal(s, pkt);
1252
        }
1253 fb2758c8 Fabrice Bellard
    }
1254
}
1255
1256
/* XXX: suppress the packet queue */
1257
static void flush_packet_queue(AVFormatContext *s)
1258
{
1259
    AVPacketList *pktl;
1260
1261
    for(;;) {
1262
        pktl = s->packet_buffer;
1263 115329f1 Diego Biurrun
        if (!pktl)
1264 fb2758c8 Fabrice Bellard
            break;
1265
        s->packet_buffer = pktl->next;
1266
        av_free_packet(&pktl->pkt);
1267
        av_free(pktl);
1268 b9a281db Fabrice Bellard
    }
1269 86cb7e33 Baptiste Coudurier
    while(s->raw_packet_buffer){
1270
        pktl = s->raw_packet_buffer;
1271
        s->raw_packet_buffer = pktl->next;
1272
        av_free_packet(&pktl->pkt);
1273
        av_free(pktl);
1274
    }
1275 42831b46 Michael Niedermayer
    s->packet_buffer_end=
1276
    s->raw_packet_buffer_end= NULL;
1277 af122d6a Baptiste Coudurier
    s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1278 b9a281db Fabrice Bellard
}
1279
1280 da24c5e3 Fabrice Bellard
/*******************************************************/
1281 fb2758c8 Fabrice Bellard
/* seek support */
1282
1283 b754978a Michael Niedermayer
int av_find_default_stream_index(AVFormatContext *s)
1284
{
1285 ca162a50 Aurelien Jacobs
    int first_audio_index = -1;
1286 b754978a Michael Niedermayer
    int i;
1287
    AVStream *st;
1288
1289
    if (s->nb_streams <= 0)
1290
        return -1;
1291
    for(i = 0; i < s->nb_streams; i++) {
1292
        st = s->streams[i];
1293 72415b2a Stefano Sabatini
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1294 b754978a Michael Niedermayer
            return i;
1295
        }
1296 72415b2a Stefano Sabatini
        if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1297 ca162a50 Aurelien Jacobs
            first_audio_index = i;
1298 b754978a Michael Niedermayer
    }
1299 ca162a50 Aurelien Jacobs
    return first_audio_index >= 0 ? first_audio_index : 0;
1300 b754978a Michael Niedermayer
}
1301
1302 e36bdf8b Daniel Kristjansson
/**
1303
 * Flush the frame reader.
1304
 */
1305 972ffe62 Aurelien Jacobs
void ff_read_frame_flush(AVFormatContext *s)
1306 fb2758c8 Fabrice Bellard
{
1307
    AVStream *st;
1308 106fa129 John Stebbins
    int i, j;
1309 fb2758c8 Fabrice Bellard
1310
    flush_packet_queue(s);
1311
1312 3a41c2f7 Michael Niedermayer
    s->cur_st = NULL;
1313 115329f1 Diego Biurrun
1314 fb2758c8 Fabrice Bellard
    /* for each stream, reset read state */
1315
    for(i = 0; i < s->nb_streams; i++) {
1316
        st = s->streams[i];
1317 115329f1 Diego Biurrun
1318 fb2758c8 Fabrice Bellard
        if (st->parser) {
1319
            av_parser_close(st->parser);
1320
            st->parser = NULL;
1321 3a41c2f7 Michael Niedermayer
            av_free_packet(&st->cur_pkt);
1322 fb2758c8 Fabrice Bellard
        }
1323 635fbcb1 Michael Niedermayer
        st->last_IP_pts = AV_NOPTS_VALUE;
1324 a843d1ff Michael Niedermayer
        st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1325 27ca0a79 Ivan Schreter
        st->reference_dts = AV_NOPTS_VALUE;
1326 3a41c2f7 Michael Niedermayer
        /* fail safe */
1327
        st->cur_ptr = NULL;
1328
        st->cur_len = 0;
1329 86cb7e33 Baptiste Coudurier
1330
        st->probe_packets = MAX_PROBE_PACKETS;
1331 106fa129 John Stebbins
1332
        for(j=0; j<MAX_REORDER_DELAY+1; j++)
1333
            st->pts_buffer[j]= AV_NOPTS_VALUE;
1334 fb2758c8 Fabrice Bellard
    }
1335
}
1336
1337 22ffac70 Reimar Döffinger
void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1338 8bcb147f Michael Niedermayer
    int i;
1339
1340
    for(i = 0; i < s->nb_streams; i++) {
1341 1a1dc611 Nathan Kurz
        AVStream *st = s->streams[i];
1342 8bcb147f Michael Niedermayer
1343 115329f1 Diego Biurrun
        st->cur_dts = av_rescale(timestamp,
1344 1a1dc611 Nathan Kurz
                                 st->time_base.den * (int64_t)ref_st->time_base.num,
1345
                                 st->time_base.num * (int64_t)ref_st->time_base.den);
1346 8bcb147f Michael Niedermayer
    }
1347
}
1348
1349 3dea63bd Paul Kelly
void ff_reduce_index(AVFormatContext *s, int stream_index)
1350
{
1351
    AVStream *st= s->streams[stream_index];
1352
    unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1353
1354
    if((unsigned)st->nb_index_entries >= max_entries){
1355
        int i;
1356
        for(i=0; 2*i<st->nb_index_entries; i++)
1357
            st->index_entries[i]= st->index_entries[2*i];
1358
        st->nb_index_entries= i;
1359
    }
1360
}
1361
1362 e6fb5a4f Peter Ross
int ff_add_index_entry(AVIndexEntry **index_entries,
1363
                       int *nb_index_entries,
1364
                       unsigned int *index_entries_allocated_size,
1365
                       int64_t pos, int64_t timestamp, int size, int distance, int flags)
1366 fb2758c8 Fabrice Bellard
{
1367
    AVIndexEntry *entries, *ie;
1368 b754978a Michael Niedermayer
    int index;
1369 115329f1 Diego Biurrun
1370 e6fb5a4f Peter Ross
    if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1371 568e18b1 Michael Niedermayer
        return -1;
1372 115329f1 Diego Biurrun
1373 e6fb5a4f Peter Ross
    entries = av_fast_realloc(*index_entries,
1374
                              index_entries_allocated_size,
1375
                              (*nb_index_entries + 1) *
1376 fb2758c8 Fabrice Bellard
                              sizeof(AVIndexEntry));
1377 568e18b1 Michael Niedermayer
    if(!entries)
1378
        return -1;
1379
1380 e6fb5a4f Peter Ross
    *index_entries= entries;
1381 b754978a Michael Niedermayer
1382 e6fb5a4f Peter Ross
    index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
1383 b754978a Michael Niedermayer
1384 3ba1438d Michael Niedermayer
    if(index<0){
1385 e6fb5a4f Peter Ross
        index= (*nb_index_entries)++;
1386 3e9245a9 Michael Niedermayer
        ie= &entries[index];
1387 3ba1438d Michael Niedermayer
        assert(index==0 || ie[-1].timestamp < timestamp);
1388
    }else{
1389
        ie= &entries[index];
1390
        if(ie->timestamp != timestamp){
1391 528c2c73 Michael Niedermayer
            if(ie->timestamp <= timestamp)
1392
                return -1;
1393 e6fb5a4f Peter Ross
            memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
1394
            (*nb_index_entries)++;
1395 755bfeab Diego Biurrun
        }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1396 3ba1438d Michael Niedermayer
            distance= ie->min_distance;
1397 3e9245a9 Michael Niedermayer
    }
1398 3ba1438d Michael Niedermayer
1399 b754978a Michael Niedermayer
    ie->pos = pos;
1400
    ie->timestamp = timestamp;
1401 3e9245a9 Michael Niedermayer
    ie->min_distance= distance;
1402 30a43f2d Michael Niedermayer
    ie->size= size;
1403 b754978a Michael Niedermayer
    ie->flags = flags;
1404 115329f1 Diego Biurrun
1405 3e9245a9 Michael Niedermayer
    return index;
1406 fb2758c8 Fabrice Bellard
}
1407
1408 e6fb5a4f Peter Ross
int av_add_index_entry(AVStream *st,
1409
                       int64_t pos, int64_t timestamp, int size, int distance, int flags)
1410
{
1411
    return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1412
                              &st->index_entries_allocated_size, pos,
1413
                              timestamp, size, distance, flags);
1414
}
1415
1416
int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1417
                              int64_t wanted_timestamp, int flags)
1418 fb2758c8 Fabrice Bellard
{
1419
    int a, b, m;
1420
    int64_t timestamp;
1421
1422 3ba1438d Michael Niedermayer
    a = - 1;
1423
    b = nb_entries;
1424 b754978a Michael Niedermayer
1425 67c10de7 Michael Niedermayer
    //optimize appending index entries at the end
1426
    if(b && entries[b-1].timestamp < wanted_timestamp)
1427
        a= b-1;
1428
1429 3ba1438d Michael Niedermayer
    while (b - a > 1) {
1430
        m = (a + b) >> 1;
1431 fb2758c8 Fabrice Bellard
        timestamp = entries[m].timestamp;
1432 3ba1438d Michael Niedermayer
        if(timestamp >= wanted_timestamp)
1433
            b = m;
1434
        if(timestamp <= wanted_timestamp)
1435 b754978a Michael Niedermayer
            a = m;
1436 fb2758c8 Fabrice Bellard
    }
1437 27a5fe5f Michael Niedermayer
    m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1438 115329f1 Diego Biurrun
1439 27a5fe5f Michael Niedermayer
    if(!(flags & AVSEEK_FLAG_ANY)){
1440
        while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1441
            m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1442
        }
1443
    }
1444 3ba1438d Michael Niedermayer
1445 115329f1 Diego Biurrun
    if(m == nb_entries)
1446 3ba1438d Michael Niedermayer
        return -1;
1447
    return  m;
1448 fb2758c8 Fabrice Bellard
}
1449
1450 e6fb5a4f Peter Ross
int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1451
                              int flags)
1452
{
1453
    return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1454
                                     wanted_timestamp, flags);
1455
}
1456
1457 0f652a8e Benoit Fouet
#define DEBUG_SEEK
1458 8d14a25c Michael Niedermayer
1459 3ba1438d Michael Niedermayer
int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1460 8d14a25c Michael Niedermayer
    AVInputFormat *avif= s->iformat;
1461 e6586575 Diego Biurrun
    int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1462 8d14a25c Michael Niedermayer
    int64_t ts_min, ts_max, ts;
1463 89ddd2a9 Michael Niedermayer
    int index;
1464 b593f7fd Sean Soria
    int64_t ret;
1465 8d14a25c Michael Niedermayer
    AVStream *st;
1466
1467 cdd5034f Michael Niedermayer
    if (stream_index < 0)
1468
        return -1;
1469 115329f1 Diego Biurrun
1470 8d14a25c Michael Niedermayer
#ifdef DEBUG_SEEK
1471 4733abcb Måns Rullgård
    av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1472 8d14a25c Michael Niedermayer
#endif
1473
1474
    ts_max=
1475
    ts_min= AV_NOPTS_VALUE;
1476 90b5b51e Diego Biurrun
    pos_limit= -1; //gcc falsely says it may be uninitialized
1477 8d14a25c Michael Niedermayer
1478
    st= s->streams[stream_index];
1479
    if(st->index_entries){
1480
        AVIndexEntry *e;
1481
1482 a85736f2 Diego Biurrun
        index= av_index_search_timestamp(st, target_ts, flags | AVSEEK_FLAG_BACKWARD); //FIXME whole func must be checked for non-keyframe entries in index case, especially read_timestamp()
1483 3ba1438d Michael Niedermayer
        index= FFMAX(index, 0);
1484 8d14a25c Michael Niedermayer
        e= &st->index_entries[index];
1485
1486
        if(e->timestamp <= target_ts || e->pos == e->min_distance){
1487
            pos_min= e->pos;
1488
            ts_min= e->timestamp;
1489
#ifdef DEBUG_SEEK
1490 c0492097 Diego Biurrun
            av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1491
                   pos_min,ts_min);
1492 8d14a25c Michael Niedermayer
#endif
1493
        }else{
1494
            assert(index==0);
1495
        }
1496 115329f1 Diego Biurrun
1497
        index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1498 27a5fe5f Michael Niedermayer
        assert(index < st->nb_index_entries);
1499
        if(index >= 0){
1500 8d14a25c Michael Niedermayer
            e= &st->index_entries[index];
1501
            assert(e->timestamp >= target_ts);
1502
            pos_max= e->pos;
1503
            ts_max= e->timestamp;
1504
            pos_limit= pos_max - e->min_distance;
1505
#ifdef DEBUG_SEEK
1506 c0492097 Diego Biurrun
            av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1507
                   pos_max,pos_limit, ts_max);
1508 8d14a25c Michael Niedermayer
#endif
1509
        }
1510
    }
1511
1512 89ddd2a9 Michael Niedermayer
    pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1513
    if(pos<0)
1514
        return -1;
1515
1516
    /* do the seek */
1517 6b4aa5da Anton Khirnov
    if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1518 b593f7fd Sean Soria
        return ret;
1519 89ddd2a9 Michael Niedermayer
1520
    av_update_cur_dts(s, st, ts);
1521
1522
    return 0;
1523
}
1524
1525
int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, int64_t pos_min, int64_t pos_max, int64_t pos_limit, int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret, int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t )){
1526
    int64_t pos, ts;
1527
    int64_t start_pos, filesize;
1528
    int no_change;
1529
1530
#ifdef DEBUG_SEEK
1531
    av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1532
#endif
1533
1534 8d14a25c Michael Niedermayer
    if(ts_min == AV_NOPTS_VALUE){
1535
        pos_min = s->data_offset;
1536 89ddd2a9 Michael Niedermayer
        ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1537 8d14a25c Michael Niedermayer
        if (ts_min == AV_NOPTS_VALUE)
1538
            return -1;
1539
    }
1540
1541
    if(ts_max == AV_NOPTS_VALUE){
1542
        int step= 1024;
1543 76aa876e Anton Khirnov
        filesize = avio_size(s->pb);
1544 6fd93ce2 Kenneth Aafløy
        pos_max = filesize - 1;
1545 8d14a25c Michael Niedermayer
        do{
1546
            pos_max -= step;
1547 89ddd2a9 Michael Niedermayer
            ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1548 8d14a25c Michael Niedermayer
            step += step;
1549
        }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1550
        if (ts_max == AV_NOPTS_VALUE)
1551
            return -1;
1552 115329f1 Diego Biurrun
1553 8d14a25c Michael Niedermayer
        for(;;){
1554
            int64_t tmp_pos= pos_max + 1;
1555 89ddd2a9 Michael Niedermayer
            int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1556 8d14a25c Michael Niedermayer
            if(tmp_ts == AV_NOPTS_VALUE)
1557
                break;
1558
            ts_max= tmp_ts;
1559
            pos_max= tmp_pos;
1560 6fd93ce2 Kenneth Aafløy
            if(tmp_pos >= filesize)
1561
                break;
1562 8d14a25c Michael Niedermayer
        }
1563
        pos_limit= pos_max;
1564
    }
1565
1566 53f7c43f Michael Niedermayer
    if(ts_min > ts_max){
1567
        return -1;
1568
    }else if(ts_min == ts_max){
1569
        pos_limit= pos_min;
1570
    }
1571
1572 8d14a25c Michael Niedermayer
    no_change=0;
1573
    while (pos_min < pos_limit) {
1574
#ifdef DEBUG_SEEK
1575 115329f1 Diego Biurrun
        av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1576 8d14a25c Michael Niedermayer
               pos_min, pos_max,
1577
               ts_min, ts_max);
1578
#endif
1579
        assert(pos_limit <= pos_max);
1580
1581
        if(no_change==0){
1582
            int64_t approximate_keyframe_distance= pos_max - pos_limit;
1583
            // interpolate position (better than dichotomy)
1584 3ba1438d Michael Niedermayer
            pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1585
                + pos_min - approximate_keyframe_distance;
1586 8d14a25c Michael Niedermayer
        }else if(no_change==1){
1587
            // bisection, if interpolation failed to change min or max pos last time
1588
            pos = (pos_min + pos_limit)>>1;
1589
        }else{
1590 a85736f2 Diego Biurrun
            /* linear search if bisection failed, can only happen if there
1591
               are very few or no keyframes between min/max */
1592 8d14a25c Michael Niedermayer
            pos=pos_min;
1593
        }
1594
        if(pos <= pos_min)
1595
            pos= pos_min + 1;
1596
        else if(pos > pos_limit)
1597
            pos= pos_limit;
1598
        start_pos= pos;
1599
1600 89ddd2a9 Michael Niedermayer
        ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1601 8d14a25c Michael Niedermayer
        if(pos == pos_max)
1602
            no_change++;
1603
        else
1604
            no_change=0;
1605
#ifdef DEBUG_SEEK
1606 c0492097 Diego Biurrun
        av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1607
               pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit,
1608
               start_pos, no_change);
1609 8d14a25c Michael Niedermayer
#endif
1610 db2a0e22 Michael Niedermayer
        if(ts == AV_NOPTS_VALUE){
1611
            av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1612
            return -1;
1613
        }
1614 8d14a25c Michael Niedermayer
        assert(ts != AV_NOPTS_VALUE);
1615 3ba1438d Michael Niedermayer
        if (target_ts <= ts) {
1616 8d14a25c Michael Niedermayer
            pos_limit = start_pos - 1;
1617
            pos_max = pos;
1618
            ts_max = ts;
1619 3ba1438d Michael Niedermayer
        }
1620
        if (target_ts >= ts) {
1621 8d14a25c Michael Niedermayer
            pos_min = pos;
1622
            ts_min = ts;
1623
        }
1624
    }
1625 115329f1 Diego Biurrun
1626 3ba1438d Michael Niedermayer
    pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1627
    ts  = (flags & AVSEEK_FLAG_BACKWARD) ?  ts_min :  ts_max;
1628 8d14a25c Michael Niedermayer
#ifdef DEBUG_SEEK
1629
    pos_min = pos;
1630 89ddd2a9 Michael Niedermayer
    ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1631 8d14a25c Michael Niedermayer
    pos_min++;
1632 89ddd2a9 Michael Niedermayer
    ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1633 115329f1 Diego Biurrun
    av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1634 8d14a25c Michael Niedermayer
           pos, ts_min, target_ts, ts_max);
1635
#endif
1636 89ddd2a9 Michael Niedermayer
    *ts_ret= ts;
1637
    return pos;
1638 8d14a25c Michael Niedermayer
}
1639
1640 3ba1438d Michael Niedermayer
static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1641
    int64_t pos_min, pos_max;
1642
#if 0
1643
    AVStream *st;
1644

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

1648
    st= s->streams[stream_index];
1649
#endif
1650
1651
    pos_min = s->data_offset;
1652 76aa876e Anton Khirnov
    pos_max = avio_size(s->pb) - 1;
1653 3ba1438d Michael Niedermayer
1654
    if     (pos < pos_min) pos= pos_min;
1655
    else if(pos > pos_max) pos= pos_max;
1656
1657 6b4aa5da Anton Khirnov
    avio_seek(s->pb, pos, SEEK_SET);
1658 3ba1438d Michael Niedermayer
1659
#if 0
1660 8bcb147f Michael Niedermayer
    av_update_cur_dts(s, st, ts);
1661 3ba1438d Michael Niedermayer
#endif
1662
    return 0;
1663
}
1664
1665 115329f1 Diego Biurrun
static int av_seek_frame_generic(AVFormatContext *s,
1666 3ba1438d Michael Niedermayer
                                 int stream_index, int64_t timestamp, int flags)
1667 fb2758c8 Fabrice Bellard
{
1668 6659b32a Sean Soria
    int index;
1669
    int64_t ret;
1670 fb2758c8 Fabrice Bellard
    AVStream *st;
1671
    AVIndexEntry *ie;
1672
1673
    st = s->streams[stream_index];
1674 e9b78eeb Michael Niedermayer
1675 27a5fe5f Michael Niedermayer
    index = av_index_search_timestamp(st, timestamp, flags);
1676 e9b78eeb Michael Niedermayer
1677 8c3b161e Michael Niedermayer
    if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1678
        return -1;
1679
1680 b5a3541d Michael Niedermayer
    if(index < 0 || index==st->nb_index_entries-1){
1681 e9b78eeb Michael Niedermayer
        int i;
1682
        AVPacket pkt;
1683
1684 5e5c9086 Michael Niedermayer
        if(st->nb_index_entries){
1685
            assert(st->index_entries);
1686 e9b78eeb Michael Niedermayer
            ie= &st->index_entries[st->nb_index_entries-1];
1687 6b4aa5da Anton Khirnov
            if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1688 aaec4e03 Baptiste Coudurier
                return ret;
1689 e9b78eeb Michael Niedermayer
            av_update_cur_dts(s, st, ie->timestamp);
1690 aaec4e03 Baptiste Coudurier
        }else{
1691 6b4aa5da Anton Khirnov
            if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
1692 aaec4e03 Baptiste Coudurier
                return ret;
1693
        }
1694 e9b78eeb Michael Niedermayer
        for(i=0;; i++) {
1695 cda6902d Michael Niedermayer
            int ret;
1696
            do{
1697
                ret = av_read_frame(s, &pkt);
1698
            }while(ret == AVERROR(EAGAIN));
1699 e9b78eeb Michael Niedermayer
            if(ret<0)
1700
                break;
1701
            av_free_packet(&pkt);
1702
            if(stream_index == pkt.stream_index){
1703 cc947f04 Jean-Daniel Dupas
                if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
1704 e9b78eeb Michael Niedermayer
                    break;
1705
            }
1706
        }
1707
        index = av_index_search_timestamp(st, timestamp, flags);
1708
    }
1709 fb2758c8 Fabrice Bellard
    if (index < 0)
1710
        return -1;
1711
1712 972ffe62 Aurelien Jacobs
    ff_read_frame_flush(s);
1713 e9b78eeb Michael Niedermayer
    if (s->iformat->read_seek){
1714
        if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1715
            return 0;
1716
    }
1717
    ie = &st->index_entries[index];
1718 6b4aa5da Anton Khirnov
    if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1719 aaec4e03 Baptiste Coudurier
        return ret;
1720 8bcb147f Michael Niedermayer
    av_update_cur_dts(s, st, ie->timestamp);
1721 cdd5034f Michael Niedermayer
1722 fb2758c8 Fabrice Bellard
    return 0;
1723
}
1724
1725 3ba1438d Michael Niedermayer
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1726 fb2758c8 Fabrice Bellard
{
1727
    int ret;
1728 cdd5034f Michael Niedermayer
    AVStream *st;
1729 115329f1 Diego Biurrun
1730 972ffe62 Aurelien Jacobs
    ff_read_frame_flush(s);
1731 115329f1 Diego Biurrun
1732 3ba1438d Michael Niedermayer
    if(flags & AVSEEK_FLAG_BYTE)
1733
        return av_seek_frame_byte(s, stream_index, timestamp, flags);
1734 115329f1 Diego Biurrun
1735 cdd5034f Michael Niedermayer
    if(stream_index < 0){
1736
        stream_index= av_find_default_stream_index(s);
1737
        if(stream_index < 0)
1738
            return -1;
1739 115329f1 Diego Biurrun
1740 3ba1438d Michael Niedermayer
        st= s->streams[stream_index];
1741 eb497825 Nathan Kurz
       /* timestamp for default must be expressed in AV_TIME_BASE units */
1742 3ba1438d Michael Niedermayer
        timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1743 cdd5034f Michael Niedermayer
    }
1744
1745 fb2758c8 Fabrice Bellard
    /* first, we try the format specific seek */
1746
    if (s->iformat->read_seek)
1747 3ba1438d Michael Niedermayer
        ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1748 fb2758c8 Fabrice Bellard
    else
1749
        ret = -1;
1750
    if (ret >= 0) {
1751
        return 0;
1752
    }
1753 8d14a25c Michael Niedermayer
1754
    if(s->iformat->read_timestamp)
1755 3ba1438d Michael Niedermayer
        return av_seek_frame_binary(s, stream_index, timestamp, flags);
1756 8d14a25c Michael Niedermayer
    else
1757 3ba1438d Michael Niedermayer
        return av_seek_frame_generic(s, stream_index, timestamp, flags);
1758 fb2758c8 Fabrice Bellard
}
1759
1760 32d88592 Michael Niedermayer
int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1761
{
1762
    if(min_ts > ts || max_ts < ts)
1763
        return -1;
1764
1765 972ffe62 Aurelien Jacobs
    ff_read_frame_flush(s);
1766 32d88592 Michael Niedermayer
1767
    if (s->iformat->read_seek2)
1768
        return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1769
1770
    if(s->iformat->read_timestamp){
1771
        //try to seek via read_timestamp()
1772
    }
1773
1774
    //Fallback to old API if new is not implemented but old is
1775
    //Note the old has somewat different sematics
1776
    if(s->iformat->read_seek || 1)
1777 85b4230f Michael Niedermayer
        return av_seek_frame(s, stream_index, ts, flags | (ts - min_ts > (uint64_t)(max_ts - ts) ? AVSEEK_FLAG_BACKWARD : 0));
1778 32d88592 Michael Niedermayer
1779
    // try some generic seek like av_seek_frame_generic() but with new ts semantics
1780
}
1781
1782 fb2758c8 Fabrice Bellard
/*******************************************************/
1783 12f996ed Fabrice Bellard
1784 e36bdf8b Daniel Kristjansson
/**
1785 49bd8e4b Måns Rullgård
 * Return TRUE if the stream has accurate duration in any stream.
1786 e36bdf8b Daniel Kristjansson
 *
1787 c1e8b678 Neil Brown
 * @return TRUE if the stream has accurate duration for at least one component.
1788 e36bdf8b Daniel Kristjansson
 */
1789 c1e8b678 Neil Brown
static int av_has_duration(AVFormatContext *ic)
1790 12f996ed Fabrice Bellard
{
1791
    int i;
1792
    AVStream *st;
1793
1794
    for(i = 0;i < ic->nb_streams; i++) {
1795
        st = ic->streams[i];
1796 c1e8b678 Neil Brown
        if (st->duration != AV_NOPTS_VALUE)
1797 12f996ed Fabrice Bellard
            return 1;
1798
    }
1799
    return 0;
1800
}
1801
1802 e36bdf8b Daniel Kristjansson
/**
1803
 * Estimate the stream timings from the one of each components.
1804
 *
1805
 * Also computes the global bitrate if possible.
1806
 */
1807 12f996ed Fabrice Bellard
static void av_update_stream_timings(AVFormatContext *ic)
1808
{
1809 c0df9d75 Michael Niedermayer
    int64_t start_time, start_time1, end_time, end_time1;
1810 c1e8b678 Neil Brown
    int64_t duration, duration1;
1811 12f996ed Fabrice Bellard
    int i;
1812
    AVStream *st;
1813
1814 f27a7268 Måns Rullgård
    start_time = INT64_MAX;
1815
    end_time = INT64_MIN;
1816 c1e8b678 Neil Brown
    duration = INT64_MIN;
1817 12f996ed Fabrice Bellard
    for(i = 0;i < ic->nb_streams; i++) {
1818
        st = ic->streams[i];
1819 7f938dd3 Aurelien Jacobs
        if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1820 c0df9d75 Michael Niedermayer
            start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1821
            if (start_time1 < start_time)
1822
                start_time = start_time1;
1823 12f996ed Fabrice Bellard
            if (st->duration != AV_NOPTS_VALUE) {
1824 c0df9d75 Michael Niedermayer
                end_time1 = start_time1
1825
                          + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1826 12f996ed Fabrice Bellard
                if (end_time1 > end_time)
1827
                    end_time = end_time1;
1828
            }
1829
        }
1830 c1e8b678 Neil Brown
        if (st->duration != AV_NOPTS_VALUE) {
1831
            duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1832
            if (duration1 > duration)
1833
                duration = duration1;
1834
        }
1835 12f996ed Fabrice Bellard
    }
1836 f27a7268 Måns Rullgård
    if (start_time != INT64_MAX) {
1837 12f996ed Fabrice Bellard
        ic->start_time = start_time;
1838 f27a7268 Måns Rullgård
        if (end_time != INT64_MIN) {
1839 c1e8b678 Neil Brown
            if (end_time - start_time > duration)
1840
                duration = end_time - start_time;
1841
        }
1842
    }
1843
    if (duration != INT64_MIN) {
1844
        ic->duration = duration;
1845
        if (ic->file_size > 0) {
1846 a85736f2 Diego Biurrun
            /* compute the bitrate */
1847 c1e8b678 Neil Brown
            ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1848
                (double)ic->duration;
1849 12f996ed Fabrice Bellard
        }
1850
    }
1851
}
1852
1853
static void fill_all_stream_timings(AVFormatContext *ic)
1854
{
1855
    int i;
1856
    AVStream *st;
1857
1858
    av_update_stream_timings(ic);
1859
    for(i = 0;i < ic->nb_streams; i++) {
1860
        st = ic->streams[i];
1861
        if (st->start_time == AV_NOPTS_VALUE) {
1862 c0df9d75 Michael Niedermayer
            if(ic->start_time != AV_NOPTS_VALUE)
1863
                st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1864
            if(ic->duration != AV_NOPTS_VALUE)
1865
                st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1866 12f996ed Fabrice Bellard
        }
1867
    }
1868
}
1869
1870
static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1871
{
1872
    int64_t filesize, duration;
1873
    int bit_rate, i;
1874
    AVStream *st;
1875
1876
    /* if bit_rate is already set, we believe it */
1877 9100d4d6 David Czech
    if (ic->bit_rate <= 0) {
1878 12f996ed Fabrice Bellard
        bit_rate = 0;
1879
        for(i=0;i<ic->nb_streams;i++) {
1880
            st = ic->streams[i];
1881 9100d4d6 David Czech
            if (st->codec->bit_rate > 0)
1882 01f4895c Michael Niedermayer
            bit_rate += st->codec->bit_rate;
1883 12f996ed Fabrice Bellard
        }
1884
        ic->bit_rate = bit_rate;
1885
    }
1886
1887
    /* if duration is already set, we believe it */
1888 115329f1 Diego Biurrun
    if (ic->duration == AV_NOPTS_VALUE &&
1889
        ic->bit_rate != 0 &&
1890 12f996ed Fabrice Bellard
        ic->file_size != 0)  {
1891
        filesize = ic->file_size;
1892
        if (filesize > 0) {
1893
            for(i = 0; i < ic->nb_streams; i++) {
1894
                st = ic->streams[i];
1895 c0df9d75 Michael Niedermayer
                duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1896 9f32041d Neil Brown
                if (st->duration == AV_NOPTS_VALUE)
1897 12f996ed Fabrice Bellard
                    st->duration = duration;
1898
            }
1899
        }
1900
    }
1901
}
1902
1903
#define DURATION_MAX_READ_SIZE 250000
1904 411ff322 Michael Niedermayer
#define DURATION_MAX_RETRY 3
1905 12f996ed Fabrice Bellard
1906
/* only usable for MPEG-PS streams */
1907 bc5c918e Diego Biurrun
static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1908 12f996ed Fabrice Bellard
{
1909
    AVPacket pkt1, *pkt = &pkt1;
1910
    AVStream *st;
1911
    int read_size, i, ret;
1912 3e4318bf Aurelien Jacobs
    int64_t end_time;
1913 12f996ed Fabrice Bellard
    int64_t filesize, offset, duration;
1914 411ff322 Michael Niedermayer
    int retry=0;
1915 115329f1 Diego Biurrun
1916 578688fa Luca Abeni
    ic->cur_st = NULL;
1917
1918
    /* flush packet queue */
1919
    flush_packet_queue(ic);
1920
1921 e99179de Aurelien Jacobs
    for (i=0; i<ic->nb_streams; i++) {
1922 578688fa Luca Abeni
        st = ic->streams[i];
1923 3e4318bf Aurelien Jacobs
        if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
1924 cc20679a Michael Niedermayer
            av_log(st->codec, AV_LOG_WARNING, "start time is not set in av_estimate_timings_from_pts\n");
1925
1926 578688fa Luca Abeni
        if (st->parser) {
1927
            av_parser_close(st->parser);
1928
            st->parser= NULL;
1929 3a41c2f7 Michael Niedermayer
            av_free_packet(&st->cur_pkt);
1930 578688fa Luca Abeni
        }
1931
    }
1932 115329f1 Diego Biurrun
1933 12f996ed Fabrice Bellard
    /* estimate the end time (duration) */
1934
    /* XXX: may need to support wrapping */
1935
    filesize = ic->file_size;
1936 411ff322 Michael Niedermayer
    end_time = AV_NOPTS_VALUE;
1937
    do{
1938
    offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
1939 12f996ed Fabrice Bellard
    if (offset < 0)
1940
        offset = 0;
1941
1942 6b4aa5da Anton Khirnov
    avio_seek(ic->pb, offset, SEEK_SET);
1943 12f996ed Fabrice Bellard
    read_size = 0;
1944
    for(;;) {
1945 411ff322 Michael Niedermayer
        if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
1946 12f996ed Fabrice Bellard
            break;
1947 115329f1 Diego Biurrun
1948 cda6902d Michael Niedermayer
        do{
1949
            ret = av_read_packet(ic, pkt);
1950
        }while(ret == AVERROR(EAGAIN));
1951 12f996ed Fabrice Bellard
        if (ret != 0)
1952
            break;
1953
        read_size += pkt->size;
1954
        st = ic->streams[pkt->stream_index];
1955 bf494092 Neil Brown
        if (pkt->pts != AV_NOPTS_VALUE &&
1956 3e4318bf Aurelien Jacobs
            (st->start_time != AV_NOPTS_VALUE ||
1957
             st->first_dts  != AV_NOPTS_VALUE)) {
1958
            duration = end_time = pkt->pts;
1959
            if (st->start_time != AV_NOPTS_VALUE)  duration -= st->start_time;
1960
            else                                   duration -= st->first_dts;
1961 d30a8beb Michael Niedermayer
            if (duration < 0)
1962
                duration += 1LL<<st->pts_wrap_bits;
1963 12f996ed Fabrice Bellard
            if (duration > 0) {
1964
                if (st->duration == AV_NOPTS_VALUE ||
1965
                    st->duration < duration)
1966
                    st->duration = duration;
1967
            }
1968
        }
1969
        av_free_packet(pkt);
1970
    }
1971 411ff322 Michael Niedermayer
    }while(   end_time==AV_NOPTS_VALUE
1972
           && filesize > (DURATION_MAX_READ_SIZE<<retry)
1973
           && ++retry <= DURATION_MAX_RETRY);
1974 115329f1 Diego Biurrun
1975 c0df9d75 Michael Niedermayer
    fill_all_stream_timings(ic);
1976 12f996ed Fabrice Bellard
1977 6b4aa5da Anton Khirnov
    avio_seek(ic->pb, old_offset, SEEK_SET);
1978 e99179de Aurelien Jacobs
    for (i=0; i<ic->nb_streams; i++) {
1979 df886e7e Michael Niedermayer
        st= ic->streams[i];
1980
        st->cur_dts= st->first_dts;
1981 635fbcb1 Michael Niedermayer
        st->last_IP_pts = AV_NOPTS_VALUE;
1982 df886e7e Michael Niedermayer
    }
1983 12f996ed Fabrice Bellard
}
1984
1985 bc5c918e Diego Biurrun
static void av_estimate_timings(AVFormatContext *ic, int64_t old_offset)
1986 12f996ed Fabrice Bellard
{
1987
    int64_t file_size;
1988
1989
    /* get the file size, if possible */
1990
    if (ic->iformat->flags & AVFMT_NOFILE) {
1991
        file_size = 0;
1992
    } else {
1993 76aa876e Anton Khirnov
        file_size = avio_size(ic->pb);
1994 12f996ed Fabrice Bellard
        if (file_size < 0)
1995
            file_size = 0;
1996
    }
1997
    ic->file_size = file_size;
1998
1999 ff70e601 Måns Rullgård
    if ((!strcmp(ic->iformat->name, "mpeg") ||
2000
         !strcmp(ic->iformat->name, "mpegts")) &&
2001 8978feda Anton Khirnov
        file_size && ic->pb->seekable) {
2002 12f996ed Fabrice Bellard
        /* get accurate estimate from the PTSes */
2003 9ecf7fad Wolfram Gloger
        av_estimate_timings_from_pts(ic, old_offset);
2004 c1e8b678 Neil Brown
    } else if (av_has_duration(ic)) {
2005 a85736f2 Diego Biurrun
        /* at least one component has timings - we use them for all
2006 12f996ed Fabrice Bellard
           the components */
2007
        fill_all_stream_timings(ic);
2008
    } else {
2009 77ac76a3 Michael Niedermayer
        av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
2010 a85736f2 Diego Biurrun
        /* less precise: use bitrate info */
2011 12f996ed Fabrice Bellard
        av_estimate_timings_from_bit_rate(ic);
2012
    }
2013
    av_update_stream_timings(ic);
2014
2015
#if 0
2016
    {
2017
        int i;
2018
        AVStream *st;
2019
        for(i = 0;i < ic->nb_streams; i++) {
2020
            st = ic->streams[i];
2021 115329f1 Diego Biurrun
        printf("%d: start_time: %0.3f duration: %0.3f\n",
2022
               i, (double)st->start_time / AV_TIME_BASE,
2023 12f996ed Fabrice Bellard
               (double)st->duration / AV_TIME_BASE);
2024
        }
2025 115329f1 Diego Biurrun
        printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2026
               (double)ic->start_time / AV_TIME_BASE,
2027 12f996ed Fabrice Bellard
               (double)ic->duration / AV_TIME_BASE,
2028
               ic->bit_rate / 1000);
2029
    }
2030
#endif
2031
}
2032
2033 b9a281db Fabrice Bellard
static int has_codec_parameters(AVCodecContext *enc)
2034
{
2035
    int val;
2036
    switch(enc->codec_type) {
2037 72415b2a Stefano Sabatini
    case AVMEDIA_TYPE_AUDIO:
2038 5d6e4c16 Stefano Sabatini
        val = enc->sample_rate && enc->channels && enc->sample_fmt != AV_SAMPLE_FMT_NONE;
2039 f3b5a1a2 Baptiste Coudurier
        if(!enc->frame_size &&
2040
           (enc->codec_id == CODEC_ID_VORBIS ||
2041 1d07029f Justin Ruggles
            enc->codec_id == CODEC_ID_AAC ||
2042 b7884740 Michael Niedermayer
            enc->codec_id == CODEC_ID_MP1 ||
2043
            enc->codec_id == CODEC_ID_MP2 ||
2044 8425ceca Baptiste Coudurier
            enc->codec_id == CODEC_ID_MP3 ||
2045 1d07029f Justin Ruggles
            enc->codec_id == CODEC_ID_SPEEX))
2046 4d35bf74 Michael Niedermayer
            return 0;
2047 b9a281db Fabrice Bellard
        break;
2048 72415b2a Stefano Sabatini
    case AVMEDIA_TYPE_VIDEO:
2049 644a9262 Michael Niedermayer
        val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
2050 b9a281db Fabrice Bellard
        break;
2051
    default:
2052
        val = 1;
2053
        break;
2054
    }
2055 ccd425e7 Diego Biurrun
    return enc->codec_id != CODEC_ID_NONE && val != 0;
2056 b9a281db Fabrice Bellard
}
2057
2058 ae447836 Baptiste Coudurier
static int has_decode_delay_been_guessed(AVStream *st)
2059
{
2060
    return st->codec->codec_id != CODEC_ID_H264 ||
2061 581ba2ce Baptiste Coudurier
        st->codec_info_nb_frames >= 6 + st->codec->has_b_frames;
2062 ae447836 Baptiste Coudurier
}
2063
2064 655d47c2 Thilo Borgmann
static int try_decode_frame(AVStream *st, AVPacket *avpkt)
2065 fb2758c8 Fabrice Bellard
{
2066
    int16_t *samples;
2067
    AVCodec *codec;
2068 3fdb6af9 Baptiste Coudurier
    int got_picture, data_size, ret=0;
2069 fb2758c8 Fabrice Bellard
    AVFrame picture;
2070 115329f1 Diego Biurrun
2071 e472ea34 Baptiste Coudurier
    if(!st->codec->codec){
2072
        codec = avcodec_find_decoder(st->codec->codec_id);
2073
        if (!codec)
2074
            return -1;
2075
        ret = avcodec_open(st->codec, codec);
2076
        if (ret < 0)
2077
            return ret;
2078
    }
2079 644a9262 Michael Niedermayer
2080 ae447836 Baptiste Coudurier
    if(!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st)){
2081 e472ea34 Baptiste Coudurier
        switch(st->codec->codec_type) {
2082 72415b2a Stefano Sabatini
        case AVMEDIA_TYPE_VIDEO:
2083 1bd280f7 Baptiste Coudurier
            avcodec_get_frame_defaults(&picture);
2084 e472ea34 Baptiste Coudurier
            ret = avcodec_decode_video2(st->codec, &picture,
2085
                                        &got_picture, avpkt);
2086
            break;
2087 72415b2a Stefano Sabatini
        case AVMEDIA_TYPE_AUDIO:
2088 e472ea34 Baptiste Coudurier
            data_size = FFMAX(avpkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
2089
            samples = av_malloc(data_size);
2090
            if (!samples)
2091
                goto fail;
2092
            ret = avcodec_decode_audio3(st->codec, samples,
2093
                                        &data_size, avpkt);
2094
            av_free(samples);
2095
            break;
2096
        default:
2097
            break;
2098
        }
2099 fb2758c8 Fabrice Bellard
    }
2100
 fail:
2101
    return ret;
2102
}
2103
2104 83c27079 Stefano Sabatini
unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum CodecID id)
2105 45da8124 Aurelien Jacobs
{
2106
    while (tags->id != CODEC_ID_NONE) {
2107
        if (tags->id == id)
2108
            return tags->tag;
2109
        tags++;
2110
    }
2111
    return 0;
2112
}
2113
2114 1a40491e Daniel Verkamp
enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2115 45da8124 Aurelien Jacobs
{
2116 41415d28 Michael Niedermayer
    int i;
2117
    for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
2118
        if(tag == tags[i].tag)
2119
            return tags[i].id;
2120
    }
2121
    for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
2122 603a5f04 Francesco Lavra
        if (ff_toupper4(tag) == ff_toupper4(tags[i].tag))
2123 41415d28 Michael Niedermayer
            return tags[i].id;
2124 45da8124 Aurelien Jacobs
    }
2125
    return CODEC_ID_NONE;
2126
}
2127
2128 15545a09 Stefano Sabatini
unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
2129 45da8124 Aurelien Jacobs
{
2130
    int i;
2131
    for(i=0; tags && tags[i]; i++){
2132 1a40491e Daniel Verkamp
        int tag= ff_codec_get_tag(tags[i], id);
2133 45da8124 Aurelien Jacobs
        if(tag) return tag;
2134
    }
2135
    return 0;
2136
}
2137
2138 15545a09 Stefano Sabatini
enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2139 45da8124 Aurelien Jacobs
{
2140
    int i;
2141
    for(i=0; tags && tags[i]; i++){
2142 1a40491e Daniel Verkamp
        enum CodecID id= ff_codec_get_id(tags[i], tag);
2143 45da8124 Aurelien Jacobs
        if(id!=CODEC_ID_NONE) return id;
2144
    }
2145
    return CODEC_ID_NONE;
2146
}
2147
2148 c2c3dedf Aurelien Jacobs
static void compute_chapters_end(AVFormatContext *s)
2149
{
2150 ab11317c Anton Khirnov
    unsigned int i, j;
2151
    int64_t max_time = s->duration + (s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time;
2152 c2c3dedf Aurelien Jacobs
2153 ab11317c Anton Khirnov
    for (i = 0; i < s->nb_chapters; i++)
2154 c2c3dedf Aurelien Jacobs
        if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2155 ab11317c Anton Khirnov
            AVChapter *ch = s->chapters[i];
2156
            int64_t   end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
2157
                                     : INT64_MAX;
2158
2159
            for (j = 0; j < s->nb_chapters; j++) {
2160
                AVChapter *ch1 = s->chapters[j];
2161
                int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
2162
                if (j != i && next_start > ch->start && next_start < end)
2163
                    end = next_start;
2164
            }
2165
            ch->end = (end == INT64_MAX) ? ch->start : end;
2166 c2c3dedf Aurelien Jacobs
        }
2167
}
2168
2169 4d43cbcc Michael Niedermayer
static int get_std_framerate(int i){
2170
    if(i<60*12) return i*1001;
2171 aecf157e Reimar Döffinger
    else        return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2172 4d43cbcc Michael Niedermayer
}
2173
2174 945208ca Michael Niedermayer
/*
2175
 * Is the time base unreliable.
2176
 * This is a heuristic to balance between quick acceptance of the values in
2177
 * the headers vs. some extra checks.
2178 a85736f2 Diego Biurrun
 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2179
 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2180 945208ca Michael Niedermayer
 * And there are "variable" fps files this needs to detect as well.
2181
 */
2182
static int tb_unreliable(AVCodecContext *c){
2183
    if(   c->time_base.den >= 101L*c->time_base.num
2184
       || c->time_base.den <    5L*c->time_base.num
2185 2bb6eba2 Aurelien Jacobs
/*       || c->codec_tag == AV_RL32("DIVX")
2186
       || c->codec_tag == AV_RL32("XVID")*/
2187 7f123e7f Michael Niedermayer
       || c->codec_id == CODEC_ID_MPEG2VIDEO
2188
       || c->codec_id == CODEC_ID_H264
2189
       )
2190 945208ca Michael Niedermayer
        return 1;
2191
    return 0;
2192
}
2193
2194 b9a281db Fabrice Bellard
int av_find_stream_info(AVFormatContext *ic)
2195
{
2196 9f75260e Michael Niedermayer
    int i, count, ret, read_size, j;
2197 b9a281db Fabrice Bellard
    AVStream *st;
2198 fb2758c8 Fabrice Bellard
    AVPacket pkt1, *pkt;
2199 a2704c97 Anton Khirnov
    int64_t old_offset = avio_tell(ic->pb);
2200 0cbff027 Kristian Amlie
2201 c0df9d75 Michael Niedermayer
    for(i=0;i<ic->nb_streams;i++) {
2202 62784e37 Benjamin Larsson
        AVCodec *codec;
2203 c0df9d75 Michael Niedermayer
        st = ic->streams[i];
2204 e7e291e9 Alex Converse
        if (st->codec->codec_id == CODEC_ID_AAC) {
2205
            st->codec->sample_rate = 0;
2206
            st->codec->frame_size = 0;
2207
            st->codec->channels = 0;
2208
        }
2209 b3c0fc76 Aurelien Jacobs
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2210
            st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2211 c0df9d75 Michael Niedermayer
/*            if(!st->time_base.num)
2212
                st->time_base= */
2213 01f4895c Michael Niedermayer
            if(!st->codec->time_base.num)
2214
                st->codec->time_base= st->time_base;
2215 c0df9d75 Michael Niedermayer
        }
2216 90ad92b3 Michael Niedermayer
        //only for the split stuff
2217 fe8344a2 Michael Niedermayer
        if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2218 01f4895c Michael Niedermayer
            st->parser = av_parser_init(st->codec->codec_id);
2219 57004ff1 Aurelien Jacobs
            if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2220 7cbaa7ba Michael Niedermayer
                st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2221
            }
2222 90ad92b3 Michael Niedermayer
        }
2223 43e4d57f Michael Niedermayer
        assert(!st->codec->codec);
2224 62784e37 Benjamin Larsson
        codec = avcodec_find_decoder(st->codec->codec_id);
2225
2226
        /* Force decoding of at least one frame of codec data
2227
         * this makes sure the codec initializes the channel configuration
2228
         * and does not trust the values from the container.
2229
         */
2230
        if (codec && codec->capabilities & CODEC_CAP_CHANNEL_CONF)
2231
            st->codec->channels = 0;
2232
2233 cb2c971d Aurelien Jacobs
        /* Ensure that subtitle_header is properly set. */
2234
        if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
2235
            && codec && !st->codec->codec)
2236
            avcodec_open(st->codec, codec);
2237
2238 43e4d57f Michael Niedermayer
        //try to just open decoders, in case this is enough to get parameters
2239
        if(!has_codec_parameters(st->codec)){
2240 cb2c971d Aurelien Jacobs
            if (codec && !st->codec->codec)
2241 43e4d57f Michael Niedermayer
                avcodec_open(st->codec, codec);
2242
        }
2243 c0df9d75 Michael Niedermayer
    }
2244
2245 feb2440c Aurelien Jacobs
    for (i=0; i<ic->nb_streams; i++) {
2246 fd0368e7 Aurelien Jacobs
        ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
2247 15bc38e5 Michael Niedermayer
    }
2248 115329f1 Diego Biurrun
2249 b9a281db Fabrice Bellard
    count = 0;
2250
    read_size = 0;
2251
    for(;;) {
2252 1d14361d Michael Niedermayer
        if(url_interrupt_cb()){
2253 c76374c6 Nicolas George
            ret= AVERROR_EXIT;
2254 71ee6515 Michael Niedermayer
            av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2255 1d14361d Michael Niedermayer
            break;
2256
        }
2257
2258 b9a281db Fabrice Bellard
        /* check if one codec still needs to be handled */
2259
        for(i=0;i<ic->nb_streams;i++) {
2260
            st = ic->streams[i];
2261 01f4895c Michael Niedermayer
            if (!has_codec_parameters(st->codec))
2262 b9a281db Fabrice Bellard
                break;
2263 3e76d1b5 Michael Niedermayer
            /* variable fps and no guess at the real fps */
2264 0e5f33f2 Michael Niedermayer
            if(   tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)
2265 fd0368e7 Aurelien Jacobs
               && st->info->duration_count<20 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2266 3e76d1b5 Michael Niedermayer
                break;
2267 01f4895c Michael Niedermayer
            if(st->parser && st->parser->parser->split && !st->codec->extradata)
2268 90ad92b3 Michael Niedermayer
                break;
2269 82583548 Michael Niedermayer
            if(st->first_dts == AV_NOPTS_VALUE)
2270
                break;
2271 b9a281db Fabrice Bellard
        }
2272
        if (i == ic->nb_streams) {
2273
            /* NOTE: if the format has no header, then we need to read
2274
               some packets to get most of the streams, so we cannot
2275
               stop here */
2276 fb2758c8 Fabrice Bellard
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2277 b9a281db Fabrice Bellard
                /* if we found the info for all the codecs, we can stop */
2278
                ret = count;
2279 71ee6515 Michael Niedermayer
                av_log(ic, AV_LOG_DEBUG, "All info found\n");
2280 b9a281db Fabrice Bellard
                break;
2281
            }
2282 5fb83c38 Michael Niedermayer
        }
2283 35eab0c0 Michael Niedermayer
        /* we did not get all the codec info, but we read too much data */
2284 57011a13 Baptiste Coudurier
        if (read_size >= ic->probesize) {
2285 35eab0c0 Michael Niedermayer
            ret = count;
2286 9bbe9a0d Jai Menon
            av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2287 35eab0c0 Michael Niedermayer
            break;
2288
        }
2289 b9a281db Fabrice Bellard
2290 fb2758c8 Fabrice Bellard
        /* NOTE: a new stream can be added there if no header in file
2291
           (AVFMTCTX_NOHEADER) */
2292
        ret = av_read_frame_internal(ic, &pkt1);
2293 feb2440c Aurelien Jacobs
        if (ret < 0 && ret != AVERROR(EAGAIN)) {
2294 fb2758c8 Fabrice Bellard
            /* EOF or error */
2295
            ret = -1; /* we could not have all the codec parameters before EOF */
2296 e19456e3 Michael Niedermayer
            for(i=0;i<ic->nb_streams;i++) {
2297
                st = ic->streams[i];
2298 305ee50f Michael Niedermayer
                if (!has_codec_parameters(st->codec)){
2299
                    char buf[256];
2300
                    avcodec_string(buf, sizeof(buf), st->codec, 0);
2301 657eca1f Michael Niedermayer
                    av_log(ic, AV_LOG_WARNING, "Could not find codec parameters (%s)\n", buf);
2302 344a18c3 Måns Rullgård
                } else {
2303
                    ret = 0;
2304 305ee50f Michael Niedermayer
                }
2305 e19456e3 Michael Niedermayer
            }
2306 fb2758c8 Fabrice Bellard
            break;
2307
        }
2308
2309 feb2440c Aurelien Jacobs
        if (ret == AVERROR(EAGAIN))
2310
            continue;
2311
2312 5c5b1731 Måns Rullgård
        pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
2313 fd0368e7 Aurelien Jacobs
        if ((ret = av_dup_packet(pkt)) < 0)
2314
            goto find_stream_info_err;
2315 b9a281db Fabrice Bellard
2316 fb2758c8 Fabrice Bellard
        read_size += pkt->size;
2317 b9a281db Fabrice Bellard
2318
        st = ic->streams[pkt->stream_index];
2319 fd0368e7 Aurelien Jacobs
        if (st->codec_info_nb_frames>1) {
2320
            if (st->time_base.den > 0 && av_rescale_q(st->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
2321 657eca1f Michael Niedermayer
                av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2322 3a560188 Baptiste Coudurier
                break;
2323 71ee6515 Michael Niedermayer
            }
2324 fd0368e7 Aurelien Jacobs
            st->info->codec_info_duration += pkt->duration;
2325 3a560188 Baptiste Coudurier
        }
2326 cefe0607 Michael Niedermayer
        {
2327 fd0368e7 Aurelien Jacobs
            int64_t last = st->info->last_dts;
2328 3c150d16 Michael Niedermayer
            int64_t duration= pkt->dts - last;
2329
2330
            if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
2331 4d43cbcc Michael Niedermayer
                double dur= duration * av_q2d(st->time_base);
2332
2333 72415b2a Stefano Sabatini
//                if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2334 4d43cbcc Michael Niedermayer
//                    av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
2335 fd0368e7 Aurelien Jacobs
                if (st->info->duration_count < 2)
2336
                    memset(st->info->duration_error, 0, sizeof(st->info->duration_error));
2337
                for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error); i++) {
2338 69c262d1 Michael Niedermayer
                    int framerate= get_std_framerate(i);
2339
                    int ticks= lrintf(dur*framerate/(1001*12));
2340
                    double error= dur - ticks*1001*12/(double)framerate;
2341 fd0368e7 Aurelien Jacobs
                    st->info->duration_error[i] += error*error;
2342 69c262d1 Michael Niedermayer
                }
2343 fd0368e7 Aurelien Jacobs
                st->info->duration_count++;
2344 85142724 Reimar Döffinger
                // ignore the first 4 values, they might have some random jitter
2345 fd0368e7 Aurelien Jacobs
                if (st->info->duration_count > 3)
2346
                    st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
2347 15bc38e5 Michael Niedermayer
            }
2348 fd0368e7 Aurelien Jacobs
            if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
2349
                st->info->last_dts = pkt->dts;
2350 15bc38e5 Michael Niedermayer
        }
2351 01f4895c Michael Niedermayer
        if(st->parser && st->parser->parser->split && !st->codec->extradata){
2352
            int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2353 90ad92b3 Michael Niedermayer
            if(i){
2354 01f4895c Michael Niedermayer
                st->codec->extradata_size= i;
2355 62c52121 Måns Rullgård
                st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2356 01f4895c Michael Niedermayer
                memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2357 62c52121 Måns Rullgård
                memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2358 90ad92b3 Michael Niedermayer
            }
2359
        }
2360 115329f1 Diego Biurrun
2361 fb2758c8 Fabrice Bellard
        /* if still no information, we try to open the codec and to
2362
           decompress the frame. We try to avoid that in most cases as
2363 a85736f2 Diego Biurrun
           it takes longer and uses more memory. For MPEG-4, we need to
2364
           decompress for QuickTime. */
2365 ae447836 Baptiste Coudurier
        if (!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st))
2366 655d47c2 Thilo Borgmann
            try_decode_frame(st, pkt);
2367 115329f1 Diego Biurrun
2368 9d3fdf20 Baptiste Coudurier
        st->codec_info_nb_frames++;
2369 b9a281db Fabrice Bellard
        count++;
2370
    }
2371
2372 bd107136 Diego Biurrun
    // close codecs which were opened in try_decode_frame()
2373 43c0040a Michael Niedermayer
    for(i=0;i<ic->nb_streams;i++) {
2374
        st = ic->streams[i];
2375 01f4895c Michael Niedermayer
        if(st->codec->codec)
2376
            avcodec_close(st->codec);
2377 43c0040a Michael Niedermayer
    }
2378 b9a281db Fabrice Bellard
    for(i=0;i<ic->nb_streams;i++) {
2379
        st = ic->streams[i];
2380 fd0368e7 Aurelien Jacobs
        if (st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && st->info->codec_info_duration)
2381 02b398ef Michael Niedermayer
            av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2382 6c6e6ef5 Michael Niedermayer
                     (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,
2383 fd0368e7 Aurelien Jacobs
                      st->info->codec_info_duration*(int64_t)st->time_base.num, 60000);
2384 72415b2a Stefano Sabatini
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2385 dd1c8f3e Luca Abeni
            if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample)
2386 01f4895c Michael Niedermayer
                st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2387 15bc38e5 Michael Niedermayer
2388 85142724 Reimar Döffinger
            // the check for tb_unreliable() is not completely correct, since this is not about handling
2389
            // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2390
            // ipmovie.c produces.
2391 fd0368e7 Aurelien Jacobs
            if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > 1 && !st->r_frame_rate.num)
2392
                av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * st->info->duration_gcd, INT_MAX);
2393
            if (st->info->duration_count && !st->r_frame_rate.num
2394 945208ca Michael Niedermayer
               && tb_unreliable(st->codec) /*&&
2395 a85736f2 Diego Biurrun
               //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2396 fd0368e7 Aurelien Jacobs
               st->time_base.num*duration_sum[i]/st->info->duration_count*101LL > st->time_base.den*/){
2397 fe02d9e7 Reimar Döffinger
                int num = 0;
2398 4d43cbcc Michael Niedermayer
                double best_error= 2*av_q2d(st->time_base);
2399 fd0368e7 Aurelien Jacobs
                best_error = best_error*best_error*st->info->duration_count*1000*12*30;
2400 4d43cbcc Michael Niedermayer
2401 fd0368e7 Aurelien Jacobs
                for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error); j++) {
2402
                    double error = st->info->duration_error[j] * get_std_framerate(j);
2403 72415b2a Stefano Sabatini
//                    if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2404 4d43cbcc Michael Niedermayer
//                        av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
2405 9f75260e Michael Niedermayer
                    if(error < best_error){
2406
                        best_error= error;
2407 fe02d9e7 Reimar Döffinger
                        num = get_std_framerate(j);
2408 9f75260e Michael Niedermayer
                    }
2409 3c150d16 Michael Niedermayer
                }
2410 fe02d9e7 Reimar Döffinger
                // do not increase frame rate by more than 1 % in order to match a standard rate.
2411
                if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
2412
                    av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2413 15bc38e5 Michael Niedermayer
            }
2414
2415 c0df9d75 Michael Niedermayer
            if (!st->r_frame_rate.num){
2416 5523d5f4 Michael Niedermayer
                if(    st->codec->time_base.den * (int64_t)st->time_base.num
2417 3797c74b Michael Niedermayer
                    <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){
2418 5523d5f4 Michael Niedermayer
                    st->r_frame_rate.num = st->codec->time_base.den;
2419 3797c74b Michael Niedermayer
                    st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
2420 5523d5f4 Michael Niedermayer
                }else{
2421
                    st->r_frame_rate.num = st->time_base.den;
2422
                    st->r_frame_rate.den = st->time_base.num;
2423
                }
2424 14bea432 Michael Niedermayer
            }
2425 72415b2a Stefano Sabatini
        }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2426 dd1c8f3e Luca Abeni
            if(!st->codec->bits_per_coded_sample)
2427
                st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2428 c70a6a41 Justin Ruggles
            // set stream disposition based on audio service type
2429
            switch (st->codec->audio_service_type) {
2430
            case AV_AUDIO_SERVICE_TYPE_EFFECTS:
2431
                st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;    break;
2432
            case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
2433
                st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;  break;
2434
            case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
2435
                st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
2436
            case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
2437
                st->disposition = AV_DISPOSITION_COMMENT;          break;
2438
            case AV_AUDIO_SERVICE_TYPE_KARAOKE:
2439
                st->disposition = AV_DISPOSITION_KARAOKE;          break;
2440
            }
2441 b9a281db Fabrice Bellard
        }
2442 de6d9b64 Fabrice Bellard
    }
2443 b9a281db Fabrice Bellard
2444 9ecf7fad Wolfram Gloger
    av_estimate_timings(ic, old_offset);
2445 6fea687e John Donaghy
2446 c2c3dedf Aurelien Jacobs
    compute_chapters_end(ic);
2447
2448 e928649b Michael Niedermayer
#if 0
2449 a85736f2 Diego Biurrun
    /* correct DTS for B-frame streams with no timestamps */
2450 e928649b Michael Niedermayer
    for(i=0;i<ic->nb_streams;i++) {
2451
        st = ic->streams[i];
2452 72415b2a Stefano Sabatini
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2453 e928649b Michael Niedermayer
            if(b-frames){
2454
                ppktl = &ic->packet_buffer;
2455
                while(ppkt1){
2456
                    if(ppkt1->stream_index != i)
2457
                        continue;
2458
                    if(ppkt1->pkt->dts < 0)
2459
                        break;
2460
                    if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2461
                        break;
2462
                    ppkt1->pkt->dts -= delta;
2463
                    ppkt1= ppkt1->next;
2464
                }
2465
                if(ppkt1)
2466
                    continue;
2467
                st->cur_dts -= delta;
2468
            }
2469
        }
2470
    }
2471
#endif
2472 0cbff027 Kristian Amlie
2473 fd0368e7 Aurelien Jacobs
 find_stream_info_err:
2474
    for (i=0; i < ic->nb_streams; i++)
2475
        av_freep(&ic->streams[i]->info);
2476 b9a281db Fabrice Bellard
    return ret;
2477 de6d9b64 Fabrice Bellard
}
2478
2479 9128ae08 Nicolas George
static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
2480
{
2481
    int i, j;
2482
2483
    for (i = 0; i < ic->nb_programs; i++)
2484
        for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2485
            if (ic->programs[i]->stream_index[j] == s)
2486
                return ic->programs[i];
2487
    return NULL;
2488
}
2489
2490
int av_find_best_stream(AVFormatContext *ic,
2491
                        enum AVMediaType type,
2492
                        int wanted_stream_nb,
2493
                        int related_stream,
2494
                        AVCodec **decoder_ret,
2495
                        int flags)
2496
{
2497
    int i, nb_streams = ic->nb_streams, stream_number = 0;
2498
    int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2499
    unsigned *program = NULL;
2500
    AVCodec *decoder = NULL, *best_decoder = NULL;
2501
2502
    if (related_stream >= 0 && wanted_stream_nb < 0) {
2503
        AVProgram *p = find_program_from_stream(ic, related_stream);
2504
        if (p) {
2505
            program = p->stream_index;
2506
            nb_streams = p->nb_stream_indexes;
2507
        }
2508
    }
2509
    for (i = 0; i < nb_streams; i++) {
2510
        AVStream *st = ic->streams[program ? program[i] : i];
2511
        AVCodecContext *avctx = st->codec;
2512
        if (avctx->codec_type != type)
2513
            continue;
2514
        if (wanted_stream_nb >= 0 && stream_number++ != wanted_stream_nb)
2515
            continue;
2516 52091491 Peter Ross
        if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
2517
            continue;
2518 9128ae08 Nicolas George
        if (decoder_ret) {
2519
            decoder = avcodec_find_decoder(ic->streams[i]->codec->codec_id);
2520
            if (!decoder) {
2521
                if (ret < 0)
2522
                    ret = AVERROR_DECODER_NOT_FOUND;
2523
                continue;
2524
            }
2525
        }
2526
        if (best_count >= st->codec_info_nb_frames)
2527
            continue;
2528
        best_count = st->codec_info_nb_frames;
2529 22ec6b73 Balint Marton
        ret = program ? program[i] : i;
2530 9128ae08 Nicolas George
        best_decoder = decoder;
2531
        if (program && i == nb_streams - 1 && ret < 0) {
2532
            program = NULL;
2533
            nb_streams = ic->nb_streams;
2534
            i = 0; /* no related stream found, try again with everything */
2535
        }
2536
    }
2537
    if (decoder_ret)
2538
        *decoder_ret = best_decoder;
2539
    return ret;
2540
}
2541
2542 fb2758c8 Fabrice Bellard
/*******************************************************/
2543
2544
int av_read_play(AVFormatContext *s)
2545
{
2546 fa13095a Björn Axelsson
    if (s->iformat->read_play)
2547
        return s->iformat->read_play(s);
2548 fd2982a0 Aurelien Jacobs
    if (s->pb)
2549 ff1ec0c3 Anton Khirnov
        return avio_pause(s->pb, 0);
2550 fa13095a Björn Axelsson
    return AVERROR(ENOSYS);
2551 fb2758c8 Fabrice Bellard
}
2552
2553
int av_read_pause(AVFormatContext *s)
2554
{
2555 fa13095a Björn Axelsson
    if (s->iformat->read_pause)
2556
        return s->iformat->read_pause(s);
2557 fd2982a0 Aurelien Jacobs
    if (s->pb)
2558 ff1ec0c3 Anton Khirnov
        return avio_pause(s->pb, 1);
2559 fa13095a Björn Axelsson
    return AVERROR(ENOSYS);
2560 fb2758c8 Fabrice Bellard
}
2561
2562 2506fd54 Reimar Döffinger
void av_close_input_stream(AVFormatContext *s)
2563 de6d9b64 Fabrice Bellard
{
2564 81bd4119 Stefano Sabatini
    flush_packet_queue(s);
2565 b9a281db Fabrice Bellard
    if (s->iformat->read_close)
2566
        s->iformat->read_close(s);
2567 f124b087 Martin Storsjö
    avformat_free_context(s);
2568
}
2569
2570
void avformat_free_context(AVFormatContext *s)
2571
{
2572
    int i;
2573
    AVStream *st;
2574
2575 de6d9b64 Fabrice Bellard
    for(i=0;i<s->nb_streams;i++) {
2576 da24c5e3 Fabrice Bellard
        /* free all data in a stream component */
2577
        st = s->streams[i];
2578 fb2758c8 Fabrice Bellard
        if (st->parser) {
2579
            av_parser_close(st->parser);
2580 3a41c2f7 Michael Niedermayer
            av_free_packet(&st->cur_pkt);
2581 de6d9b64 Fabrice Bellard
        }
2582 094d9df7 Aurelien Jacobs
        av_metadata_free(&st->metadata);
2583 fb2758c8 Fabrice Bellard
        av_free(st->index_entries);
2584 a5e9102b Måns Rullgård
        av_free(st->codec->extradata);
2585 cb2c971d Aurelien Jacobs
        av_free(st->codec->subtitle_header);
2586 01f4895c Michael Niedermayer
        av_free(st->codec);
2587 ade8d8b9 Baptiste Coudurier
        av_free(st->priv_data);
2588 fd0368e7 Aurelien Jacobs
        av_free(st->info);
2589 fb2758c8 Fabrice Bellard
        av_free(st);
2590 de6d9b64 Fabrice Bellard
    }
2591 15afa396 Nico Sabbi
    for(i=s->nb_programs-1; i>=0; i--) {
2592 094d9df7 Aurelien Jacobs
        av_metadata_free(&s->programs[i]->metadata);
2593 526efa10 Nico Sabbi
        av_freep(&s->programs[i]->stream_index);
2594 15afa396 Nico Sabbi
        av_freep(&s->programs[i]);
2595
    }
2596 ceedda75 Michael Niedermayer
    av_freep(&s->programs);
2597 a8dbe951 Philip Gladstone
    av_freep(&s->priv_data);
2598 7c8202cc Michael Niedermayer
    while(s->nb_chapters--) {
2599 094d9df7 Aurelien Jacobs
        av_metadata_free(&s->chapters[s->nb_chapters]->metadata);
2600 7c8202cc Michael Niedermayer
        av_free(s->chapters[s->nb_chapters]);
2601 79d7836a Anton Khirnov
    }
2602
    av_freep(&s->chapters);
2603 094d9df7 Aurelien Jacobs
    av_metadata_free(&s->metadata);
2604 668338c5 Måns Rullgård
    av_freep(&s->key);
2605 1ea4f593 Fabrice Bellard
    av_free(s);
2606 de6d9b64 Fabrice Bellard
}
2607
2608 2506fd54 Reimar Döffinger
void av_close_input_file(AVFormatContext *s)
2609
{
2610 ae628ec1 Anton Khirnov
    AVIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
2611 2506fd54 Reimar Döffinger
    av_close_input_stream(s);
2612
    if (pb)
2613 22a3212e Anton Khirnov
        avio_close(pb);
2614 2506fd54 Reimar Döffinger
}
2615
2616 b9a281db Fabrice Bellard
AVStream *av_new_stream(AVFormatContext *s, int id)
2617
{
2618
    AVStream *st;
2619 504ee036 Michael Niedermayer
    int i;
2620 38aab35f Aurelien Jacobs
    AVStream **streams;
2621 b9a281db Fabrice Bellard
2622 38aab35f Aurelien Jacobs
    if (s->nb_streams >= INT_MAX/sizeof(*streams))
2623
        return NULL;
2624
    streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
2625
    if (!streams)
2626
        return NULL;
2627
    s->streams = streams;
2628 b9a281db Fabrice Bellard
2629
    st = av_mallocz(sizeof(AVStream));
2630
    if (!st)
2631
        return NULL;
2632 fd0368e7 Aurelien Jacobs
    if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2633
        av_free(st);
2634
        return NULL;
2635
    }
2636 115329f1 Diego Biurrun
2637 01f4895c Michael Niedermayer
    st->codec= avcodec_alloc_context();
2638 48091512 Fabrice Bellard
    if (s->iformat) {
2639
        /* no default bitrate if decoding */
2640 01f4895c Michael Niedermayer
        st->codec->bit_rate = 0;
2641 48091512 Fabrice Bellard
    }
2642 b9a281db Fabrice Bellard
    st->index = s->nb_streams;
2643
    st->id = id;
2644 12f996ed Fabrice Bellard
    st->start_time = AV_NOPTS_VALUE;
2645
    st->duration = AV_NOPTS_VALUE;
2646 6d77d9ac Michael Niedermayer
        /* we set the current DTS to 0 so that formats without any timestamps
2647
           but durations get some timestamps, formats with some unknown
2648
           timestamps have their first few packets buffered and the
2649
           timestamps corrected before they are returned to the user */
2650
    st->cur_dts = 0;
2651 82583548 Michael Niedermayer
    st->first_dts = AV_NOPTS_VALUE;
2652 86cb7e33 Baptiste Coudurier
    st->probe_packets = MAX_PROBE_PACKETS;
2653 9ee91c2f Michael Niedermayer
2654 a85736f2 Diego Biurrun
    /* default pts setting is MPEG-like */
2655 9ee91c2f Michael Niedermayer
    av_set_pts_info(st, 33, 1, 90000);
2656 635fbcb1 Michael Niedermayer
    st->last_IP_pts = AV_NOPTS_VALUE;
2657 504ee036 Michael Niedermayer
    for(i=0; i<MAX_REORDER_DELAY+1; i++)
2658
        st->pts_buffer[i]= AV_NOPTS_VALUE;
2659 27ca0a79 Ivan Schreter
    st->reference_dts = AV_NOPTS_VALUE;
2660 9ee91c2f Michael Niedermayer
2661 c30a4489 Aurelien Jacobs
    st->sample_aspect_ratio = (AVRational){0,1};
2662
2663 b9a281db Fabrice Bellard
    s->streams[s->nb_streams++] = st;
2664
    return st;
2665
}
2666
2667 15afa396 Nico Sabbi
AVProgram *av_new_program(AVFormatContext *ac, int id)
2668
{
2669
    AVProgram *program=NULL;
2670
    int i;
2671
2672
#ifdef DEBUG_SI
2673
    av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id);
2674
#endif
2675
2676
    for(i=0; i<ac->nb_programs; i++)
2677
        if(ac->programs[i]->id == id)
2678
            program = ac->programs[i];
2679
2680
    if(!program){
2681
        program = av_mallocz(sizeof(AVProgram));
2682
        if (!program)
2683
            return NULL;
2684
        dynarray_add(&ac->programs, &ac->nb_programs, program);
2685
        program->discard = AVDISCARD_NONE;
2686
    }
2687
    program->id = id;
2688
2689
    return program;
2690
}
2691
2692 abd2256d Michael Niedermayer
AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2693 79d7836a Anton Khirnov
{
2694 7a2a3e8e Michael Niedermayer
    AVChapter *chapter = NULL;
2695
    int i;
2696
2697 7c8202cc Michael Niedermayer
    for(i=0; i<s->nb_chapters; i++)
2698 7a2a3e8e Michael Niedermayer
        if(s->chapters[i]->id == id)
2699
            chapter = s->chapters[i];
2700