Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ d7fb5a18

History | View | Annotate | Download (99 KB)

1 de6d9b64 Fabrice Bellard
/*
2 a85736f2 Diego Biurrun
 * various utility functions for use within FFmpeg
3 19720f15 Fabrice Bellard
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4 de6d9b64 Fabrice Bellard
 *
5 b78e7197 Diego Biurrun
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg 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 b78e7197 Diego Biurrun
 * FFmpeg 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 b78e7197 Diego Biurrun
 * License along with FFmpeg; 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 8be1c656 Fabrice Bellard
#include "avformat.h"
22 f1c80e35 Ronald S. Bultje
#include "internal.h"
23 245976da Diego Biurrun
#include "libavcodec/opt.h"
24
#include "libavutil/avstring.h"
25 45da8124 Aurelien Jacobs
#include "riff.h"
26 82e4ac2c Ramiro Polla
#include <sys/time.h>
27
#include <time.h>
28 ea452b54 Aurelien Jacobs
#include <strings.h>
29 c5510dd6 Philip Gladstone
30 b754978a Michael Niedermayer
#undef NDEBUG
31
#include <assert.h>
32
33 e36bdf8b Daniel Kristjansson
/**
34
 * @file libavformat/utils.c
35 a85736f2 Diego Biurrun
 * various utility functions for use within FFmpeg
36 e36bdf8b Daniel Kristjansson
 */
37
38 c97429e2 Stefano Sabatini
unsigned avformat_version(void)
39
{
40
    return LIBAVFORMAT_VERSION_INT;
41
}
42
43 8163c870 Stefano Sabatini
/* fraction handling */
44
45
/**
46
 * f = val + (num / den) + 0.5.
47
 *
48
 * 'num' is normalized so that it is such as 0 <= num < den.
49
 *
50
 * @param f fractional number
51
 * @param val integer value
52
 * @param num must be >= 0
53
 * @param den must be >= 1
54
 */
55
static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
56
{
57
    num += (den >> 1);
58
    if (num >= den) {
59
        val += num / den;
60
        num = num % den;
61
    }
62
    f->val = val;
63
    f->num = num;
64
    f->den = den;
65
}
66
67
/**
68
 * Fractional addition to f: f = f + (incr / f->den).
69
 *
70
 * @param f fractional number
71
 * @param incr increment, can be positive or negative
72
 */
73
static void av_frac_add(AVFrac *f, int64_t incr)
74
{
75
    int64_t num, den;
76
77
    num = f->num + incr;
78
    den = f->den;
79
    if (num < 0) {
80
        f->val += num / den;
81
        num = num % den;
82
        if (num < 0) {
83
            num += den;
84
            f->val--;
85
        }
86
    } else if (num >= den) {
87
        f->val += num / den;
88
        num = num % den;
89
    }
90
    f->num = num;
91
}
92 f3a30e3a Luca Barbato
93 a85736f2 Diego Biurrun
/** head of registered input format linked list */
94 8b69867f Michael Niedermayer
AVInputFormat *first_iformat = NULL;
95 a85736f2 Diego Biurrun
/** head of registered output format linked list */
96 8b69867f Michael Niedermayer
AVOutputFormat *first_oformat = NULL;
97 de6d9b64 Fabrice Bellard
98 84be6e72 Michael Niedermayer
AVInputFormat  *av_iformat_next(AVInputFormat  *f)
99
{
100
    if(f) return f->next;
101
    else  return first_iformat;
102
}
103
104
AVOutputFormat *av_oformat_next(AVOutputFormat *f)
105
{
106
    if(f) return f->next;
107
    else  return first_oformat;
108
}
109
110 b9a281db Fabrice Bellard
void av_register_input_format(AVInputFormat *format)
111 de6d9b64 Fabrice Bellard
{
112 b9a281db Fabrice Bellard
    AVInputFormat **p;
113
    p = &first_iformat;
114
    while (*p != NULL) p = &(*p)->next;
115
    *p = format;
116
    format->next = NULL;
117
}
118
119
void av_register_output_format(AVOutputFormat *format)
120
{
121
    AVOutputFormat **p;
122
    p = &first_oformat;
123 de6d9b64 Fabrice Bellard
    while (*p != NULL) p = &(*p)->next;
124
    *p = format;
125
    format->next = NULL;
126
}
127
128 5b25dfa7 Fabrice Bellard
int match_ext(const char *filename, const char *extensions)
129 de6d9b64 Fabrice Bellard
{
130
    const char *ext, *p;
131
    char ext1[32], *q;
132
133 293ed23f Michael Niedermayer
    if(!filename)
134
        return 0;
135 115329f1 Diego Biurrun
136 de6d9b64 Fabrice Bellard
    ext = strrchr(filename, '.');
137
    if (ext) {
138
        ext++;
139
        p = extensions;
140
        for(;;) {
141
            q = ext1;
142 115329f1 Diego Biurrun
            while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
143 de6d9b64 Fabrice Bellard
                *q++ = *p++;
144
            *q = '\0';
145 115329f1 Diego Biurrun
            if (!strcasecmp(ext1, ext))
146 de6d9b64 Fabrice Bellard
                return 1;
147 115329f1 Diego Biurrun
            if (*p == '\0')
148 de6d9b64 Fabrice Bellard
                break;
149
            p++;
150
        }
151
    }
152
    return 0;
153
}
154
155 115329f1 Diego Biurrun
AVOutputFormat *guess_format(const char *short_name, const char *filename,
156 b9a281db Fabrice Bellard
                             const char *mime_type)
157 de6d9b64 Fabrice Bellard
{
158 b9a281db Fabrice Bellard
    AVOutputFormat *fmt, *fmt_found;
159 de6d9b64 Fabrice Bellard
    int score_max, score;
160
161 87a0a681 Fabrice Bellard
    /* specific test for image sequences */
162 ff70e601 Måns Rullgård
#ifdef CONFIG_IMAGE2_MUXER
163 115329f1 Diego Biurrun
    if (!short_name && filename &&
164 5c07cf53 Michel Bardiaux
        av_filename_number_test(filename) &&
165 5b6d5596 Michael Niedermayer
        av_guess_image2_codec(filename) != CODEC_ID_NONE) {
166
        return guess_format("image2", NULL, NULL);
167
    }
168 ff70e601 Måns Rullgård
#endif
169 a85736f2 Diego Biurrun
    /* Find the proper file type. */
170 de6d9b64 Fabrice Bellard
    fmt_found = NULL;
171
    score_max = 0;
172 b9a281db Fabrice Bellard
    fmt = first_oformat;
173 de6d9b64 Fabrice Bellard
    while (fmt != NULL) {
174
        score = 0;
175
        if (fmt->name && short_name && !strcmp(fmt->name, short_name))
176
            score += 100;
177
        if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
178
            score += 10;
179 115329f1 Diego Biurrun
        if (filename && fmt->extensions &&
180 de6d9b64 Fabrice Bellard
            match_ext(filename, fmt->extensions)) {
181
            score += 5;
182
        }
183
        if (score > score_max) {
184
            score_max = score;
185
            fmt_found = fmt;
186
        }
187
        fmt = fmt->next;
188
    }
189
    return fmt_found;
190 115329f1 Diego Biurrun
}
191 de6d9b64 Fabrice Bellard
192 115329f1 Diego Biurrun
AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
193 c5510dd6 Philip Gladstone
                             const char *mime_type)
194
{
195
    AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
196
197
    if (fmt) {
198
        AVOutputFormat *stream_fmt;
199
        char stream_format_name[64];
200
201
        snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
202
        stream_fmt = guess_format(stream_format_name, NULL, NULL);
203
204
        if (stream_fmt)
205
            fmt = stream_fmt;
206
    }
207
208
    return fmt;
209
}
210
211 115329f1 Diego Biurrun
enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
212 5b6d5596 Michael Niedermayer
                            const char *filename, const char *mime_type, enum CodecType type){
213
    if(type == CODEC_TYPE_VIDEO){
214
        enum CodecID codec_id= CODEC_ID_NONE;
215
216 ff70e601 Måns Rullgård
#ifdef CONFIG_IMAGE2_MUXER
217 ae214ac3 Michael Niedermayer
        if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
218 5b6d5596 Michael Niedermayer
            codec_id= av_guess_image2_codec(filename);
219
        }
220 ff70e601 Måns Rullgård
#endif
221 5b6d5596 Michael Niedermayer
        if(codec_id == CODEC_ID_NONE)
222
            codec_id= fmt->video_codec;
223
        return codec_id;
224
    }else if(type == CODEC_TYPE_AUDIO)
225
        return fmt->audio_codec;
226
    else
227
        return CODEC_ID_NONE;
228
}
229
230 b9a281db Fabrice Bellard
AVInputFormat *av_find_input_format(const char *short_name)
231
{
232
    AVInputFormat *fmt;
233
    for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
234
        if (!strcmp(fmt->name, short_name))
235
            return fmt;
236
    }
237
    return NULL;
238
}
239
240 de6d9b64 Fabrice Bellard
/* memory handling */
241
242 90ad92b3 Michael Niedermayer
void av_destruct_packet(AVPacket *pkt)
243 6fa5a56c Fabrice Bellard
{
244
    av_free(pkt->data);
245
    pkt->data = NULL; pkt->size = 0;
246
}
247
248 659596f0 Ramiro Polla
void av_init_packet(AVPacket *pkt)
249
{
250
    pkt->pts   = AV_NOPTS_VALUE;
251
    pkt->dts   = AV_NOPTS_VALUE;
252
    pkt->pos   = -1;
253
    pkt->duration = 0;
254 a2636c0f Michael Niedermayer
    pkt->convergence_duration = 0;
255 659596f0 Ramiro Polla
    pkt->flags = 0;
256
    pkt->stream_index = 0;
257
    pkt->destruct= av_destruct_packet_nofree;
258
}
259
260 de6d9b64 Fabrice Bellard
int av_new_packet(AVPacket *pkt, int size)
261
{
262 55bdd34d Baptiste Coudurier
    uint8_t *data;
263 568e18b1 Michael Niedermayer
    if((unsigned)size > (unsigned)size + FF_INPUT_BUFFER_PADDING_SIZE)
264 769e10f0 Panagiotis Issaris
        return AVERROR(ENOMEM);
265 568e18b1 Michael Niedermayer
    data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
266 6fa5a56c Fabrice Bellard
    if (!data)
267 769e10f0 Panagiotis Issaris
        return AVERROR(ENOMEM);
268 6fa5a56c Fabrice Bellard
    memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
269 8cd5be98 Michael Niedermayer
270 6fa5a56c Fabrice Bellard
    av_init_packet(pkt);
271 115329f1 Diego Biurrun
    pkt->data = data;
272 6fa5a56c Fabrice Bellard
    pkt->size = size;
273
    pkt->destruct = av_destruct_packet;
274 de6d9b64 Fabrice Bellard
    return 0;
275
}
276
277 2692067a Michael Niedermayer
int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
278
{
279
    int ret= av_new_packet(pkt, size);
280
281
    if(ret<0)
282
        return ret;
283
284
    pkt->pos= url_ftell(s);
285
286
    ret= get_buffer(s, pkt->data, size);
287
    if(ret<=0)
288
        av_free_packet(pkt);
289
    else
290
        pkt->size= ret;
291
292
    return ret;
293
}
294
295 fb2758c8 Fabrice Bellard
int av_dup_packet(AVPacket *pkt)
296
{
297
    if (pkt->destruct != av_destruct_packet) {
298
        uint8_t *data;
299 a85736f2 Diego Biurrun
        /* We duplicate the packet and don't forget to add the padding again. */
300 568e18b1 Michael Niedermayer
        if((unsigned)pkt->size > (unsigned)pkt->size + FF_INPUT_BUFFER_PADDING_SIZE)
301 769e10f0 Panagiotis Issaris
            return AVERROR(ENOMEM);
302 8a56ac7b Fabrice Bellard
        data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
303 fb2758c8 Fabrice Bellard
        if (!data) {
304 769e10f0 Panagiotis Issaris
            return AVERROR(ENOMEM);
305 fb2758c8 Fabrice Bellard
        }
306
        memcpy(data, pkt->data, pkt->size);
307 8a56ac7b Fabrice Bellard
        memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
308 fb2758c8 Fabrice Bellard
        pkt->data = data;
309
        pkt->destruct = av_destruct_packet;
310
    }
311
    return 0;
312
}
313
314 5c07cf53 Michel Bardiaux
int av_filename_number_test(const char *filename)
315 b9a281db Fabrice Bellard
{
316
    char buf[1024];
317 5c07cf53 Michel Bardiaux
    return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
318 b9a281db Fabrice Bellard
}
319
320 79750486 Michael Niedermayer
static AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
321 b9a281db Fabrice Bellard
{
322
    AVInputFormat *fmt1, *fmt;
323 79750486 Michael Niedermayer
    int score;
324 b9a281db Fabrice Bellard
325
    fmt = NULL;
326
    for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
327 b8e705ec Reimar Döffinger
        if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
328 b9a281db Fabrice Bellard
            continue;
329
        score = 0;
330 a8dbe951 Philip Gladstone
        if (fmt1->read_probe) {
331
            score = fmt1->read_probe(pd);
332
        } else if (fmt1->extensions) {
333 b9a281db Fabrice Bellard
            if (match_ext(pd->filename, fmt1->extensions)) {
334
                score = 50;
335
            }
336 115329f1 Diego Biurrun
        }
337 79750486 Michael Niedermayer
        if (score > *score_max) {
338
            *score_max = score;
339 b9a281db Fabrice Bellard
            fmt = fmt1;
340 4b3cca36 Michael Niedermayer
        }else if (score == *score_max)
341
            fmt = NULL;
342 b9a281db Fabrice Bellard
    }
343
    return fmt;
344
}
345
346 79750486 Michael Niedermayer
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
347
    int score=0;
348
    return av_probe_input_format2(pd, is_opened, &score);
349
}
350
351 64cd3108 Michael Niedermayer
static int set_codec_from_probe_data(AVStream *st, AVProbeData *pd, int score)
352
{
353
    AVInputFormat *fmt;
354
    fmt = av_probe_input_format2(pd, 1, &score);
355
356
    if (fmt) {
357 f1588ed5 Andreas Öman
        if (!strcmp(fmt->name, "mp3")) {
358 64cd3108 Michael Niedermayer
            st->codec->codec_id = CODEC_ID_MP3;
359 f1588ed5 Andreas Öman
            st->codec->codec_type = CODEC_TYPE_AUDIO;
360
        } else if (!strcmp(fmt->name, "ac3")) {
361 64cd3108 Michael Niedermayer
            st->codec->codec_id = CODEC_ID_AC3;
362 f1588ed5 Andreas Öman
            st->codec->codec_type = CODEC_TYPE_AUDIO;
363
        } else if (!strcmp(fmt->name, "mpegvideo")) {
364 312d24d5 Michael Niedermayer
            st->codec->codec_id = CODEC_ID_MPEG2VIDEO;
365 f1588ed5 Andreas Öman
            st->codec->codec_type = CODEC_TYPE_VIDEO;
366 74aa41ba Michael Niedermayer
        } else if (!strcmp(fmt->name, "m4v")) {
367
            st->codec->codec_id = CODEC_ID_MPEG4;
368
            st->codec->codec_type = CODEC_TYPE_VIDEO;
369 f1588ed5 Andreas Öman
        } else if (!strcmp(fmt->name, "h264")) {
370 312d24d5 Michael Niedermayer
            st->codec->codec_id = CODEC_ID_H264;
371 f1588ed5 Andreas Öman
            st->codec->codec_type = CODEC_TYPE_VIDEO;
372
        }
373 64cd3108 Michael Niedermayer
    }
374
    return !!fmt;
375
}
376
377 b9a281db Fabrice Bellard
/************************************************************/
378
/* input media file */
379 96baaa6a Fabrice Bellard
380 da24c5e3 Fabrice Bellard
/**
381 e36bdf8b Daniel Kristjansson
 * Open a media file from an IO stream. 'fmt' must be specified.
382 da24c5e3 Fabrice Bellard
 */
383 43465395 Michael Niedermayer
static const char* format_to_name(void* ptr)
384 bc874dae Michel Bardiaux
{
385 43465395 Michael Niedermayer
    AVFormatContext* fc = (AVFormatContext*) ptr;
386 bc874dae Michel Bardiaux
    if(fc->iformat) return fc->iformat->name;
387
    else if(fc->oformat) return fc->oformat->name;
388
    else return "NULL";
389
}
390
391 66acccf0 Panagiotis Issaris
#define OFFSET(x) offsetof(AVFormatContext,x)
392 755bfeab Diego Biurrun
#define DEFAULT 0 //should be NAN but it does not work as it is not a constant in glibc as required by ANSI/ISO C
393 4eb72c6b Nico Sabbi
//these names are too long to be readable
394
#define E AV_OPT_FLAG_ENCODING_PARAM
395
#define D AV_OPT_FLAG_DECODING_PARAM
396
397
static const AVOption options[]={
398 8c3dd5dc Panagiotis Issaris
{"probesize", NULL, OFFSET(probesize), FF_OPT_TYPE_INT, 32000, 32, INT_MAX, D}, /* 32000 from mpegts.c: 1.0 second at 24Mbit/s */
399 09a45576 Panagiotis Issaris
{"muxrate", "set mux rate", OFFSET(mux_rate), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
400 4ff8fcef Panagiotis Issaris
{"packetsize", "set packet size", OFFSET(packet_size), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
401 18de0b81 Baptiste Coudurier
{"fflags", NULL, OFFSET(flags), FF_OPT_TYPE_FLAGS, DEFAULT, INT_MIN, INT_MAX, D|E, "fflags"},
402 2c00106c Michael Niedermayer
{"ignidx", "ignore index", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_IGNIDX, INT_MIN, INT_MAX, D, "fflags"},
403
{"genpts", "generate pts", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_GENPTS, INT_MIN, INT_MAX, D, "fflags"},
404 8c3dd5dc Panagiotis Issaris
{"track", " set the track number", OFFSET(track), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
405 ec1b10f4 Panagiotis Issaris
{"year", "set the year", OFFSET(year), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, E},
406 e19fbbec Víctor Paesa
{"analyzeduration", "how many microseconds are analyzed to estimate duration", OFFSET(max_analyze_duration), FF_OPT_TYPE_INT, 3*AV_TIME_BASE, 0, INT_MAX, D},
407 841f39a7 Reimar Döffinger
{"cryptokey", "decryption key", OFFSET(key), FF_OPT_TYPE_BINARY, 0, 0, 0, D},
408 ac6f1330 Michael Niedermayer
{"indexmem", "max memory used for timestamp index (per stream)", OFFSET(max_index_size), FF_OPT_TYPE_INT, 1<<20, 0, INT_MAX, D},
409 ab8ab30c Ramiro Polla
{"rtbufsize", "max memory used for buffering real-time frames", OFFSET(max_picture_buffer), FF_OPT_TYPE_INT, 3041280, 0, INT_MAX, D}, /* defaults to 1s of 15fps 352x288 YUYV422 video */
410 45b2b05f Michael Niedermayer
{"fdebug", "print specific debug info", OFFSET(debug), FF_OPT_TYPE_FLAGS, DEFAULT, 0, INT_MAX, E|D, "fdebug"},
411
{"ts", NULL, 0, FF_OPT_TYPE_CONST, FF_FDEBUG_TS, INT_MIN, INT_MAX, E|D, "fdebug"},
412 4eb72c6b Nico Sabbi
{NULL},
413
};
414
415 5e89b50b Panagiotis Issaris
#undef E
416
#undef D
417
#undef DEFAULT
418
419 4eb72c6b Nico Sabbi
static const AVClass av_format_context_class = { "AVFormatContext", format_to_name, options };
420
421 702dfe01 Baptiste Coudurier
static void avformat_get_context_defaults(AVFormatContext *s)
422
{
423 4eb72c6b Nico Sabbi
    memset(s, 0, sizeof(AVFormatContext));
424 9e6c9470 Nico Sabbi
425 73a8ceaa Panagiotis Issaris
    s->av_class = &av_format_context_class;
426
427
    av_opt_set_defaults(s);
428 4eb72c6b Nico Sabbi
}
429 bc874dae Michel Bardiaux
430
AVFormatContext *av_alloc_format_context(void)
431
{
432
    AVFormatContext *ic;
433 5894991f Panagiotis Issaris
    ic = av_malloc(sizeof(AVFormatContext));
434 bc874dae Michel Bardiaux
    if (!ic) return ic;
435 4eb72c6b Nico Sabbi
    avformat_get_context_defaults(ic);
436 43465395 Michael Niedermayer
    ic->av_class = &av_format_context_class;
437 bc874dae Michel Bardiaux
    return ic;
438
}
439
440 115329f1 Diego Biurrun
int av_open_input_stream(AVFormatContext **ic_ptr,
441
                         ByteIOContext *pb, const char *filename,
442 da24c5e3 Fabrice Bellard
                         AVInputFormat *fmt, AVFormatParameters *ap)
443
{
444
    int err;
445
    AVFormatContext *ic;
446 c04c3282 Michael Niedermayer
    AVFormatParameters default_ap;
447
448
    if(!ap){
449
        ap=&default_ap;
450
        memset(ap, 0, sizeof(default_ap));
451
    }
452 da24c5e3 Fabrice Bellard
453 4eb72c6b Nico Sabbi
    if(!ap->prealloced_context)
454
        ic = av_alloc_format_context();
455
    else
456
        ic = *ic_ptr;
457 da24c5e3 Fabrice Bellard
    if (!ic) {
458 769e10f0 Panagiotis Issaris
        err = AVERROR(ENOMEM);
459 da24c5e3 Fabrice Bellard
        goto fail;
460
    }
461
    ic->iformat = fmt;
462 899681cd Björn Axelsson
    ic->pb = pb;
463 da24c5e3 Fabrice Bellard
    ic->duration = AV_NOPTS_VALUE;
464
    ic->start_time = AV_NOPTS_VALUE;
465 75e61b0e Måns Rullgård
    av_strlcpy(ic->filename, filename, sizeof(ic->filename));
466 da24c5e3 Fabrice Bellard
467
    /* allocate private data */
468
    if (fmt->priv_data_size > 0) {
469
        ic->priv_data = av_mallocz(fmt->priv_data_size);
470
        if (!ic->priv_data) {
471 769e10f0 Panagiotis Issaris
            err = AVERROR(ENOMEM);
472 da24c5e3 Fabrice Bellard
            goto fail;
473
        }
474
    } else {
475
        ic->priv_data = NULL;
476
    }
477
478 e145ce20 Ronald S. Bultje
    if (ic->iformat->read_header) {
479 1e2802c5 Ronald S. Bultje
        err = ic->iformat->read_header(ic, ap);
480
        if (err < 0)
481
            goto fail;
482 e145ce20 Ronald S. Bultje
    }
483 fb2758c8 Fabrice Bellard
484 faf7cbf1 Michael Niedermayer
    if (pb && !ic->data_offset)
485 899681cd Björn Axelsson
        ic->data_offset = url_ftell(ic->pb);
486 fb2758c8 Fabrice Bellard
487 da24c5e3 Fabrice Bellard
    *ic_ptr = ic;
488
    return 0;
489
 fail:
490
    if (ic) {
491 ccafd472 Baptiste Coudurier
        int i;
492 da24c5e3 Fabrice Bellard
        av_freep(&ic->priv_data);
493 ccafd472 Baptiste Coudurier
        for(i=0;i<ic->nb_streams;i++) {
494
            AVStream *st = ic->streams[i];
495
            if (st) {
496
                av_free(st->priv_data);
497
                av_free(st->codec->extradata);
498
            }
499
            av_free(st);
500
        }
501 da24c5e3 Fabrice Bellard
    }
502
    av_free(ic);
503
    *ic_ptr = NULL;
504
    return err;
505
}
506
507 a85736f2 Diego Biurrun
/** size of probe buffer, for guessing file type from file contents */
508 a877eedc Michael Niedermayer
#define PROBE_BUF_MIN 2048
509 329b1e75 Michael Niedermayer
#define PROBE_BUF_MAX (1<<20)
510 b9a281db Fabrice Bellard
511 115329f1 Diego Biurrun
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
512 b9a281db Fabrice Bellard
                       AVInputFormat *fmt,
513
                       int buf_size,
514
                       AVFormatParameters *ap)
515 de6d9b64 Fabrice Bellard
{
516 17acc63a Reimar Döffinger
    int err, probe_size;
517 b9a281db Fabrice Bellard
    AVProbeData probe_data, *pd = &probe_data;
518 17acc63a Reimar Döffinger
    ByteIOContext *pb = NULL;
519 115329f1 Diego Biurrun
520 da24c5e3 Fabrice Bellard
    pd->filename = "";
521
    if (filename)
522
        pd->filename = filename;
523 a877eedc Michael Niedermayer
    pd->buf = NULL;
524 b9a281db Fabrice Bellard
    pd->buf_size = 0;
525
526
    if (!fmt) {
527 a85736f2 Diego Biurrun
        /* guess format if no file can be opened */
528 a25e098d Fabrice Bellard
        fmt = av_probe_input_format(pd, 0);
529 de6d9b64 Fabrice Bellard
    }
530
531 a85736f2 Diego Biurrun
    /* Do not open file if the format does not need it. XXX: specific
532 b6892136 Fabrice Bellard
       hack needed to handle RTSP/TCP */
533 17acc63a Reimar Döffinger
    if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
534 87a0a681 Fabrice Bellard
        /* if no file needed do not try to open one */
535 899681cd Björn Axelsson
        if ((err=url_fopen(&pb, filename, URL_RDONLY)) < 0) {
536 96baaa6a Fabrice Bellard
            goto fail;
537 b9a281db Fabrice Bellard
        }
538 96baaa6a Fabrice Bellard
        if (buf_size > 0) {
539 da24c5e3 Fabrice Bellard
            url_setbufsize(pb, buf_size);
540 96baaa6a Fabrice Bellard
        }
541 a877eedc Michael Niedermayer
542
        for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
543 79750486 Michael Niedermayer
            int score= probe_size < PROBE_BUF_MAX ? AVPROBE_SCORE_MAX/4 : 0;
544 5b25dfa7 Fabrice Bellard
            /* read probe data */
545 87e87886 Michael Niedermayer
            pd->buf= av_realloc(pd->buf, probe_size + AVPROBE_PADDING_SIZE);
546 a877eedc Michael Niedermayer
            pd->buf_size = get_buffer(pb, pd->buf, probe_size);
547 9be51815 Wolfram Gloger
            memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
548 497244a8 Baptiste Coudurier
            if (url_fseek(pb, 0, SEEK_SET) < 0) {
549 53e2f9ca Michael Niedermayer
                url_fclose(pb);
550 899681cd Björn Axelsson
                if (url_fopen(&pb, filename, URL_RDONLY) < 0) {
551 17acc63a Reimar Döffinger
                    pb = NULL;
552 6f3e0b21 Panagiotis Issaris
                    err = AVERROR(EIO);
553 53e2f9ca Michael Niedermayer
                    goto fail;
554
                }
555
            }
556 a877eedc Michael Niedermayer
            /* guess file format */
557 79750486 Michael Niedermayer
            fmt = av_probe_input_format2(pd, 1, &score);
558 5b25dfa7 Fabrice Bellard
        }
559 a877eedc Michael Niedermayer
        av_freep(&pd->buf);
560 b9a281db Fabrice Bellard
    }
561
562
    /* if still no format found, error */
563
    if (!fmt) {
564
        err = AVERROR_NOFMT;
565 da24c5e3 Fabrice Bellard
        goto fail;
566 de6d9b64 Fabrice Bellard
    }
567 115329f1 Diego Biurrun
568 a85736f2 Diego Biurrun
    /* check filename in case an image number is expected */
569 da24c5e3 Fabrice Bellard
    if (fmt->flags & AVFMT_NEEDNUMBER) {
570 5c07cf53 Michel Bardiaux
        if (!av_filename_number_test(filename)) {
571 87a0a681 Fabrice Bellard
            err = AVERROR_NUMEXPECTED;
572 da24c5e3 Fabrice Bellard
            goto fail;
573 87a0a681 Fabrice Bellard
        }
574
    }
575 da24c5e3 Fabrice Bellard
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
576
    if (err)
577
        goto fail;
578 b9a281db Fabrice Bellard
    return 0;
579 de6d9b64 Fabrice Bellard
 fail:
580 a877eedc Michael Niedermayer
    av_freep(&pd->buf);
581 17acc63a Reimar Döffinger
    if (pb)
582 da24c5e3 Fabrice Bellard
        url_fclose(pb);
583 b9a281db Fabrice Bellard
    *ic_ptr = NULL;
584
    return err;
585 115329f1 Diego Biurrun
586 de6d9b64 Fabrice Bellard
}
587
588 da24c5e3 Fabrice Bellard
/*******************************************************/
589
590 5c5b1731 Måns Rullgård
static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
591
                               AVPacketList **plast_pktl){
592
    AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
593 9d3b9f2c Michael Niedermayer
    if (!pktl)
594
        return NULL;
595
596 5c5b1731 Måns Rullgård
    if (*packet_buffer)
597
        (*plast_pktl)->next = pktl;
598
    else
599
        *packet_buffer = pktl;
600
601 9d3b9f2c Michael Niedermayer
    /* add the packet in the buffered packet list */
602
    *plast_pktl = pktl;
603
    pktl->pkt= *pkt;
604
    return &pktl->pkt;
605
}
606
607 de6d9b64 Fabrice Bellard
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
608
{
609 62600469 Michael Niedermayer
    int ret;
610
    AVStream *st;
611 0bef08e5 Michael Niedermayer
612
    for(;;){
613
        AVPacketList *pktl = s->raw_packet_buffer;
614
615
        if (pktl) {
616
            *pkt = pktl->pkt;
617
            if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE){
618
                s->raw_packet_buffer = pktl->next;
619
                av_free(pktl);
620
                return 0;
621
            }
622
        }
623
624 55823964 Michael Niedermayer
        av_init_packet(pkt);
625
        ret= s->iformat->read_packet(s, pkt);
626
        if (ret < 0)
627
            return ret;
628
        st= s->streams[pkt->stream_index];
629 62600469 Michael Niedermayer
630 55823964 Michael Niedermayer
        switch(st->codec->codec_type){
631
        case CODEC_TYPE_VIDEO:
632
            if(s->video_codec_id)   st->codec->codec_id= s->video_codec_id;
633
            break;
634
        case CODEC_TYPE_AUDIO:
635
            if(s->audio_codec_id)   st->codec->codec_id= s->audio_codec_id;
636
            break;
637
        case CODEC_TYPE_SUBTITLE:
638
            if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
639
            break;
640
        }
641 62600469 Michael Niedermayer
642 744b4c02 Michael Niedermayer
        if(!pktl && st->codec->codec_id!=CODEC_ID_PROBE)
643
            return ret;
644
645 5c5b1731 Måns Rullgård
        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
646 744b4c02 Michael Niedermayer
647 0bef08e5 Michael Niedermayer
        if(st->codec->codec_id == CODEC_ID_PROBE){
648
            AVProbeData *pd = &st->probe_data;
649
650
            pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
651
            memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
652
            pd->buf_size += pkt->size;
653
            memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
654
655 942de2f4 Michael Niedermayer
            if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
656 25d3fb73 Michael Niedermayer
                set_codec_from_probe_data(st, pd, 1);
657
                if(st->codec->codec_id != CODEC_ID_PROBE){
658
                    pd->buf_size=0;
659
                    av_freep(&pd->buf);
660
                }
661 942de2f4 Michael Niedermayer
            }
662 0bef08e5 Michael Niedermayer
        }
663
    }
664 fb2758c8 Fabrice Bellard
}
665
666
/**********************************************************/
667
668 e36bdf8b Daniel Kristjansson
/**
669 a85736f2 Diego Biurrun
 * Get the number of samples of an audio frame. Return -1 on error.
670 e36bdf8b Daniel Kristjansson
 */
671 fb2758c8 Fabrice Bellard
static int get_audio_frame_size(AVCodecContext *enc, int size)
672
{
673
    int frame_size;
674
675 c924ca78 Michael Niedermayer
    if(enc->codec_id == CODEC_ID_VORBIS)
676
        return -1;
677
678 fb2758c8 Fabrice Bellard
    if (enc->frame_size <= 1) {
679 ac3e1834 Baptiste Coudurier
        int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
680
681
        if (bits_per_sample) {
682 fb2758c8 Fabrice Bellard
            if (enc->channels == 0)
683
                return -1;
684 f1b163e0 Aurelien Jacobs
            frame_size = (size << 3) / (bits_per_sample * enc->channels);
685 ac3e1834 Baptiste Coudurier
        } else {
686 fb2758c8 Fabrice Bellard
            /* used for example by ADPCM codecs */
687
            if (enc->bit_rate == 0)
688
                return -1;
689
            frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
690
        }
691
    } else {
692
        frame_size = enc->frame_size;
693
    }
694
    return frame_size;
695
}
696
697
698 e36bdf8b Daniel Kristjansson
/**
699 a85736f2 Diego Biurrun
 * Return the frame duration in seconds. Return 0 if not available.
700 e36bdf8b Daniel Kristjansson
 */
701 115329f1 Diego Biurrun
static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
702 fb2758c8 Fabrice Bellard
                                   AVCodecParserContext *pc, AVPacket *pkt)
703
{
704
    int frame_size;
705
706
    *pnum = 0;
707
    *pden = 0;
708 01f4895c Michael Niedermayer
    switch(st->codec->codec_type) {
709 fb2758c8 Fabrice Bellard
    case CODEC_TYPE_VIDEO:
710 1677155d Michael Niedermayer
        if(st->time_base.num*1000LL > st->time_base.den){
711 c0df9d75 Michael Niedermayer
            *pnum = st->time_base.num;
712
            *pden = st->time_base.den;
713 01f4895c Michael Niedermayer
        }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
714
            *pnum = st->codec->time_base.num;
715
            *pden = st->codec->time_base.den;
716 327c4076 Michael Niedermayer
            if (pc && pc->repeat_pict) {
717
                *pden *= 2;
718
                *pnum = (*pnum) * (2 + pc->repeat_pict);
719
            }
720 fb2758c8 Fabrice Bellard
        }
721
        break;
722
    case CODEC_TYPE_AUDIO:
723 01f4895c Michael Niedermayer
        frame_size = get_audio_frame_size(st->codec, pkt->size);
724 fb2758c8 Fabrice Bellard
        if (frame_size < 0)
725
            break;
726
        *pnum = frame_size;
727 01f4895c Michael Niedermayer
        *pden = st->codec->sample_rate;
728 fb2758c8 Fabrice Bellard
        break;
729
    default:
730
        break;
731
    }
732
}
733
734 5ba7c3d7 Michael Niedermayer
static int is_intra_only(AVCodecContext *enc){
735
    if(enc->codec_type == CODEC_TYPE_AUDIO){
736
        return 1;
737
    }else if(enc->codec_type == CODEC_TYPE_VIDEO){
738
        switch(enc->codec_id){
739
        case CODEC_ID_MJPEG:
740
        case CODEC_ID_MJPEGB:
741
        case CODEC_ID_LJPEG:
742
        case CODEC_ID_RAWVIDEO:
743
        case CODEC_ID_DVVIDEO:
744
        case CODEC_ID_HUFFYUV:
745 f37b9768 Loren Merritt
        case CODEC_ID_FFVHUFF:
746 5ba7c3d7 Michael Niedermayer
        case CODEC_ID_ASV1:
747
        case CODEC_ID_ASV2:
748
        case CODEC_ID_VCR1:
749 b774fdd7 Baptiste Coudurier
        case CODEC_ID_DNXHD:
750 5ba7c3d7 Michael Niedermayer
            return 1;
751
        default: break;
752
        }
753
    }
754
    return 0;
755
}
756
757 9fcbcca6 Neil Brown
static void update_initial_timestamps(AVFormatContext *s, int stream_index,
758
                                      int64_t dts, int64_t pts)
759
{
760 82583548 Michael Niedermayer
    AVStream *st= s->streams[stream_index];
761
    AVPacketList *pktl= s->packet_buffer;
762
763 7efeb73a Michael Niedermayer
    if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
764 82583548 Michael Niedermayer
        return;
765
766
    st->first_dts= dts - st->cur_dts;
767
    st->cur_dts= dts;
768
769
    for(; pktl; pktl= pktl->next){
770
        if(pktl->pkt.stream_index != stream_index)
771
            continue;
772
        //FIXME think more about this check
773
        if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
774
            pktl->pkt.pts += st->first_dts;
775
776
        if(pktl->pkt.dts != AV_NOPTS_VALUE)
777
            pktl->pkt.dts += st->first_dts;
778 48a59dfe Michael Niedermayer
779
        if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
780
            st->start_time= pktl->pkt.pts;
781 82583548 Michael Niedermayer
    }
782 9fcbcca6 Neil Brown
    if (st->start_time == AV_NOPTS_VALUE)
783
        st->start_time = pts;
784 82583548 Michael Niedermayer
}
785
786 83a9db42 Michael Niedermayer
static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
787
{
788
    AVPacketList *pktl= s->packet_buffer;
789 820ad60c Michael Niedermayer
    int64_t cur_dts= 0;
790
791
    if(st->first_dts != AV_NOPTS_VALUE){
792
        cur_dts= st->first_dts;
793
        for(; pktl; pktl= pktl->next){
794
            if(pktl->pkt.stream_index == pkt->stream_index){
795
                if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
796
                    break;
797
                cur_dts -= pkt->duration;
798
            }
799
        }
800
        pktl= s->packet_buffer;
801
        st->first_dts = cur_dts;
802
    }else if(st->cur_dts)
803
        return;
804 83a9db42 Michael Niedermayer
805
    for(; pktl; pktl= pktl->next){
806
        if(pktl->pkt.stream_index != pkt->stream_index)
807
            continue;
808 91acf9a8 Michael Niedermayer
        if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
809
           && !pktl->pkt.duration){
810 820ad60c Michael Niedermayer
            pktl->pkt.dts= cur_dts;
811 5853423c Michael Niedermayer
            if(!st->codec->has_b_frames)
812 820ad60c Michael Niedermayer
                pktl->pkt.pts= cur_dts;
813
            cur_dts += pkt->duration;
814 83a9db42 Michael Niedermayer
            pktl->pkt.duration= pkt->duration;
815
        }else
816
            break;
817
    }
818 820ad60c Michael Niedermayer
    if(st->first_dts == AV_NOPTS_VALUE)
819
        st->cur_dts= cur_dts;
820 83a9db42 Michael Niedermayer
}
821
822 115329f1 Diego Biurrun
static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
823 fb2758c8 Fabrice Bellard
                               AVCodecParserContext *pc, AVPacket *pkt)
824
{
825 d9e1efb7 Michael Niedermayer
    int num, den, presentation_delayed, delay, i;
826 a74008a4 Joakim Plate
    int64_t offset;
827 115329f1 Diego Biurrun
828 f781f748 Michael Niedermayer
    /* do we have a video B-frame ? */
829
    delay= st->codec->has_b_frames;
830
    presentation_delayed = 0;
831
    /* XXX: need has_b_frame, but cannot get it if the codec is
832
        not initialized */
833
    if (delay &&
834
        pc && pc->pict_type != FF_B_TYPE)
835
        presentation_delayed = 1;
836
837 10a7571b Michael Niedermayer
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
838
       /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
839
        pkt->dts -= 1LL<<st->pts_wrap_bits;
840
    }
841
842 9806f846 Michael Niedermayer
    // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
843
    // we take the conservative approach and discard both
844
    // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
845
    if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
846
        av_log(s, AV_LOG_ERROR, "invalid dts/pts combination\n");
847
        pkt->dts= pkt->pts= AV_NOPTS_VALUE;
848
    }
849
850 fb2758c8 Fabrice Bellard
    if (pkt->duration == 0) {
851 3c895fc0 Michael Niedermayer
        compute_frame_duration(&num, &den, st, pc, pkt);
852 fb2758c8 Fabrice Bellard
        if (den && num) {
853 77405fc8 Michael Niedermayer
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
854 83a9db42 Michael Niedermayer
855 820ad60c Michael Niedermayer
            if(pkt->duration != 0 && s->packet_buffer)
856 83a9db42 Michael Niedermayer
                update_initial_durations(s, st, pkt);
857 fb2758c8 Fabrice Bellard
        }
858
    }
859
860 a85736f2 Diego Biurrun
    /* correct timestamps with byte offset if demuxers only have timestamps
861
       on packet boundaries */
862 a74008a4 Joakim Plate
    if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
863
        /* this will estimate bitrate based on this frame's duration and size */
864
        offset = av_rescale(pc->offset, pkt->duration, pkt->size);
865
        if(pkt->pts != AV_NOPTS_VALUE)
866
            pkt->pts += offset;
867
        if(pkt->dts != AV_NOPTS_VALUE)
868
            pkt->dts += offset;
869
    }
870
871 755bfeab Diego Biurrun
    /* This may be redundant, but it should not hurt. */
872 7e4baa66 Michael Niedermayer
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
873
        presentation_delayed = 1;
874 115329f1 Diego Biurrun
875 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);
876 fb2758c8 Fabrice Bellard
    /* interpolate PTS and DTS if they are not present */
877 406a0fdc Michael Niedermayer
    if(delay==0 || (delay==1 && pc)){
878 7e4baa66 Michael Niedermayer
        if (presentation_delayed) {
879 a85736f2 Diego Biurrun
            /* DTS = decompression timestamp */
880
            /* PTS = presentation timestamp */
881 7e4baa66 Michael Niedermayer
            if (pkt->dts == AV_NOPTS_VALUE)
882 635fbcb1 Michael Niedermayer
                pkt->dts = st->last_IP_pts;
883 9fcbcca6 Neil Brown
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
884 7e4baa66 Michael Niedermayer
            if (pkt->dts == AV_NOPTS_VALUE)
885
                pkt->dts = st->cur_dts;
886
887
            /* this is tricky: the dts must be incremented by the duration
888 a85736f2 Diego Biurrun
            of the frame we are displaying, i.e. the last I- or P-frame */
889 635fbcb1 Michael Niedermayer
            if (st->last_IP_duration == 0)
890
                st->last_IP_duration = pkt->duration;
891 7efeb73a Michael Niedermayer
            if(pkt->dts != AV_NOPTS_VALUE)
892 cdb5af79 Michael Niedermayer
                st->cur_dts = pkt->dts + st->last_IP_duration;
893 635fbcb1 Michael Niedermayer
            st->last_IP_duration  = pkt->duration;
894
            st->last_IP_pts= pkt->pts;
895 7e4baa66 Michael Niedermayer
            /* cannot compute PTS if not present (we can compute it only
896 a85736f2 Diego Biurrun
            by knowing the future */
897 028d6f3e Michael Niedermayer
        } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
898 7e4baa66 Michael Niedermayer
            if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
899
                int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
900
                int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
901
                if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
902
                    pkt->pts += pkt->duration;
903
    //                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);
904
                }
905 90bb394d Michael Niedermayer
            }
906 115329f1 Diego Biurrun
907 7e4baa66 Michael Niedermayer
            /* presentation is not delayed : PTS and DTS are the same */
908
            if(pkt->pts == AV_NOPTS_VALUE)
909
                pkt->pts = pkt->dts;
910 9fcbcca6 Neil Brown
            update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
911 7e4baa66 Michael Niedermayer
            if(pkt->pts == AV_NOPTS_VALUE)
912
                pkt->pts = st->cur_dts;
913
            pkt->dts = pkt->pts;
914 7efeb73a Michael Niedermayer
            if(pkt->pts != AV_NOPTS_VALUE)
915 cdb5af79 Michael Niedermayer
                st->cur_dts = pkt->pts + pkt->duration;
916 7e4baa66 Michael Niedermayer
        }
917 fb2758c8 Fabrice Bellard
    }
918 d9e1efb7 Michael Niedermayer
919 cb5b96cd Baptiste Coudurier
    if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
920 d9e1efb7 Michael Niedermayer
        st->pts_buffer[0]= pkt->pts;
921
        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
922
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
923
        if(pkt->dts == AV_NOPTS_VALUE)
924
            pkt->dts= st->pts_buffer[0];
925 82583548 Michael Niedermayer
        if(delay>1){
926 9fcbcca6 Neil Brown
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
927 82583548 Michael Niedermayer
        }
928 d9e1efb7 Michael Niedermayer
        if(pkt->dts > st->cur_dts)
929
            st->cur_dts = pkt->dts;
930
    }
931
932
//    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);
933 115329f1 Diego Biurrun
934 fb2758c8 Fabrice Bellard
    /* update flags */
935 3a1d3588 Jeff Downs
    if(is_intra_only(st->codec))
936
        pkt->flags |= PKT_FLAG_KEY;
937
    else if (pc) {
938 fb2758c8 Fabrice Bellard
        pkt->flags = 0;
939 a85736f2 Diego Biurrun
        /* keyframe computation */
940 fb2758c8 Fabrice Bellard
            if (pc->pict_type == FF_I_TYPE)
941
                pkt->flags |= PKT_FLAG_KEY;
942
    }
943
}
944
945 63dd1377 Michael Niedermayer
void av_destruct_packet_nofree(AVPacket *pkt)
946 fb2758c8 Fabrice Bellard
{
947
    pkt->data = NULL; pkt->size = 0;
948
}
949
950
static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
951
{
952
    AVStream *st;
953 37353960 Fabrice Bellard
    int len, ret, i;
954 fb2758c8 Fabrice Bellard
955 b237eb80 Michael Niedermayer
    av_init_packet(pkt);
956
957 fb2758c8 Fabrice Bellard
    for(;;) {
958
        /* select current input stream component */
959
        st = s->cur_st;
960
        if (st) {
961 90ad92b3 Michael Niedermayer
            if (!st->need_parsing || !st->parser) {
962 fb2758c8 Fabrice Bellard
                /* no parsing needed: we just output the packet as is */
963
                /* raw data support */
964
                *pkt = s->cur_pkt;
965
                compute_pkt_fields(s, st, NULL, pkt);
966
                s->cur_st = NULL;
967 434cab9e Michael Niedermayer
                break;
968 f3356e9c Michael Niedermayer
            } else if (s->cur_len > 0 && st->discard < AVDISCARD_ALL) {
969 115329f1 Diego Biurrun
                len = av_parser_parse(st->parser, st->codec, &pkt->data, &pkt->size,
970 6ec87caa Fabrice Bellard
                                      s->cur_ptr, s->cur_len,
971
                                      s->cur_pkt.pts, s->cur_pkt.dts);
972
                s->cur_pkt.pts = AV_NOPTS_VALUE;
973
                s->cur_pkt.dts = AV_NOPTS_VALUE;
974 fb2758c8 Fabrice Bellard
                /* increment read pointer */
975
                s->cur_ptr += len;
976
                s->cur_len -= len;
977 115329f1 Diego Biurrun
978 fb2758c8 Fabrice Bellard
                /* return packet if any */
979
                if (pkt->size) {
980 37353960 Fabrice Bellard
                got_packet:
981 711737af Daniel Cardenas
                    pkt->pos = s->cur_pkt.pos;              // Isn't quite accurate but close.
982 fb2758c8 Fabrice Bellard
                    pkt->duration = 0;
983
                    pkt->stream_index = st->index;
984 6ec87caa Fabrice Bellard
                    pkt->pts = st->parser->pts;
985
                    pkt->dts = st->parser->dts;
986 fb2758c8 Fabrice Bellard
                    pkt->destruct = av_destruct_packet_nofree;
987
                    compute_pkt_fields(s, st, st->parser, pkt);
988 e9b78eeb Michael Niedermayer
989
                    if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & PKT_FLAG_KEY){
990 3dea63bd Paul Kelly
                        ff_reduce_index(s, st->index);
991 e9b78eeb Michael Niedermayer
                        av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
992
                                           0, 0, AVINDEX_KEYFRAME);
993
                    }
994
995 434cab9e Michael Niedermayer
                    break;
996 fb2758c8 Fabrice Bellard
                }
997
            } else {
998 bcbecff1 Fabrice Bellard
                /* free packet */
999 115329f1 Diego Biurrun
                av_free_packet(&s->cur_pkt);
1000 fb2758c8 Fabrice Bellard
                s->cur_st = NULL;
1001
            }
1002
        } else {
1003
            /* read next packet */
1004
            ret = av_read_packet(s, &s->cur_pkt);
1005 37353960 Fabrice Bellard
            if (ret < 0) {
1006 8fa36ae0 François Revol
                if (ret == AVERROR(EAGAIN))
1007 37353960 Fabrice Bellard
                    return ret;
1008
                /* return the last frames, if any */
1009
                for(i = 0; i < s->nb_streams; i++) {
1010
                    st = s->streams[i];
1011 90ad92b3 Michael Niedermayer
                    if (st->parser && st->need_parsing) {
1012 115329f1 Diego Biurrun
                        av_parser_parse(st->parser, st->codec,
1013
                                        &pkt->data, &pkt->size,
1014
                                        NULL, 0,
1015 6ec87caa Fabrice Bellard
                                        AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1016 37353960 Fabrice Bellard
                        if (pkt->size)
1017
                            goto got_packet;
1018
                    }
1019
                }
1020 a85736f2 Diego Biurrun
                /* no more packets: really terminate parsing */
1021 fb2758c8 Fabrice Bellard
                return ret;
1022 37353960 Fabrice Bellard
            }
1023 115329f1 Diego Biurrun
1024 b18a4ab2 Michael Niedermayer
            if(s->cur_pkt.pts != AV_NOPTS_VALUE &&
1025
               s->cur_pkt.dts != AV_NOPTS_VALUE &&
1026
               s->cur_pkt.pts < s->cur_pkt.dts){
1027
                av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1028
                    s->cur_pkt.stream_index,
1029
                    s->cur_pkt.pts,
1030
                    s->cur_pkt.dts,
1031
                    s->cur_pkt.size);
1032
//                av_free_packet(&s->cur_pkt);
1033
//                return -1;
1034
            }
1035
1036 9ee91c2f Michael Niedermayer
            st = s->streams[s->cur_pkt.stream_index];
1037 45b2b05f Michael Niedermayer
            if(s->debug & FF_FDEBUG_TS)
1038 3041a4a1 Michael Niedermayer
                av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d,  flags=%d\n",
1039 434cab9e Michael Niedermayer
                    s->cur_pkt.stream_index,
1040
                    s->cur_pkt.pts,
1041
                    s->cur_pkt.dts,
1042 3041a4a1 Michael Niedermayer
                    s->cur_pkt.size,
1043
                    s->cur_pkt.flags);
1044 fb2758c8 Fabrice Bellard
1045
            s->cur_st = st;
1046
            s->cur_ptr = s->cur_pkt.data;
1047
            s->cur_len = s->cur_pkt.size;
1048
            if (st->need_parsing && !st->parser) {
1049 01f4895c Michael Niedermayer
                st->parser = av_parser_init(st->codec->codec_id);
1050 fb2758c8 Fabrice Bellard
                if (!st->parser) {
1051 a85736f2 Diego Biurrun
                    /* no parser available: just output the raw packets */
1052 57004ff1 Aurelien Jacobs
                    st->need_parsing = AVSTREAM_PARSE_NONE;
1053
                }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
1054 7cbaa7ba Michael Niedermayer
                    st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1055 fb2758c8 Fabrice Bellard
                }
1056 e9b78eeb Michael Niedermayer
                if(st->parser && (s->iformat->flags & AVFMT_GENERIC_INDEX)){
1057 c5577c40 Baptiste Coudurier
                    st->parser->next_frame_offset=
1058 e9b78eeb Michael Niedermayer
                    st->parser->cur_offset= s->cur_pkt.pos;
1059
                }
1060 fb2758c8 Fabrice Bellard
            }
1061
        }
1062
    }
1063 45b2b05f Michael Niedermayer
    if(s->debug & FF_FDEBUG_TS)
1064 3041a4a1 Michael Niedermayer
        av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, flags=%d\n",
1065 434cab9e Michael Niedermayer
            pkt->stream_index,
1066
            pkt->pts,
1067
            pkt->dts,
1068 3041a4a1 Michael Niedermayer
            pkt->size,
1069
            pkt->flags);
1070 434cab9e Michael Niedermayer
1071
    return 0;
1072 fb2758c8 Fabrice Bellard
}
1073
1074
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1075
{
1076 de6d9b64 Fabrice Bellard
    AVPacketList *pktl;
1077 30bc6613 Michael Niedermayer
    int eof=0;
1078
    const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1079
1080
    for(;;){
1081
        pktl = s->packet_buffer;
1082
        if (pktl) {
1083
            AVPacket *next_pkt= &pktl->pkt;
1084
1085
            if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1086
                while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1087 115329f1 Diego Biurrun
                    if(   pktl->pkt.stream_index == next_pkt->stream_index
1088 30bc6613 Michael Niedermayer
                       && next_pkt->dts < pktl->pkt.dts
1089
                       && pktl->pkt.pts != pktl->pkt.dts //not b frame
1090
                       /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
1091
                        next_pkt->pts= pktl->pkt.dts;
1092
                    }
1093
                    pktl= pktl->next;
1094
                }
1095
                pktl = s->packet_buffer;
1096
            }
1097 115329f1 Diego Biurrun
1098
            if(   next_pkt->pts != AV_NOPTS_VALUE
1099
               || next_pkt->dts == AV_NOPTS_VALUE
1100 30bc6613 Michael Niedermayer
               || !genpts || eof){
1101
                /* read packet from packet buffer, if there is data */
1102
                *pkt = *next_pkt;
1103
                s->packet_buffer = pktl->next;
1104
                av_free(pktl);
1105
                return 0;
1106
            }
1107
        }
1108
        if(genpts){
1109
            int ret= av_read_frame_internal(s, pkt);
1110
            if(ret<0){
1111 8fa36ae0 François Revol
                if(pktl && ret != AVERROR(EAGAIN)){
1112 30bc6613 Michael Niedermayer
                    eof=1;
1113
                    continue;
1114
                }else
1115
                    return ret;
1116
            }
1117 115329f1 Diego Biurrun
1118 5c5b1731 Måns Rullgård
            if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1119
                                           &s->packet_buffer_end)) < 0)
1120 769e10f0 Panagiotis Issaris
                return AVERROR(ENOMEM);
1121 30bc6613 Michael Niedermayer
        }else{
1122
            assert(!s->packet_buffer);
1123
            return av_read_frame_internal(s, pkt);
1124
        }
1125 fb2758c8 Fabrice Bellard
    }
1126
}
1127
1128
/* XXX: suppress the packet queue */
1129
static void flush_packet_queue(AVFormatContext *s)
1130
{
1131
    AVPacketList *pktl;
1132
1133
    for(;;) {
1134
        pktl = s->packet_buffer;
1135 115329f1 Diego Biurrun
        if (!pktl)
1136 fb2758c8 Fabrice Bellard
            break;
1137
        s->packet_buffer = pktl->next;
1138
        av_free_packet(&pktl->pkt);
1139
        av_free(pktl);
1140 b9a281db Fabrice Bellard
    }
1141
}
1142
1143 da24c5e3 Fabrice Bellard
/*******************************************************/
1144 fb2758c8 Fabrice Bellard
/* seek support */
1145
1146 b754978a Michael Niedermayer
int av_find_default_stream_index(AVFormatContext *s)
1147
{
1148 ca162a50 Aurelien Jacobs
    int first_audio_index = -1;
1149 b754978a Michael Niedermayer
    int i;
1150
    AVStream *st;
1151
1152
    if (s->nb_streams <= 0)
1153
        return -1;
1154
    for(i = 0; i < s->nb_streams; i++) {
1155
        st = s->streams[i];
1156 01f4895c Michael Niedermayer
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1157 b754978a Michael Niedermayer
            return i;
1158
        }
1159 ca162a50 Aurelien Jacobs
        if (first_audio_index < 0 && st->codec->codec_type == CODEC_TYPE_AUDIO)
1160
            first_audio_index = i;
1161 b754978a Michael Niedermayer
    }
1162 ca162a50 Aurelien Jacobs
    return first_audio_index >= 0 ? first_audio_index : 0;
1163 b754978a Michael Niedermayer
}
1164
1165 e36bdf8b Daniel Kristjansson
/**
1166
 * Flush the frame reader.
1167
 */
1168 fb2758c8 Fabrice Bellard
static void av_read_frame_flush(AVFormatContext *s)
1169
{
1170
    AVStream *st;
1171
    int i;
1172
1173
    flush_packet_queue(s);
1174
1175
    /* free previous packet */
1176
    if (s->cur_st) {
1177
        if (s->cur_st->parser)
1178
            av_free_packet(&s->cur_pkt);
1179
        s->cur_st = NULL;
1180
    }
1181
    /* fail safe */
1182
    s->cur_ptr = NULL;
1183
    s->cur_len = 0;
1184 115329f1 Diego Biurrun
1185 fb2758c8 Fabrice Bellard
    /* for each stream, reset read state */
1186
    for(i = 0; i < s->nb_streams; i++) {
1187
        st = s->streams[i];
1188 115329f1 Diego Biurrun
1189 fb2758c8 Fabrice Bellard
        if (st->parser) {
1190
            av_parser_close(st->parser);
1191
            st->parser = NULL;
1192
        }
1193 635fbcb1 Michael Niedermayer
        st->last_IP_pts = AV_NOPTS_VALUE;
1194 a843d1ff Michael Niedermayer
        st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1195 fb2758c8 Fabrice Bellard
    }
1196
}
1197
1198 22ffac70 Reimar Döffinger
void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1199 8bcb147f Michael Niedermayer
    int i;
1200
1201
    for(i = 0; i < s->nb_streams; i++) {
1202 1a1dc611 Nathan Kurz
        AVStream *st = s->streams[i];
1203 8bcb147f Michael Niedermayer
1204 115329f1 Diego Biurrun
        st->cur_dts = av_rescale(timestamp,
1205 1a1dc611 Nathan Kurz
                                 st->time_base.den * (int64_t)ref_st->time_base.num,
1206
                                 st->time_base.num * (int64_t)ref_st->time_base.den);
1207 8bcb147f Michael Niedermayer
    }
1208
}
1209
1210 3dea63bd Paul Kelly
void ff_reduce_index(AVFormatContext *s, int stream_index)
1211
{
1212
    AVStream *st= s->streams[stream_index];
1213
    unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1214
1215
    if((unsigned)st->nb_index_entries >= max_entries){
1216
        int i;
1217
        for(i=0; 2*i<st->nb_index_entries; i++)
1218
            st->index_entries[i]= st->index_entries[2*i];
1219
        st->nb_index_entries= i;
1220
    }
1221
}
1222
1223 3e9245a9 Michael Niedermayer
int av_add_index_entry(AVStream *st,
1224 30a43f2d Michael Niedermayer
                            int64_t pos, int64_t timestamp, int size, int distance, int flags)
1225 fb2758c8 Fabrice Bellard
{
1226
    AVIndexEntry *entries, *ie;
1227 b754978a Michael Niedermayer
    int index;
1228 115329f1 Diego Biurrun
1229 568e18b1 Michael Niedermayer
    if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1230
        return -1;
1231 115329f1 Diego Biurrun
1232 fb2758c8 Fabrice Bellard
    entries = av_fast_realloc(st->index_entries,
1233
                              &st->index_entries_allocated_size,
1234 115329f1 Diego Biurrun
                              (st->nb_index_entries + 1) *
1235 fb2758c8 Fabrice Bellard
                              sizeof(AVIndexEntry));
1236 568e18b1 Michael Niedermayer
    if(!entries)
1237
        return -1;
1238
1239 b754978a Michael Niedermayer
    st->index_entries= entries;
1240
1241 27a5fe5f Michael Niedermayer
    index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
1242 b754978a Michael Niedermayer
1243 3ba1438d Michael Niedermayer
    if(index<0){
1244 3e9245a9 Michael Niedermayer
        index= st->nb_index_entries++;
1245
        ie= &entries[index];
1246 3ba1438d Michael Niedermayer
        assert(index==0 || ie[-1].timestamp < timestamp);
1247
    }else{
1248
        ie= &entries[index];
1249
        if(ie->timestamp != timestamp){
1250 528c2c73 Michael Niedermayer
            if(ie->timestamp <= timestamp)
1251
                return -1;
1252 3ba1438d Michael Niedermayer
            memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
1253
            st->nb_index_entries++;
1254 755bfeab Diego Biurrun
        }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1255 3ba1438d Michael Niedermayer
            distance= ie->min_distance;
1256 3e9245a9 Michael Niedermayer
    }
1257 3ba1438d Michael Niedermayer
1258 b754978a Michael Niedermayer
    ie->pos = pos;
1259
    ie->timestamp = timestamp;
1260 3e9245a9 Michael Niedermayer
    ie->min_distance= distance;
1261 30a43f2d Michael Niedermayer
    ie->size= size;
1262 b754978a Michael Niedermayer
    ie->flags = flags;
1263 115329f1 Diego Biurrun
1264 3e9245a9 Michael Niedermayer
    return index;
1265 fb2758c8 Fabrice Bellard
}
1266
1267 dc56fc38 Michael Niedermayer
int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1268 27a5fe5f Michael Niedermayer
                              int flags)
1269 fb2758c8 Fabrice Bellard
{
1270 b754978a Michael Niedermayer
    AVIndexEntry *entries= st->index_entries;
1271
    int nb_entries= st->nb_index_entries;
1272 fb2758c8 Fabrice Bellard
    int a, b, m;
1273
    int64_t timestamp;
1274
1275 3ba1438d Michael Niedermayer
    a = - 1;
1276
    b = nb_entries;
1277 b754978a Michael Niedermayer
1278 3ba1438d Michael Niedermayer
    while (b - a > 1) {
1279
        m = (a + b) >> 1;
1280 fb2758c8 Fabrice Bellard
        timestamp = entries[m].timestamp;
1281 3ba1438d Michael Niedermayer
        if(timestamp >= wanted_timestamp)
1282
            b = m;
1283
        if(timestamp <= wanted_timestamp)
1284 b754978a Michael Niedermayer
            a = m;
1285 fb2758c8 Fabrice Bellard
    }
1286 27a5fe5f Michael Niedermayer
    m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1287 115329f1 Diego Biurrun
1288 27a5fe5f Michael Niedermayer
    if(!(flags & AVSEEK_FLAG_ANY)){
1289
        while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1290
            m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1291
        }
1292
    }
1293 3ba1438d Michael Niedermayer
1294 115329f1 Diego Biurrun
    if(m == nb_entries)
1295 3ba1438d Michael Niedermayer
        return -1;
1296
    return  m;
1297 fb2758c8 Fabrice Bellard
}
1298
1299 0f652a8e Benoit Fouet
#define DEBUG_SEEK
1300 8d14a25c Michael Niedermayer
1301 3ba1438d Michael Niedermayer
int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1302 8d14a25c Michael Niedermayer
    AVInputFormat *avif= s->iformat;
1303
    int64_t pos_min, pos_max, pos, pos_limit;
1304
    int64_t ts_min, ts_max, ts;
1305 89ddd2a9 Michael Niedermayer
    int index;
1306 8d14a25c Michael Niedermayer
    AVStream *st;
1307
1308 cdd5034f Michael Niedermayer
    if (stream_index < 0)
1309
        return -1;
1310 115329f1 Diego Biurrun
1311 8d14a25c Michael Niedermayer
#ifdef DEBUG_SEEK
1312 4733abcb Måns Rullgård
    av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1313 8d14a25c Michael Niedermayer
#endif
1314
1315
    ts_max=
1316
    ts_min= AV_NOPTS_VALUE;
1317 90b5b51e Diego Biurrun
    pos_limit= -1; //gcc falsely says it may be uninitialized
1318 8d14a25c Michael Niedermayer
1319
    st= s->streams[stream_index];
1320
    if(st->index_entries){
1321
        AVIndexEntry *e;
1322
1323 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()
1324 3ba1438d Michael Niedermayer
        index= FFMAX(index, 0);
1325 8d14a25c Michael Niedermayer
        e= &st->index_entries[index];
1326
1327
        if(e->timestamp <= target_ts || e->pos == e->min_distance){
1328
            pos_min= e->pos;
1329
            ts_min= e->timestamp;
1330
#ifdef DEBUG_SEEK
1331 115329f1 Diego Biurrun
        av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1332 8d14a25c Michael Niedermayer
               pos_min,ts_min);
1333
#endif
1334
        }else{
1335
            assert(index==0);
1336
        }
1337 115329f1 Diego Biurrun
1338
        index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1339 27a5fe5f Michael Niedermayer
        assert(index < st->nb_index_entries);
1340
        if(index >= 0){
1341 8d14a25c Michael Niedermayer
            e= &st->index_entries[index];
1342
            assert(e->timestamp >= target_ts);
1343
            pos_max= e->pos;
1344
            ts_max= e->timestamp;
1345
            pos_limit= pos_max - e->min_distance;
1346
#ifdef DEBUG_SEEK
1347 115329f1 Diego Biurrun
        av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1348 8d14a25c Michael Niedermayer
               pos_max,pos_limit, ts_max);
1349
#endif
1350
        }
1351
    }
1352
1353 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);
1354
    if(pos<0)
1355
        return -1;
1356
1357
    /* do the seek */
1358 899681cd Björn Axelsson
    url_fseek(s->pb, pos, SEEK_SET);
1359 89ddd2a9 Michael Niedermayer
1360
    av_update_cur_dts(s, st, ts);
1361
1362
    return 0;
1363
}
1364
1365
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 )){
1366
    int64_t pos, ts;
1367
    int64_t start_pos, filesize;
1368
    int no_change;
1369
1370
#ifdef DEBUG_SEEK
1371
    av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1372
#endif
1373
1374 8d14a25c Michael Niedermayer
    if(ts_min == AV_NOPTS_VALUE){
1375
        pos_min = s->data_offset;
1376 89ddd2a9 Michael Niedermayer
        ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1377 8d14a25c Michael Niedermayer
        if (ts_min == AV_NOPTS_VALUE)
1378
            return -1;
1379
    }
1380
1381
    if(ts_max == AV_NOPTS_VALUE){
1382
        int step= 1024;
1383 899681cd Björn Axelsson
        filesize = url_fsize(s->pb);
1384 6fd93ce2 Kenneth Aafløy
        pos_max = filesize - 1;
1385 8d14a25c Michael Niedermayer
        do{
1386
            pos_max -= step;
1387 89ddd2a9 Michael Niedermayer
            ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1388 8d14a25c Michael Niedermayer
            step += step;
1389
        }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1390
        if (ts_max == AV_NOPTS_VALUE)
1391
            return -1;
1392 115329f1 Diego Biurrun
1393 8d14a25c Michael Niedermayer
        for(;;){
1394
            int64_t tmp_pos= pos_max + 1;
1395 89ddd2a9 Michael Niedermayer
            int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1396 8d14a25c Michael Niedermayer
            if(tmp_ts == AV_NOPTS_VALUE)
1397
                break;
1398
            ts_max= tmp_ts;
1399
            pos_max= tmp_pos;
1400 6fd93ce2 Kenneth Aafløy
            if(tmp_pos >= filesize)
1401
                break;
1402 8d14a25c Michael Niedermayer
        }
1403
        pos_limit= pos_max;
1404
    }
1405
1406 53f7c43f Michael Niedermayer
    if(ts_min > ts_max){
1407
        return -1;
1408
    }else if(ts_min == ts_max){
1409
        pos_limit= pos_min;
1410
    }
1411
1412 8d14a25c Michael Niedermayer
    no_change=0;
1413
    while (pos_min < pos_limit) {
1414
#ifdef DEBUG_SEEK
1415 115329f1 Diego Biurrun
        av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1416 8d14a25c Michael Niedermayer
               pos_min, pos_max,
1417
               ts_min, ts_max);
1418
#endif
1419
        assert(pos_limit <= pos_max);
1420
1421
        if(no_change==0){
1422
            int64_t approximate_keyframe_distance= pos_max - pos_limit;
1423
            // interpolate position (better than dichotomy)
1424 3ba1438d Michael Niedermayer
            pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1425
                + pos_min - approximate_keyframe_distance;
1426 8d14a25c Michael Niedermayer
        }else if(no_change==1){
1427
            // bisection, if interpolation failed to change min or max pos last time
1428
            pos = (pos_min + pos_limit)>>1;
1429
        }else{
1430 a85736f2 Diego Biurrun
            /* linear search if bisection failed, can only happen if there
1431
               are very few or no keyframes between min/max */
1432 8d14a25c Michael Niedermayer
            pos=pos_min;
1433
        }
1434
        if(pos <= pos_min)
1435
            pos= pos_min + 1;
1436
        else if(pos > pos_limit)
1437
            pos= pos_limit;
1438
        start_pos= pos;
1439
1440 89ddd2a9 Michael Niedermayer
        ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1441 8d14a25c Michael Niedermayer
        if(pos == pos_max)
1442
            no_change++;
1443
        else
1444
            no_change=0;
1445
#ifdef DEBUG_SEEK
1446 4733abcb Måns Rullgård
av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n", pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, start_pos, no_change);
1447 8d14a25c Michael Niedermayer
#endif
1448 db2a0e22 Michael Niedermayer
        if(ts == AV_NOPTS_VALUE){
1449
            av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1450
            return -1;
1451
        }
1452 8d14a25c Michael Niedermayer
        assert(ts != AV_NOPTS_VALUE);
1453 3ba1438d Michael Niedermayer
        if (target_ts <= ts) {
1454 8d14a25c Michael Niedermayer
            pos_limit = start_pos - 1;
1455
            pos_max = pos;
1456
            ts_max = ts;
1457 3ba1438d Michael Niedermayer
        }
1458
        if (target_ts >= ts) {
1459 8d14a25c Michael Niedermayer
            pos_min = pos;
1460
            ts_min = ts;
1461
        }
1462
    }
1463 115329f1 Diego Biurrun
1464 3ba1438d Michael Niedermayer
    pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1465
    ts  = (flags & AVSEEK_FLAG_BACKWARD) ?  ts_min :  ts_max;
1466 8d14a25c Michael Niedermayer
#ifdef DEBUG_SEEK
1467
    pos_min = pos;
1468 89ddd2a9 Michael Niedermayer
    ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1469 8d14a25c Michael Niedermayer
    pos_min++;
1470 89ddd2a9 Michael Niedermayer
    ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1471 115329f1 Diego Biurrun
    av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1472 8d14a25c Michael Niedermayer
           pos, ts_min, target_ts, ts_max);
1473
#endif
1474 89ddd2a9 Michael Niedermayer
    *ts_ret= ts;
1475
    return pos;
1476 8d14a25c Michael Niedermayer
}
1477
1478 3ba1438d Michael Niedermayer
static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1479
    int64_t pos_min, pos_max;
1480
#if 0
1481
    AVStream *st;
1482

1483
    if (stream_index < 0)
1484
        return -1;
1485

1486
    st= s->streams[stream_index];
1487
#endif
1488
1489
    pos_min = s->data_offset;
1490 899681cd Björn Axelsson
    pos_max = url_fsize(s->pb) - 1;
1491 3ba1438d Michael Niedermayer
1492
    if     (pos < pos_min) pos= pos_min;
1493
    else if(pos > pos_max) pos= pos_max;
1494
1495 899681cd Björn Axelsson
    url_fseek(s->pb, pos, SEEK_SET);
1496 3ba1438d Michael Niedermayer
1497
#if 0
1498 8bcb147f Michael Niedermayer
    av_update_cur_dts(s, st, ts);
1499 3ba1438d Michael Niedermayer
#endif
1500
    return 0;
1501
}
1502
1503 115329f1 Diego Biurrun
static int av_seek_frame_generic(AVFormatContext *s,
1504 3ba1438d Michael Niedermayer
                                 int stream_index, int64_t timestamp, int flags)
1505 fb2758c8 Fabrice Bellard
{
1506 aaec4e03 Baptiste Coudurier
    int index, ret;
1507 fb2758c8 Fabrice Bellard
    AVStream *st;
1508
    AVIndexEntry *ie;
1509
1510
    st = s->streams[stream_index];
1511 e9b78eeb Michael Niedermayer
1512 27a5fe5f Michael Niedermayer
    index = av_index_search_timestamp(st, timestamp, flags);
1513 e9b78eeb Michael Niedermayer
1514 b5a3541d Michael Niedermayer
    if(index < 0 || index==st->nb_index_entries-1){
1515 e9b78eeb Michael Niedermayer
        int i;
1516
        AVPacket pkt;
1517
1518 5e5c9086 Michael Niedermayer
        if(st->nb_index_entries){
1519
            assert(st->index_entries);
1520 e9b78eeb Michael Niedermayer
            ie= &st->index_entries[st->nb_index_entries-1];
1521 aaec4e03 Baptiste Coudurier
            if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
1522
                return ret;
1523 e9b78eeb Michael Niedermayer
            av_update_cur_dts(s, st, ie->timestamp);
1524 aaec4e03 Baptiste Coudurier
        }else{
1525
            if ((ret = url_fseek(s->pb, 0, SEEK_SET)) < 0)
1526
                return ret;
1527
        }
1528 e9b78eeb Michael Niedermayer
        for(i=0;; i++) {
1529
            int ret = av_read_frame(s, &pkt);
1530
            if(ret<0)
1531
                break;
1532
            av_free_packet(&pkt);
1533
            if(stream_index == pkt.stream_index){
1534
                if((pkt.flags & PKT_FLAG_KEY) && pkt.dts > timestamp)
1535
                    break;
1536
            }
1537
        }
1538
        index = av_index_search_timestamp(st, timestamp, flags);
1539
    }
1540 fb2758c8 Fabrice Bellard
    if (index < 0)
1541
        return -1;
1542
1543
    av_read_frame_flush(s);
1544 e9b78eeb Michael Niedermayer
    if (s->iformat->read_seek){
1545
        if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1546
            return 0;
1547
    }
1548
    ie = &st->index_entries[index];
1549 aaec4e03 Baptiste Coudurier
    if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
1550
        return ret;
1551 8bcb147f Michael Niedermayer
    av_update_cur_dts(s, st, ie->timestamp);
1552 cdd5034f Michael Niedermayer
1553 fb2758c8 Fabrice Bellard
    return 0;
1554
}
1555
1556 3ba1438d Michael Niedermayer
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1557 fb2758c8 Fabrice Bellard
{
1558
    int ret;
1559 cdd5034f Michael Niedermayer
    AVStream *st;
1560 115329f1 Diego Biurrun
1561 fb2758c8 Fabrice Bellard
    av_read_frame_flush(s);
1562 115329f1 Diego Biurrun
1563 3ba1438d Michael Niedermayer
    if(flags & AVSEEK_FLAG_BYTE)
1564
        return av_seek_frame_byte(s, stream_index, timestamp, flags);
1565 115329f1 Diego Biurrun
1566 cdd5034f Michael Niedermayer
    if(stream_index < 0){
1567
        stream_index= av_find_default_stream_index(s);
1568
        if(stream_index < 0)
1569
            return -1;
1570 115329f1 Diego Biurrun
1571 3ba1438d Michael Niedermayer
        st= s->streams[stream_index];
1572 eb497825 Nathan Kurz
       /* timestamp for default must be expressed in AV_TIME_BASE units */
1573 3ba1438d Michael Niedermayer
        timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1574 cdd5034f Michael Niedermayer
    }
1575
1576 fb2758c8 Fabrice Bellard
    /* first, we try the format specific seek */
1577
    if (s->iformat->read_seek)
1578 3ba1438d Michael Niedermayer
        ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1579 fb2758c8 Fabrice Bellard
    else
1580
        ret = -1;
1581
    if (ret >= 0) {
1582
        return 0;
1583
    }
1584 8d14a25c Michael Niedermayer
1585
    if(s->iformat->read_timestamp)
1586 3ba1438d Michael Niedermayer
        return av_seek_frame_binary(s, stream_index, timestamp, flags);
1587 8d14a25c Michael Niedermayer
    else
1588 3ba1438d Michael Niedermayer
        return av_seek_frame_generic(s, stream_index, timestamp, flags);
1589 fb2758c8 Fabrice Bellard
}
1590
1591
/*******************************************************/
1592 12f996ed Fabrice Bellard
1593 e36bdf8b Daniel Kristjansson
/**
1594 c1e8b678 Neil Brown
 * Returns TRUE if the stream has accurate duration in any stream.
1595 e36bdf8b Daniel Kristjansson
 *
1596 c1e8b678 Neil Brown
 * @return TRUE if the stream has accurate duration for at least one component.
1597 e36bdf8b Daniel Kristjansson
 */
1598 c1e8b678 Neil Brown
static int av_has_duration(AVFormatContext *ic)
1599 12f996ed Fabrice Bellard
{
1600
    int i;
1601
    AVStream *st;
1602
1603
    for(i = 0;i < ic->nb_streams; i++) {
1604
        st = ic->streams[i];
1605 c1e8b678 Neil Brown
        if (st->duration != AV_NOPTS_VALUE)
1606 12f996ed Fabrice Bellard
            return 1;
1607
    }
1608
    return 0;
1609
}
1610
1611 e36bdf8b Daniel Kristjansson
/**
1612
 * Estimate the stream timings from the one of each components.
1613
 *
1614
 * Also computes the global bitrate if possible.
1615
 */
1616 12f996ed Fabrice Bellard
static void av_update_stream_timings(AVFormatContext *ic)
1617
{
1618 c0df9d75 Michael Niedermayer
    int64_t start_time, start_time1, end_time, end_time1;
1619 c1e8b678 Neil Brown
    int64_t duration, duration1;
1620 12f996ed Fabrice Bellard
    int i;
1621
    AVStream *st;
1622
1623 f27a7268 Måns Rullgård
    start_time = INT64_MAX;
1624
    end_time = INT64_MIN;
1625 c1e8b678 Neil Brown
    duration = INT64_MIN;
1626 12f996ed Fabrice Bellard
    for(i = 0;i < ic->nb_streams; i++) {
1627
        st = ic->streams[i];
1628 7f938dd3 Aurelien Jacobs
        if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1629 c0df9d75 Michael Niedermayer
            start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1630
            if (start_time1 < start_time)
1631
                start_time = start_time1;
1632 12f996ed Fabrice Bellard
            if (st->duration != AV_NOPTS_VALUE) {
1633 c0df9d75 Michael Niedermayer
                end_time1 = start_time1
1634
                          + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1635 12f996ed Fabrice Bellard
                if (end_time1 > end_time)
1636
                    end_time = end_time1;
1637
            }
1638
        }
1639 c1e8b678 Neil Brown
        if (st->duration != AV_NOPTS_VALUE) {
1640
            duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1641
            if (duration1 > duration)
1642
                duration = duration1;
1643
        }
1644 12f996ed Fabrice Bellard
    }
1645 f27a7268 Måns Rullgård
    if (start_time != INT64_MAX) {
1646 12f996ed Fabrice Bellard
        ic->start_time = start_time;
1647 f27a7268 Måns Rullgård
        if (end_time != INT64_MIN) {
1648 c1e8b678 Neil Brown
            if (end_time - start_time > duration)
1649
                duration = end_time - start_time;
1650
        }
1651
    }
1652
    if (duration != INT64_MIN) {
1653
        ic->duration = duration;
1654
        if (ic->file_size > 0) {
1655 a85736f2 Diego Biurrun
            /* compute the bitrate */
1656 c1e8b678 Neil Brown
            ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1657
                (double)ic->duration;
1658 12f996ed Fabrice Bellard
        }
1659
    }
1660
}
1661
1662
static void fill_all_stream_timings(AVFormatContext *ic)
1663
{
1664
    int i;
1665
    AVStream *st;
1666
1667
    av_update_stream_timings(ic);
1668
    for(i = 0;i < ic->nb_streams; i++) {
1669
        st = ic->streams[i];
1670
        if (st->start_time == AV_NOPTS_VALUE) {
1671 c0df9d75 Michael Niedermayer
            if(ic->start_time != AV_NOPTS_VALUE)
1672
                st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1673
            if(ic->duration != AV_NOPTS_VALUE)
1674
                st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1675 12f996ed Fabrice Bellard
        }
1676
    }
1677
}
1678
1679
static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1680
{
1681
    int64_t filesize, duration;
1682
    int bit_rate, i;
1683
    AVStream *st;
1684
1685
    /* if bit_rate is already set, we believe it */
1686
    if (ic->bit_rate == 0) {
1687
        bit_rate = 0;
1688
        for(i=0;i<ic->nb_streams;i++) {
1689
            st = ic->streams[i];
1690 01f4895c Michael Niedermayer
            bit_rate += st->codec->bit_rate;
1691 12f996ed Fabrice Bellard
        }
1692
        ic->bit_rate = bit_rate;
1693
    }
1694
1695
    /* if duration is already set, we believe it */
1696 115329f1 Diego Biurrun
    if (ic->duration == AV_NOPTS_VALUE &&
1697
        ic->bit_rate != 0 &&
1698 12f996ed Fabrice Bellard
        ic->file_size != 0)  {
1699
        filesize = ic->file_size;
1700
        if (filesize > 0) {
1701
            for(i = 0; i < ic->nb_streams; i++) {
1702
                st = ic->streams[i];
1703 c0df9d75 Michael Niedermayer
                duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1704 9f32041d Neil Brown
                if (st->duration == AV_NOPTS_VALUE)
1705 12f996ed Fabrice Bellard
                    st->duration = duration;
1706
            }
1707
        }
1708
    }
1709
}
1710
1711
#define DURATION_MAX_READ_SIZE 250000
1712
1713
/* only usable for MPEG-PS streams */
1714 bc5c918e Diego Biurrun
static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1715 12f996ed Fabrice Bellard
{
1716
    AVPacket pkt1, *pkt = &pkt1;
1717
    AVStream *st;
1718
    int read_size, i, ret;
1719 bf4e3bd2 Måns Rullgård
    int64_t end_time;
1720 12f996ed Fabrice Bellard
    int64_t filesize, offset, duration;
1721 115329f1 Diego Biurrun
1722 578688fa Luca Abeni
    /* free previous packet */
1723
    if (ic->cur_st && ic->cur_st->parser)
1724
        av_free_packet(&ic->cur_pkt);
1725
    ic->cur_st = NULL;
1726
1727
    /* flush packet queue */
1728
    flush_packet_queue(ic);
1729
1730
    for(i=0;i<ic->nb_streams;i++) {
1731
        st = ic->streams[i];
1732
        if (st->parser) {
1733
            av_parser_close(st->parser);
1734
            st->parser= NULL;
1735
        }
1736
    }
1737 115329f1 Diego Biurrun
1738 12f996ed Fabrice Bellard
    /* we read the first packets to get the first PTS (not fully
1739
       accurate, but it is enough now) */
1740 899681cd Björn Axelsson
    url_fseek(ic->pb, 0, SEEK_SET);
1741 12f996ed Fabrice Bellard
    read_size = 0;
1742
    for(;;) {
1743
        if (read_size >= DURATION_MAX_READ_SIZE)
1744
            break;
1745
        /* if all info is available, we can stop */
1746
        for(i = 0;i < ic->nb_streams; i++) {
1747
            st = ic->streams[i];
1748
            if (st->start_time == AV_NOPTS_VALUE)
1749
                break;
1750
        }
1751
        if (i == ic->nb_streams)
1752
            break;
1753
1754
        ret = av_read_packet(ic, pkt);
1755
        if (ret != 0)
1756
            break;
1757
        read_size += pkt->size;
1758
        st = ic->streams[pkt->stream_index];
1759
        if (pkt->pts != AV_NOPTS_VALUE) {
1760
            if (st->start_time == AV_NOPTS_VALUE)
1761 c0df9d75 Michael Niedermayer
                st->start_time = pkt->pts;
1762 0a5f92a1 Michael Niedermayer
        }
1763
        av_free_packet(pkt);
1764
    }
1765 12f996ed Fabrice Bellard
1766
    /* estimate the end time (duration) */
1767
    /* XXX: may need to support wrapping */
1768
    filesize = ic->file_size;
1769
    offset = filesize - DURATION_MAX_READ_SIZE;
1770
    if (offset < 0)
1771
        offset = 0;
1772
1773 899681cd Björn Axelsson
    url_fseek(ic->pb, offset, SEEK_SET);
1774 12f996ed Fabrice Bellard
    read_size = 0;
1775
    for(;;) {
1776
        if (read_size >= DURATION_MAX_READ_SIZE)
1777
            break;
1778 115329f1 Diego Biurrun
1779 12f996ed Fabrice Bellard
        ret = av_read_packet(ic, pkt);
1780
        if (ret != 0)
1781
            break;
1782
        read_size += pkt->size;
1783
        st = ic->streams[pkt->stream_index];
1784 bf494092 Neil Brown
        if (pkt->pts != AV_NOPTS_VALUE &&
1785
            st->start_time != AV_NOPTS_VALUE) {
1786 c0df9d75 Michael Niedermayer
            end_time = pkt->pts;
1787 12f996ed Fabrice Bellard
            duration = end_time - st->start_time;
1788
            if (duration > 0) {
1789
                if (st->duration == AV_NOPTS_VALUE ||
1790
                    st->duration < duration)
1791
                    st->duration = duration;
1792
            }
1793
        }
1794
        av_free_packet(pkt);
1795
    }
1796 115329f1 Diego Biurrun
1797 c0df9d75 Michael Niedermayer
    fill_all_stream_timings(ic);
1798 12f996ed Fabrice Bellard
1799 899681cd Björn Axelsson
    url_fseek(ic->pb, old_offset, SEEK_SET);
1800 df886e7e Michael Niedermayer
    for(i=0; i<ic->nb_streams; i++){
1801
        st= ic->streams[i];
1802
        st->cur_dts= st->first_dts;
1803 635fbcb1 Michael Niedermayer
        st->last_IP_pts = AV_NOPTS_VALUE;
1804 df886e7e Michael Niedermayer
    }
1805 12f996ed Fabrice Bellard
}
1806
1807 bc5c918e Diego Biurrun
static void av_estimate_timings(AVFormatContext *ic, int64_t old_offset)
1808 12f996ed Fabrice Bellard
{
1809
    int64_t file_size;
1810
1811
    /* get the file size, if possible */
1812
    if (ic->iformat->flags & AVFMT_NOFILE) {
1813
        file_size = 0;
1814
    } else {
1815 899681cd Björn Axelsson
        file_size = url_fsize(ic->pb);
1816 12f996ed Fabrice Bellard
        if (file_size < 0)
1817
            file_size = 0;
1818
    }
1819
    ic->file_size = file_size;
1820
1821 ff70e601 Måns Rullgård
    if ((!strcmp(ic->iformat->name, "mpeg") ||
1822
         !strcmp(ic->iformat->name, "mpegts")) &&
1823 ceeacce6 Aurelien Jacobs
        file_size && !url_is_streamed(ic->pb)) {
1824 12f996ed Fabrice Bellard
        /* get accurate estimate from the PTSes */
1825 9ecf7fad Wolfram Gloger
        av_estimate_timings_from_pts(ic, old_offset);
1826 c1e8b678 Neil Brown
    } else if (av_has_duration(ic)) {
1827 a85736f2 Diego Biurrun
        /* at least one component has timings - we use them for all
1828 12f996ed Fabrice Bellard
           the components */
1829
        fill_all_stream_timings(ic);
1830
    } else {
1831 a85736f2 Diego Biurrun
        /* less precise: use bitrate info */
1832 12f996ed Fabrice Bellard
        av_estimate_timings_from_bit_rate(ic);
1833
    }
1834
    av_update_stream_timings(ic);
1835
1836
#if 0
1837
    {
1838
        int i;
1839
        AVStream *st;
1840
        for(i = 0;i < ic->nb_streams; i++) {
1841
            st = ic->streams[i];
1842 115329f1 Diego Biurrun
        printf("%d: start_time: %0.3f duration: %0.3f\n",
1843
               i, (double)st->start_time / AV_TIME_BASE,
1844 12f996ed Fabrice Bellard
               (double)st->duration / AV_TIME_BASE);
1845
        }
1846 115329f1 Diego Biurrun
        printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1847
               (double)ic->start_time / AV_TIME_BASE,
1848 12f996ed Fabrice Bellard
               (double)ic->duration / AV_TIME_BASE,
1849
               ic->bit_rate / 1000);
1850
    }
1851
#endif
1852
}
1853
1854 b9a281db Fabrice Bellard
static int has_codec_parameters(AVCodecContext *enc)
1855
{
1856
    int val;
1857
    switch(enc->codec_type) {
1858
    case CODEC_TYPE_AUDIO:
1859 ca9c5a4d Baptiste Coudurier
        val = enc->sample_rate && enc->channels && enc->sample_fmt != SAMPLE_FMT_NONE;
1860 f3b5a1a2 Baptiste Coudurier
        if(!enc->frame_size &&
1861
           (enc->codec_id == CODEC_ID_VORBIS ||
1862
            enc->codec_id == CODEC_ID_AAC))
1863 4d35bf74 Michael Niedermayer
            return 0;
1864 b9a281db Fabrice Bellard
        break;
1865
    case CODEC_TYPE_VIDEO:
1866 644a9262 Michael Niedermayer
        val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
1867 b9a281db Fabrice Bellard
        break;
1868
    default:
1869
        val = 1;
1870
        break;
1871
    }
1872 ccd425e7 Diego Biurrun
    return enc->codec_id != CODEC_ID_NONE && val != 0;
1873 b9a281db Fabrice Bellard
}
1874
1875 fb2758c8 Fabrice Bellard
static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1876
{
1877
    int16_t *samples;
1878
    AVCodec *codec;
1879 3fdb6af9 Baptiste Coudurier
    int got_picture, data_size, ret=0;
1880 fb2758c8 Fabrice Bellard
    AVFrame picture;
1881 115329f1 Diego Biurrun
1882 01f4895c Michael Niedermayer
  if(!st->codec->codec){
1883
    codec = avcodec_find_decoder(st->codec->codec_id);
1884 fb2758c8 Fabrice Bellard
    if (!codec)
1885
        return -1;
1886 01f4895c Michael Niedermayer
    ret = avcodec_open(st->codec, codec);
1887 fb2758c8 Fabrice Bellard
    if (ret < 0)
1888
        return ret;
1889 43c0040a Michael Niedermayer
  }
1890 644a9262 Michael Niedermayer
1891 01f4895c Michael Niedermayer
  if(!has_codec_parameters(st->codec)){
1892
    switch(st->codec->codec_type) {
1893 fb2758c8 Fabrice Bellard
    case CODEC_TYPE_VIDEO:
1894 115329f1 Diego Biurrun
        ret = avcodec_decode_video(st->codec, &picture,
1895 dc296223 Michael Niedermayer
                                   &got_picture, data, size);
1896 fb2758c8 Fabrice Bellard
        break;
1897
    case CODEC_TYPE_AUDIO:
1898 3fdb6af9 Baptiste Coudurier
        data_size = FFMAX(size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
1899
        samples = av_malloc(data_size);
1900 fb2758c8 Fabrice Bellard
        if (!samples)
1901
            goto fail;
1902 3fdb6af9 Baptiste Coudurier
        ret = avcodec_decode_audio2(st->codec, samples,
1903 dc296223 Michael Niedermayer
                                    &data_size, data, size);
1904 fb2758c8 Fabrice Bellard
        av_free(samples);
1905
        break;
1906
    default:
1907
        break;
1908
    }
1909 644a9262 Michael Niedermayer
  }
1910 fb2758c8 Fabrice Bellard
 fail:
1911
    return ret;
1912
}
1913
1914 45da8124 Aurelien Jacobs
unsigned int codec_get_tag(const AVCodecTag *tags, int id)
1915
{
1916
    while (tags->id != CODEC_ID_NONE) {
1917
        if (tags->id == id)
1918
            return tags->tag;
1919
        tags++;
1920
    }
1921
    return 0;
1922
}
1923
1924
enum CodecID codec_get_id(const AVCodecTag *tags, unsigned int tag)
1925
{
1926 41415d28 Michael Niedermayer
    int i;
1927
    for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
1928
        if(tag == tags[i].tag)
1929
            return tags[i].id;
1930
    }
1931
    for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
1932
        if(   toupper((tag >> 0)&0xFF) == toupper((tags[i].tag >> 0)&0xFF)
1933
           && toupper((tag >> 8)&0xFF) == toupper((tags[i].tag >> 8)&0xFF)
1934
           && toupper((tag >>16)&0xFF) == toupper((tags[i].tag >>16)&0xFF)
1935
           && toupper((tag >>24)&0xFF) == toupper((tags[i].tag >>24)&0xFF))
1936
            return tags[i].id;
1937 45da8124 Aurelien Jacobs
    }
1938
    return CODEC_ID_NONE;
1939
}
1940
1941 15545a09 Stefano Sabatini
unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
1942 45da8124 Aurelien Jacobs
{
1943
    int i;
1944
    for(i=0; tags && tags[i]; i++){
1945
        int tag= codec_get_tag(tags[i], id);
1946
        if(tag) return tag;
1947
    }
1948
    return 0;
1949
}
1950
1951 15545a09 Stefano Sabatini
enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
1952 45da8124 Aurelien Jacobs
{
1953
    int i;
1954
    for(i=0; tags && tags[i]; i++){
1955
        enum CodecID id= codec_get_id(tags[i], tag);
1956
        if(id!=CODEC_ID_NONE) return id;
1957
    }
1958
    return CODEC_ID_NONE;
1959
}
1960
1961 c2c3dedf Aurelien Jacobs
static void compute_chapters_end(AVFormatContext *s)
1962
{
1963
    unsigned int i;
1964
1965
    for (i=0; i+1<s->nb_chapters; i++)
1966
        if (s->chapters[i]->end == AV_NOPTS_VALUE) {
1967
            assert(s->chapters[i]->start <= s->chapters[i+1]->start);
1968
            assert(!av_cmp_q(s->chapters[i]->time_base, s->chapters[i+1]->time_base));
1969
            s->chapters[i]->end = s->chapters[i+1]->start;
1970
        }
1971
1972
    if (s->nb_chapters && s->chapters[i]->end == AV_NOPTS_VALUE) {
1973
        assert(s->start_time != AV_NOPTS_VALUE);
1974
        assert(s->duration > 0);
1975
        s->chapters[i]->end = av_rescale_q(s->start_time + s->duration,
1976
                                           AV_TIME_BASE_Q,
1977
                                           s->chapters[i]->time_base);
1978
    }
1979
}
1980
1981 fb2758c8 Fabrice Bellard
/* absolute maximum size we read until we abort */
1982
#define MAX_READ_SIZE        5000000
1983
1984 fd97f6a2 Michael Niedermayer
#define MAX_STD_TIMEBASES (60*12+5)
1985 4d43cbcc Michael Niedermayer
static int get_std_framerate(int i){
1986
    if(i<60*12) return i*1001;
1987 aecf157e Reimar Döffinger
    else        return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
1988 4d43cbcc Michael Niedermayer
}
1989
1990 945208ca Michael Niedermayer
/*
1991
 * Is the time base unreliable.
1992
 * This is a heuristic to balance between quick acceptance of the values in
1993
 * the headers vs. some extra checks.
1994 a85736f2 Diego Biurrun
 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
1995
 * MPEG-2 commonly misuses field repeat flags to store different framerates.
1996 945208ca Michael Niedermayer
 * And there are "variable" fps files this needs to detect as well.
1997
 */
1998
static int tb_unreliable(AVCodecContext *c){
1999
    if(   c->time_base.den >= 101L*c->time_base.num
2000
       || c->time_base.den <    5L*c->time_base.num
2001
/*       || c->codec_tag == ff_get_fourcc("DIVX")
2002
       || c->codec_tag == ff_get_fourcc("XVID")*/
2003
       || c->codec_id == CODEC_ID_MPEG2VIDEO)
2004
        return 1;
2005
    return 0;
2006
}
2007
2008 b9a281db Fabrice Bellard
int av_find_stream_info(AVFormatContext *ic)
2009
{
2010 9f75260e Michael Niedermayer
    int i, count, ret, read_size, j;
2011 b9a281db Fabrice Bellard
    AVStream *st;
2012 fb2758c8 Fabrice Bellard
    AVPacket pkt1, *pkt;
2013 15bc38e5 Michael Niedermayer
    int64_t last_dts[MAX_STREAMS];
2014 3c150d16 Michael Niedermayer
    int duration_count[MAX_STREAMS]={0};
2015 0cbff027 Kristian Amlie
    double (*duration_error)[MAX_STD_TIMEBASES];
2016 bc5c918e Diego Biurrun
    int64_t old_offset = url_ftell(ic->pb);
2017 ea486ab3 Baptiste Coudurier
    int64_t codec_info_duration[MAX_STREAMS]={0};
2018
    int codec_info_nb_frames[MAX_STREAMS]={0};
2019 b9a281db Fabrice Bellard
2020 0cbff027 Kristian Amlie
    duration_error = av_mallocz(MAX_STREAMS * sizeof(*duration_error));
2021 769e10f0 Panagiotis Issaris
    if (!duration_error) return AVERROR(ENOMEM);
2022 0cbff027 Kristian Amlie
2023 c0df9d75 Michael Niedermayer
    for(i=0;i<ic->nb_streams;i++) {
2024
        st = ic->streams[i];
2025 01f4895c Michael Niedermayer
        if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2026 c0df9d75 Michael Niedermayer
/*            if(!st->time_base.num)
2027
                st->time_base= */
2028 01f4895c Michael Niedermayer
            if(!st->codec->time_base.num)
2029
                st->codec->time_base= st->time_base;
2030 c0df9d75 Michael Niedermayer
        }
2031 90ad92b3 Michael Niedermayer
        //only for the split stuff
2032
        if (!st->parser) {
2033 01f4895c Michael Niedermayer
            st->parser = av_parser_init(st->codec->codec_id);
2034 57004ff1 Aurelien Jacobs
            if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2035 7cbaa7ba Michael Niedermayer
                st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2036
            }
2037 90ad92b3 Michael Niedermayer
        }
2038 c0df9d75 Michael Niedermayer
    }
2039
2040 15bc38e5 Michael Niedermayer
    for(i=0;i<MAX_STREAMS;i++){
2041
        last_dts[i]= AV_NOPTS_VALUE;
2042
    }
2043 115329f1 Diego Biurrun
2044 b9a281db Fabrice Bellard
    count = 0;
2045
    read_size = 0;
2046
    for(;;) {
2047
        /* check if one codec still needs to be handled */
2048
        for(i=0;i<ic->nb_streams;i++) {
2049
            st = ic->streams[i];
2050 01f4895c Michael Niedermayer
            if (!has_codec_parameters(st->codec))
2051 b9a281db Fabrice Bellard
                break;
2052 3e76d1b5 Michael Niedermayer
            /* variable fps and no guess at the real fps */
2053 945208ca Michael Niedermayer
            if(   tb_unreliable(st->codec)
2054 01f4895c Michael Niedermayer
               && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)
2055 3e76d1b5 Michael Niedermayer
                break;
2056 01f4895c Michael Niedermayer
            if(st->parser && st->parser->parser->split && !st->codec->extradata)
2057 90ad92b3 Michael Niedermayer
                break;
2058 82583548 Michael Niedermayer
            if(st->first_dts == AV_NOPTS_VALUE)
2059
                break;
2060 b9a281db Fabrice Bellard
        }
2061
        if (i == ic->nb_streams) {
2062
            /* NOTE: if the format has no header, then we need to read
2063
               some packets to get most of the streams, so we cannot
2064
               stop here */
2065 fb2758c8 Fabrice Bellard
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2066 b9a281db Fabrice Bellard
                /* if we found the info for all the codecs, we can stop */
2067
                ret = count;
2068
                break;
2069
            }
2070 5fb83c38 Michael Niedermayer
        }
2071 35eab0c0 Michael Niedermayer
        /* we did not get all the codec info, but we read too much data */
2072
        if (read_size >= MAX_READ_SIZE) {
2073
            ret = count;
2074
            break;
2075
        }
2076 b9a281db Fabrice Bellard
2077 fb2758c8 Fabrice Bellard
        /* NOTE: a new stream can be added there if no header in file
2078
           (AVFMTCTX_NOHEADER) */
2079
        ret = av_read_frame_internal(ic, &pkt1);
2080
        if (ret < 0) {
2081
            /* EOF or error */
2082
            ret = -1; /* we could not have all the codec parameters before EOF */
2083 e19456e3 Michael Niedermayer
            for(i=0;i<ic->nb_streams;i++) {
2084
                st = ic->streams[i];
2085 305ee50f Michael Niedermayer
                if (!has_codec_parameters(st->codec)){
2086
                    char buf[256];
2087
                    avcodec_string(buf, sizeof(buf), st->codec, 0);
2088
                    av_log(ic, AV_LOG_INFO, "Could not find codec parameters (%s)\n", buf);
2089 344a18c3 Måns Rullgård
                } else {
2090
                    ret = 0;
2091 305ee50f Michael Niedermayer
                }
2092 e19456e3 Michael Niedermayer
            }
2093 fb2758c8 Fabrice Bellard
            break;
2094
        }
2095
2096 5c5b1731 Måns Rullgård
        pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
2097 be390a4e Erik Hovland
        if(av_dup_packet(pkt) < 0) {
2098
            av_free(duration_error);
2099 02b15cc8 Michael Niedermayer
            return AVERROR(ENOMEM);
2100 be390a4e Erik Hovland
        }
2101 b9a281db Fabrice Bellard
2102 fb2758c8 Fabrice Bellard
        read_size += pkt->size;
2103 b9a281db Fabrice Bellard
2104
        st = ic->streams[pkt->stream_index];
2105 ea486ab3 Baptiste Coudurier
        if(codec_info_nb_frames[st->index]>1)
2106
            codec_info_duration[st->index] += pkt->duration;
2107 fb2758c8 Fabrice Bellard
        if (pkt->duration != 0)
2108 ea486ab3 Baptiste Coudurier
            codec_info_nb_frames[st->index]++;
2109 fb2758c8 Fabrice Bellard
2110 cefe0607 Michael Niedermayer
        {
2111 3c150d16 Michael Niedermayer
            int index= pkt->stream_index;
2112
            int64_t last= last_dts[index];
2113
            int64_t duration= pkt->dts - last;
2114
2115
            if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
2116 4d43cbcc Michael Niedermayer
                double dur= duration * av_q2d(st->time_base);
2117
2118
//                if(st->codec->codec_type == CODEC_TYPE_VIDEO)
2119
//                    av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
2120 1694118b Michael Niedermayer
                if(duration_count[index] < 2)
2121 4c7981ba Baptiste Coudurier
                    memset(duration_error[index], 0, sizeof(*duration_error));
2122 69c262d1 Michael Niedermayer
                for(i=1; i<MAX_STD_TIMEBASES; i++){
2123
                    int framerate= get_std_framerate(i);
2124
                    int ticks= lrintf(dur*framerate/(1001*12));
2125
                    double error= dur - ticks*1001*12/(double)framerate;
2126
                    duration_error[index][i] += error*error;
2127
                }
2128 4d43cbcc Michael Niedermayer
                duration_count[index]++;
2129 15bc38e5 Michael Niedermayer
            }
2130 fd97f6a2 Michael Niedermayer
            if(last == AV_NOPTS_VALUE || duration_count[index]<=1)
2131
                last_dts[pkt->stream_index]= pkt->dts;
2132 15bc38e5 Michael Niedermayer
        }
2133 01f4895c Michael Niedermayer
        if(st->parser && st->parser->parser->split && !st->codec->extradata){
2134
            int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2135 90ad92b3 Michael Niedermayer
            if(i){
2136 01f4895c Michael Niedermayer
                st->codec->extradata_size= i;
2137 62c52121 Måns Rullgård
                st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2138 01f4895c Michael Niedermayer
                memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2139 62c52121 Måns Rullgård
                memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2140 90ad92b3 Michael Niedermayer
            }
2141
        }
2142 115329f1 Diego Biurrun
2143 fb2758c8 Fabrice Bellard
        /* if still no information, we try to open the codec and to
2144
           decompress the frame. We try to avoid that in most cases as
2145 a85736f2 Diego Biurrun
           it takes longer and uses more memory. For MPEG-4, we need to
2146
           decompress for QuickTime. */
2147 01f4895c Michael Niedermayer
        if (!has_codec_parameters(st->codec) /*&&
2148
            (st->codec->codec_id == CODEC_ID_FLV1 ||
2149
             st->codec->codec_id == CODEC_ID_H264 ||
2150
             st->codec->codec_id == CODEC_ID_H263 ||
2151
             st->codec->codec_id == CODEC_ID_H261 ||
2152
             st->codec->codec_id == CODEC_ID_VORBIS ||
2153
             st->codec->codec_id == CODEC_ID_MJPEG ||
2154
             st->codec->codec_id == CODEC_ID_PNG ||
2155
             st->codec->codec_id == CODEC_ID_PAM ||
2156
             st->codec->codec_id == CODEC_ID_PGM ||
2157
             st->codec->codec_id == CODEC_ID_PGMYUV ||
2158
             st->codec->codec_id == CODEC_ID_PBM ||
2159
             st->codec->codec_id == CODEC_ID_PPM ||
2160
             st->codec->codec_id == CODEC_ID_SHORTEN ||
2161
             (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
2162 fb2758c8 Fabrice Bellard
            try_decode_frame(st, pkt->data, pkt->size);
2163 115329f1 Diego Biurrun
2164 b3fc0925 Måns Rullgård
        if (st->time_base.den > 0 && av_rescale_q(codec_info_duration[st->index], st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
2165 fb2758c8 Fabrice Bellard
            break;
2166 b9a281db Fabrice Bellard
        }
2167
        count++;
2168
    }
2169
2170 bd107136 Diego Biurrun
    // close codecs which were opened in try_decode_frame()
2171 43c0040a Michael Niedermayer
    for(i=0;i<ic->nb_streams;i++) {
2172
        st = ic->streams[i];
2173 01f4895c Michael Niedermayer
        if(st->codec->codec)
2174
            avcodec_close(st->codec);
2175 43c0040a Michael Niedermayer
    }
2176 b9a281db Fabrice Bellard
    for(i=0;i<ic->nb_streams;i++) {
2177
        st = ic->streams[i];
2178 01f4895c Michael Niedermayer
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2179 dd1c8f3e Luca Abeni
            if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample)
2180 01f4895c Michael Niedermayer
                st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2181 15bc38e5 Michael Niedermayer
2182 1694118b Michael Niedermayer
            if(duration_count[i]
2183 945208ca Michael Niedermayer
               && tb_unreliable(st->codec) /*&&
2184 a85736f2 Diego Biurrun
               //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2185 4d43cbcc Michael Niedermayer
               st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den*/){
2186
                double best_error= 2*av_q2d(st->time_base);
2187
                best_error= best_error*best_error*duration_count[i]*1000*12*30;
2188
2189
                for(j=1; j<MAX_STD_TIMEBASES; j++){
2190
                    double error= duration_error[i][j] * get_std_framerate(j);
2191
//                    if(st->codec->codec_type == CODEC_TYPE_VIDEO)
2192
//                        av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
2193 9f75260e Michael Niedermayer
                    if(error < best_error){
2194
                        best_error= error;
2195 4d43cbcc Michael Niedermayer
                        av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, get_std_framerate(j), 12*1001, INT_MAX);
2196 9f75260e Michael Niedermayer
                    }
2197 3c150d16 Michael Niedermayer
                }
2198 15bc38e5 Michael Niedermayer
            }
2199
2200 c0df9d75 Michael Niedermayer
            if (!st->r_frame_rate.num){
2201 5523d5f4 Michael Niedermayer
                if(    st->codec->time_base.den * (int64_t)st->time_base.num
2202
                    <= st->codec->time_base.num * (int64_t)st->time_base.den){
2203
                    st->r_frame_rate.num = st->codec->time_base.den;
2204
                    st->r_frame_rate.den = st->codec->time_base.num;
2205
                }else{
2206
                    st->r_frame_rate.num = st->time_base.den;
2207
                    st->r_frame_rate.den = st->time_base.num;
2208
                }
2209 14bea432 Michael Niedermayer
            }
2210 a185f52a Michael Niedermayer
        }else if(st->codec->codec_type == CODEC_TYPE_AUDIO) {
2211 dd1c8f3e Luca Abeni
            if(!st->codec->bits_per_coded_sample)
2212
                st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2213 b9a281db Fabrice Bellard
        }
2214 de6d9b64 Fabrice Bellard
    }
2215 b9a281db Fabrice Bellard
2216 9ecf7fad Wolfram Gloger
    av_estimate_timings(ic, old_offset);
2217 6fea687e John Donaghy
2218 c2c3dedf Aurelien Jacobs
    compute_chapters_end(ic);
2219
2220 e928649b Michael Niedermayer
#if 0
2221 a85736f2 Diego Biurrun
    /* correct DTS for B-frame streams with no timestamps */
2222 e928649b Michael Niedermayer
    for(i=0;i<ic->nb_streams;i++) {
2223
        st = ic->streams[i];
2224 01f4895c Michael Niedermayer
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2225 e928649b Michael Niedermayer
            if(b-frames){
2226
                ppktl = &ic->packet_buffer;
2227
                while(ppkt1){
2228
                    if(ppkt1->stream_index != i)
2229
                        continue;
2230
                    if(ppkt1->pkt->dts < 0)
2231
                        break;
2232
                    if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2233
                        break;
2234
                    ppkt1->pkt->dts -= delta;
2235
                    ppkt1= ppkt1->next;
2236
                }
2237
                if(ppkt1)
2238
                    continue;
2239
                st->cur_dts -= delta;
2240
            }
2241
        }
2242
    }
2243
#endif
2244 0cbff027 Kristian Amlie
2245
    av_free(duration_error);
2246
2247 b9a281db Fabrice Bellard
    return ret;
2248 de6d9b64 Fabrice Bellard
}
2249
2250 fb2758c8 Fabrice Bellard
/*******************************************************/
2251
2252
int av_read_play(AVFormatContext *s)
2253
{
2254 fa13095a Björn Axelsson
    if (s->iformat->read_play)
2255
        return s->iformat->read_play(s);
2256 fd2982a0 Aurelien Jacobs
    if (s->pb)
2257 502bdf68 Michael Niedermayer
        return av_url_read_fpause(s->pb, 0);
2258 fa13095a Björn Axelsson
    return AVERROR(ENOSYS);
2259 fb2758c8 Fabrice Bellard
}
2260
2261
int av_read_pause(AVFormatContext *s)
2262
{
2263 fa13095a Björn Axelsson
    if (s->iformat->read_pause)
2264
        return s->iformat->read_pause(s);
2265 fd2982a0 Aurelien Jacobs
    if (s->pb)
2266 502bdf68 Michael Niedermayer
        return av_url_read_fpause(s->pb, 1);
2267 fa13095a Björn Axelsson
    return AVERROR(ENOSYS);
2268 fb2758c8 Fabrice Bellard
}
2269
2270 2506fd54 Reimar Döffinger
void av_close_input_stream(AVFormatContext *s)
2271 de6d9b64 Fabrice Bellard
{
2272 ca75a923 Reimar Döffinger
    int i;
2273 da24c5e3 Fabrice Bellard
    AVStream *st;
2274 de6d9b64 Fabrice Bellard
2275 fb2758c8 Fabrice Bellard
    /* free previous packet */
2276
    if (s->cur_st && s->cur_st->parser)
2277 115329f1 Diego Biurrun
        av_free_packet(&s->cur_pkt);
2278 fb2758c8 Fabrice Bellard
2279 b9a281db Fabrice Bellard
    if (s->iformat->read_close)
2280
        s->iformat->read_close(s);
2281 de6d9b64 Fabrice Bellard
    for(i=0;i<s->nb_streams;i++) {
2282 da24c5e3 Fabrice Bellard
        /* free all data in a stream component */
2283
        st = s->streams[i];
2284 fb2758c8 Fabrice Bellard
        if (st->parser) {
2285
            av_parser_close(st->parser);
2286 de6d9b64 Fabrice Bellard
        }
2287 fb2758c8 Fabrice Bellard
        av_free(st->index_entries);
2288 a5e9102b Måns Rullgård
        av_free(st->codec->extradata);
2289 01f4895c Michael Niedermayer
        av_free(st->codec);
2290 f8d7c9d3 Evgeniy Stepanov
        av_free(st->filename);
2291 ade8d8b9 Baptiste Coudurier
        av_free(st->priv_data);
2292 fb2758c8 Fabrice Bellard
        av_free(st);
2293 de6d9b64 Fabrice Bellard
    }
2294 15afa396 Nico Sabbi
    for(i=s->nb_programs-1; i>=0; i--) {
2295
        av_freep(&s->programs[i]->provider_name);
2296
        av_freep(&s->programs[i]->name);
2297 526efa10 Nico Sabbi
        av_freep(&s->programs[i]->stream_index);
2298 15afa396 Nico Sabbi
        av_freep(&s->programs[i]);
2299
    }
2300 ceedda75 Michael Niedermayer
    av_freep(&s->programs);
2301 fb2758c8 Fabrice Bellard
    flush_packet_queue(s);
2302 a8dbe951 Philip Gladstone
    av_freep(&s->priv_data);
2303 7c8202cc Michael Niedermayer
    while(s->nb_chapters--) {
2304
        av_free(s->chapters[s->nb_chapters]->title);
2305
        av_free(s->chapters[s->nb_chapters]);
2306 79d7836a Anton Khirnov
    }
2307
    av_freep(&s->chapters);
2308 1ea4f593 Fabrice Bellard
    av_free(s);
2309 de6d9b64 Fabrice Bellard
}
2310
2311 2506fd54 Reimar Döffinger
void av_close_input_file(AVFormatContext *s)
2312
{
2313
    ByteIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
2314
    av_close_input_stream(s);
2315
    if (pb)
2316
        url_fclose(pb);
2317
}
2318
2319 b9a281db Fabrice Bellard
AVStream *av_new_stream(AVFormatContext *s, int id)
2320
{
2321
    AVStream *st;
2322 504ee036 Michael Niedermayer
    int i;
2323 b9a281db Fabrice Bellard
2324
    if (s->nb_streams >= MAX_STREAMS)
2325
        return NULL;
2326
2327
    st = av_mallocz(sizeof(AVStream));
2328
    if (!st)
2329
        return NULL;
2330 115329f1 Diego Biurrun
2331 01f4895c Michael Niedermayer
    st->codec= avcodec_alloc_context();
2332 48091512 Fabrice Bellard
    if (s->iformat) {
2333
        /* no default bitrate if decoding */
2334 01f4895c Michael Niedermayer
        st->codec->bit_rate = 0;
2335 48091512 Fabrice Bellard
    }
2336 b9a281db Fabrice Bellard
    st->index = s->nb_streams;
2337
    st->id = id;
2338 12f996ed Fabrice Bellard
    st->start_time = AV_NOPTS_VALUE;
2339
    st->duration = AV_NOPTS_VALUE;
2340 6d77d9ac Michael Niedermayer
        /* we set the current DTS to 0 so that formats without any timestamps
2341
           but durations get some timestamps, formats with some unknown
2342
           timestamps have their first few packets buffered and the
2343
           timestamps corrected before they are returned to the user */
2344
    st->cur_dts = 0;
2345 82583548 Michael Niedermayer
    st->first_dts = AV_NOPTS_VALUE;
2346 9ee91c2f Michael Niedermayer
2347 a85736f2 Diego Biurrun
    /* default pts setting is MPEG-like */
2348 9ee91c2f Michael Niedermayer
    av_set_pts_info(st, 33, 1, 90000);
2349 635fbcb1 Michael Niedermayer
    st->last_IP_pts = AV_NOPTS_VALUE;
2350 504ee036 Michael Niedermayer
    for(i=0; i<MAX_REORDER_DELAY+1; i++)
2351
        st->pts_buffer[i]= AV_NOPTS_VALUE;
2352 9ee91c2f Michael Niedermayer
2353 c30a4489 Aurelien Jacobs
    st->sample_aspect_ratio = (AVRational){0,1};
2354
2355 b9a281db Fabrice Bellard
    s->streams[s->nb_streams++] = st;
2356
    return st;
2357
}
2358
2359 15afa396 Nico Sabbi
AVProgram *av_new_program(AVFormatContext *ac, int id)
2360
{
2361
    AVProgram *program=NULL;
2362
    int i;
2363
2364
#ifdef DEBUG_SI
2365
    av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id);
2366
#endif
2367
2368
    for(i=0; i<ac->nb_programs; i++)
2369
        if(ac->programs[i]->id == id)
2370
            program = ac->programs[i];
2371
2372
    if(!program){
2373
        program = av_mallocz(sizeof(AVProgram));
2374
        if (!program)
2375
            return NULL;
2376
        dynarray_add(&ac->programs, &ac->nb_programs, program);
2377
        program->discard = AVDISCARD_NONE;
2378
    }
2379
    program->id = id;
2380
2381
    return program;
2382
}
2383
2384
void av_set_program_name(AVProgram *program, char *provider_name, char *name)
2385
{
2386
    assert(!provider_name == !name);
2387
    if(name){
2388
        av_free(program->provider_name);
2389
        av_free(program->         name);
2390
        program->provider_name = av_strdup(provider_name);
2391
        program->         name = av_strdup(         name);
2392
    }
2393
}
2394
2395 abd2256d Michael Niedermayer
AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2396 79d7836a Anton Khirnov
{
2397 7a2a3e8e Michael Niedermayer
    AVChapter *chapter = NULL;
2398
    int i;
2399
2400 7c8202cc Michael Niedermayer
    for(i=0; i<s->nb_chapters; i++)
2401 7a2a3e8e Michael Niedermayer
        if(s->chapters[i]->id == id)
2402
            chapter = s->chapters[i];
2403
2404
    if(!chapter){
2405
        chapter= av_mallocz(sizeof(AVChapter));
2406 6b43e2c7 Michael Niedermayer
        if(!chapter)
2407 5c37f43a Michael Niedermayer
            return NULL;
2408 7c8202cc Michael Niedermayer
        dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2409 7a2a3e8e Michael Niedermayer
    }
2410 ebea1d76 Aurelien Jacobs
    av_free(chapter->title);
2411 42720ee4 Michael Niedermayer
    chapter->title = av_strdup(title);
2412 7a2a3e8e Michael Niedermayer
    chapter->id    = id;
2413 abd2256d Michael Niedermayer
    chapter->time_base= time_base;
2414 79d7836a Anton Khirnov
    chapter->start = start;
2415 747fb6c6 Michael Niedermayer
    chapter->end   = end;
2416 79d7836a Anton Khirnov
2417 5c37f43a Michael Niedermayer
    return chapter;
2418 79d7836a Anton Khirnov
}
2419 15afa396 Nico Sabbi
2420 b9a281db Fabrice Bellard
/************************************************************/
2421
/* output media file */
2422 de6d9b64 Fabrice Bellard
2423 87a0a681 Fabrice Bellard
int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2424
{
2425
    int ret;
2426 115329f1 Diego Biurrun
2427 98486a6b Roman Shaposhnik
    if (s->oformat->priv_data_size > 0) {
2428
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
2429
        if (!s->priv_data)
2430 769e10f0 Panagiotis Issaris
            return AVERROR(ENOMEM);
2431 98486a6b Roman Shaposhnik
    } else
2432
        s->priv_data = NULL;
2433 115329f1 Diego Biurrun
2434 87a0a681 Fabrice Bellard
    if (s->oformat->set_parameters) {
2435
        ret = s->oformat->set_parameters(s, ap);
2436
        if (ret < 0)
2437
            return ret;
2438
    }
2439
    return 0;
2440
}
2441
2442 b9a281db Fabrice Bellard
int av_write_header(AVFormatContext *s)
2443
{
2444 1e51d801 Fabrice Bellard
    int ret, i;
2445
    AVStream *st;
2446
2447 9450118b Michael Niedermayer
    // some sanity checks
2448
    for(i=0;i<s->nb_streams;i++) {
2449
        st = s->streams[i];
2450
2451
        switch (st->codec->codec_type) {
2452
        case CODEC_TYPE_AUDIO:
2453
            if(st->codec->sample_rate<=0){
2454
                av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2455
                return -1;
2456
            }
2457 bf912a48 Baptiste Coudurier
            if(!st->codec->block_align)
2458
                st->codec->block_align = st->codec->channels *
2459
                    av_get_bits_per_sample(st->codec->codec_id) >> 3;
2460 9450118b Michael Niedermayer
            break;
2461
        case CODEC_TYPE_VIDEO:
2462
            if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2463
                av_log(s, AV_LOG_ERROR, "time base not set\n");
2464
                return -1;
2465
            }
2466
            if(st->codec->width<=0 || st->codec->height<=0){
2467
                av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2468
                return -1;
2469
            }
2470 0354ddb7 Michael Niedermayer
            if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)){
2471
                av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");
2472
                return -1;
2473
            }
2474 9450118b Michael Niedermayer
            break;
2475
        }
2476 5ecfa9f5 Michael Niedermayer
2477
        if(s->oformat->codec_tag){
2478
            if(st->codec->codec_tag){
2479
                //FIXME
2480
                //check that tag + id is in the table
2481 a85736f2 Diego Biurrun
                //if neither is in the table -> OK
2482 5ecfa9f5 Michael Niedermayer
                //if tag is in the table with another id -> FAIL
2483
                //if id is in the table with another tag -> FAIL unless strict < ?
2484
            }else
2485
                st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
2486
        }
2487 9450118b Michael Niedermayer
    }
2488
2489 8fae2df5 Baptiste Coudurier
    if (!s->priv_data && s->oformat->priv_data_size > 0) {
2490 c6efa4b5 Baptiste Coudurier
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
2491
        if (!s->priv_data)
2492 769e10f0 Panagiotis Issaris
            return AVERROR(ENOMEM);
2493 8fae2df5 Baptiste Coudurier
    }
2494 c6efa4b5 Baptiste Coudurier
2495 31e11451 Michael Niedermayer
    if(s->oformat->write_header){
2496
        ret = s->oformat->write_header(s);
2497
        if (ret < 0)
2498
            return ret;
2499
    }
2500 1e51d801 Fabrice Bellard
2501
    /* init PTS generation */
2502
    for(i=0;i<s->nb_streams;i++) {
2503 f0ff20a1 Wolfram Gloger
        int64_t den = AV_NOPTS_VALUE;
2504 1e51d801 Fabrice Bellard
        st = s->streams[i];
2505
2506 01f4895c Michael Niedermayer
        switch (st->codec->codec_type) {
2507 1e51d801 Fabrice Bellard
        case CODEC_TYPE_AUDIO:
2508 f0ff20a1 Wolfram Gloger
            den = (int64_t)st->time_base.num * st->codec->sample_rate;
2509 1e51d801 Fabrice Bellard
            break;
2510
        case CODEC_TYPE_VIDEO:
2511 f0ff20a1 Wolfram Gloger
            den = (int64_t)st->time_base.num * st->codec->time_base.den;
2512 1e51d801 Fabrice Bellard
            break;
2513
        default:
2514
            break;
2515
        }
2516 f0ff20a1 Wolfram Gloger
        if (den != AV_NOPTS_VALUE) {
2517
            if (den <= 0)
2518
                return AVERROR_INVALIDDATA;
2519
            av_frac_init(&st->pts, 0, 0, den);
2520
        }
2521 1e51d801 Fabrice Bellard
    }
2522
    return 0;
2523 b9a281db Fabrice Bellard
}
2524
2525 3c895fc0 Michael Niedermayer
//FIXME merge with compute_pkt_fields
2526 5edea431 Michael Niedermayer
static int compute_pkt_fields2(AVStream *st, AVPacket *pkt){
2527 504ee036 Michael Niedermayer
    int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
2528
    int num, den, frame_size, i;
2529 b0c7f5a9 Michael Niedermayer
2530 949b1a13 Steve L'Homme
//    av_log(st->codec, AV_LOG_DEBUG, "av_write_frame: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
2531 115329f1 Diego Biurrun
2532 e928649b Michael Niedermayer
/*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2533
        return -1;*/
2534 115329f1 Diego Biurrun
2535 e928649b Michael Niedermayer
    /* duration field */
2536 3c895fc0 Michael Niedermayer
    if (pkt->duration == 0) {
2537
        compute_frame_duration(&num, &den, st, NULL, pkt);
2538
        if (den && num) {
2539
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
2540
        }
2541
    }
2542 e928649b Michael Niedermayer
2543 6e1aa0f3 Michael Niedermayer
    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
2544
        pkt->pts= pkt->dts;
2545
2546 e928649b Michael Niedermayer
    //XXX/FIXME this is a temporary hack until all encoders output pts
2547 504ee036 Michael Niedermayer
    if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
2548 e928649b Michael Niedermayer
        pkt->dts=
2549
//        pkt->pts= st->cur_dts;
2550
        pkt->pts= st->pts.val;
2551
    }
2552
2553 115329f1 Diego Biurrun
    //calculate dts from pts
2554 cb5b96cd Baptiste Coudurier
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
2555 504ee036 Michael Niedermayer
        st->pts_buffer[0]= pkt->pts;
2556
        for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
2557
            st->pts_buffer[i]= (i-delay-1) * pkt->duration;
2558
        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
2559 1345f4ed Diego Biurrun
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
2560 504ee036 Michael Niedermayer
2561
        pkt->dts= st->pts_buffer[0];
2562 e928649b Michael Niedermayer
    }
2563 115329f1 Diego Biurrun
2564 5edea431 Michael Niedermayer
    if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2565 15061147 Baptiste Coudurier
        av_log(st->codec, AV_LOG_ERROR, "error, non monotone timestamps %"PRId64" >= %"PRId64"\n", st->cur_dts, pkt->dts);
2566 5edea431 Michael Niedermayer
        return -1;
2567
    }
2568
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2569 15061147 Baptiste Coudurier
        av_log(st->codec, AV_LOG_ERROR, "error, pts < dts\n");
2570 5edea431 Michael Niedermayer
        return -1;
2571
    }
2572
2573 949b1a13 Steve L'Homme
//    av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
2574 e928649b Michael Niedermayer
    st->cur_dts= pkt->dts;
2575
    st->pts.val= pkt->dts;
2576
2577 1e51d801 Fabrice Bellard
    /* update pts */
2578 01f4895c Michael Niedermayer
    switch (st->codec->codec_type) {
2579 1e51d801 Fabrice Bellard
    case CODEC_TYPE_AUDIO:
2580 01f4895c Michael Niedermayer
        frame_size = get_audio_frame_size(st->codec, pkt->size);
2581 6d8f985e Michael Niedermayer
2582 a85736f2 Diego Biurrun
        /* HACK/FIXME, we skip the initial 0 size packets as they are most
2583
           likely equal to the encoder delay, but it would be better if we
2584
           had the real timestamps from the encoder */
2585 e928649b Michael Niedermayer
        if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2586 9ee91c2f Michael Niedermayer
            av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2587 7feb950a Fabrice Bellard
        }
2588 1e51d801 Fabrice Bellard
        break;
2589
    case CODEC_TYPE_VIDEO:
2590 01f4895c Michael Niedermayer
        av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
2591 1e51d801 Fabrice Bellard
        break;
2592
    default:
2593
        break;
2594
    }
2595 5edea431 Michael Niedermayer
    return 0;
2596 3c895fc0 Michael Niedermayer
}
2597
2598
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2599
{
2600 fc9c2d53 Ramiro Polla
    int ret = compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
2601 576ae256 Michael Niedermayer
2602 494bbf58 Michael Niedermayer
    if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2603 5edea431 Michael Niedermayer
        return ret;
2604 115329f1 Diego Biurrun
2605 576ae256 Michael Niedermayer
    ret= s->oformat->write_packet(s, pkt);
2606
    if(!ret)
2607 899681cd Björn Axelsson
        ret= url_ferror(s->pb);
2608 576ae256 Michael Niedermayer
    return ret;
2609 3c895fc0 Michael Niedermayer
}
2610
2611 f21c0b4c Baptiste Coudurier
int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2612 fe2d6fe2 Michael Niedermayer
    AVPacketList *pktl, **next_point, *this_pktl;
2613
    int stream_count=0;
2614
    int streams[MAX_STREAMS];
2615
2616
    if(pkt){
2617
        AVStream *st= s->streams[ pkt->stream_index];
2618
2619 2577897d Michael Niedermayer
//        assert(pkt->destruct != av_destruct_packet); //FIXME
2620 fe2d6fe2 Michael Niedermayer
2621
        this_pktl = av_mallocz(sizeof(AVPacketList));
2622
        this_pktl->pkt= *pkt;
2623 2577897d Michael Niedermayer
        if(pkt->destruct == av_destruct_packet)
2624 a85736f2 Diego Biurrun
            pkt->destruct= NULL; // not shared -> must keep original from being freed
2625 2577897d Michael Niedermayer
        else
2626
            av_dup_packet(&this_pktl->pkt);  //shared -> must dup
2627 fe2d6fe2 Michael Niedermayer
2628
        next_point = &s->packet_buffer;
2629
        while(*next_point){
2630
            AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
2631
            int64_t left=  st2->time_base.num * (int64_t)st ->time_base.den;
2632
            int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2633
            if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
2634
                break;
2635
            next_point= &(*next_point)->next;
2636
        }
2637
        this_pktl->next= *next_point;
2638
        *next_point= this_pktl;
2639
    }
2640 115329f1 Diego Biurrun
2641 fe2d6fe2 Michael Niedermayer
    memset(streams, 0, sizeof(streams));
2642
    pktl= s->packet_buffer;
2643
    while(pktl){
2644 949b1a13 Steve L'Homme
//av_log(s, AV_LOG_DEBUG, "show st:%d dts:%"PRId64"\n", pktl->pkt.stream_index, pktl->pkt.dts);
2645 fe2d6fe2 Michael Niedermayer
        if(streams[ pktl->pkt.stream_index ] == 0)
2646
            stream_count++;
2647
        streams[ pktl->pkt.stream_index ]++;
2648
        pktl= pktl->next;
2649
    }
2650 115329f1 Diego Biurrun
2651 6919e54c Art Clarke
    if(stream_count && (s->nb_streams == stream_count || flush)){
2652 fe2d6fe2 Michael Niedermayer
        pktl= s->packet_buffer;
2653
        *out= pktl->pkt;
2654 115329f1 Diego Biurrun
2655
        s->packet_buffer= pktl->next;
2656 fe2d6fe2 Michael Niedermayer
        av_freep(&pktl);
2657
        return 1;
2658
    }else{
2659
        av_init_packet(out);
2660
        return 0;
2661
    }
2662
}
2663
2664
/**
2665 a85736f2 Diego Biurrun
 * Interleaves an AVPacket correctly so it can be muxed.
2666 fe2d6fe2 Michael Niedermayer
 * @param out the interleaved packet will be output here
2667
 * @param in the input packet
2668
 * @param flush 1 if no further packets are available as input and all
2669
 *              remaining packets should be output
2670 115329f1 Diego Biurrun
 * @return 1 if a packet was output, 0 if no packet could be output,
2671 d9526386 Diego Biurrun
 *         < 0 if an error occurred
2672 fe2d6fe2 Michael Niedermayer
 */
2673
static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2674
    if(s->oformat->interleave_packet)
2675
        return s->oformat->interleave_packet(s, out, in, flush);
2676
    else
2677
        return av_interleave_packet_per_dts(s, out, in, flush);
2678
}
2679
2680 3c895fc0 Michael Niedermayer
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2681
    AVStream *st= s->streams[ pkt->stream_index];
2682
2683 6f824977 Michael Niedermayer
    //FIXME/XXX/HACK drop zero sized packets
2684 01f4895c Michael Niedermayer
    if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
2685 6f824977 Michael Niedermayer
        return 0;
2686 3ce16b30 Michael Niedermayer
2687 949b1a13 Steve L'Homme
//av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %"PRId64" %"PRId64"\n", pkt->size, pkt->dts, pkt->pts);
2688 494bbf58 Michael Niedermayer
    if(compute_pkt_fields2(st, pkt) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2689 3ce16b30 Michael Niedermayer
        return -1;
2690 115329f1 Diego Biurrun
2691 3c895fc0 Michael Niedermayer
    if(pkt->dts == AV_NOPTS_VALUE)
2692
        return -1;
2693
2694 fe2d6fe2 Michael Niedermayer
    for(;;){
2695
        AVPacket opkt;
2696
        int ret= av_interleave_packet(s, &opkt, pkt, 0);
2697
        if(ret<=0) //FIXME cleanup needed for ret<0 ?
2698
            return ret;
2699 115329f1 Diego Biurrun
2700 fe2d6fe2 Michael Niedermayer
        ret= s->oformat->write_packet(s, &opkt);
2701 115329f1 Diego Biurrun
2702 fe2d6fe2 Michael Niedermayer
        av_free_packet(&opkt);
2703
        pkt= NULL;
2704 115329f1 Diego Biurrun
2705 3c895fc0 Michael Niedermayer
        if(ret<0)
2706
            return ret;
2707 899681cd Björn Axelsson
        if(url_ferror(s->pb))
2708
            return url_ferror(s->pb);
2709 3c895fc0 Michael Niedermayer
    }
2710 b9a281db Fabrice Bellard
}
2711
2712
int av_write_trailer(AVFormatContext *s)
2713
{
2714 c40a3a42 Michael Niedermayer
    int ret, i;
2715 115329f1 Diego Biurrun
2716 fe2d6fe2 Michael Niedermayer
    for(;;){
2717
        AVPacket pkt;
2718
        ret= av_interleave_packet(s, &pkt, NULL, 1);
2719
        if(ret<0) //FIXME cleanup needed for ret<0 ?
2720 c40a3a42 Michael Niedermayer
            goto fail;
2721 fe2d6fe2 Michael Niedermayer
        if(!ret)
2722
            break;
2723 115329f1 Diego Biurrun
2724 fe2d6fe2 Michael Niedermayer
        ret= s->oformat->write_packet(s, &pkt);
2725 115329f1 Diego Biurrun
2726 fe2d6fe2 Michael Niedermayer
        av_free_packet(&pkt);
2727 115329f1 Diego Biurrun
2728 3c895fc0 Michael Niedermayer
        if(ret<0)
2729 c40a3a42 Michael Niedermayer
            goto fail;
2730 899681cd Björn Axelsson
        if(url_ferror(s->pb))
2731 576ae256 Michael Niedermayer
            goto fail;
2732 3c895fc0 Michael Niedermayer
    }
2733
2734 31e11451 Michael Niedermayer
    if(s->oformat->write_trailer)
2735
        ret = s->oformat->write_trailer(s);
2736 c40a3a4