Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ 5f8e0227

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

1410
    if (stream_index < 0)
1411
        return -1;
1412

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