~ubuntu-branches/ubuntu/jaunty/xvidcap/jaunty-proposed

« back to all changes in this revision

Viewing changes to ffmpeg/libavformat/utils.c

  • Committer: Bazaar Package Importer
  • Author(s): Lionel Le Folgoc, Andrew Starr-Bochicchio, Lionel Le Folgoc
  • Date: 2008-12-26 00:10:06 UTC
  • mfrom: (1.1.2 upstream)
  • Revision ID: james.westby@ubuntu.com-20081226001006-2040ls9680bd1blt
Tags: 1.1.7-0.2ubuntu1
[ Andrew Starr-Bochicchio ]
* Merge from debian-multimedia (LP: #298547), Ubuntu Changes:
 - For ffmpeg-related build-deps, fix versionized dependencies
   as the ubuntu versioning is different than debian-multimedia's.

[ Lionel Le Folgoc ]
* LP: #311412 is fixed since the 1.1.7~rc1-0.1 revision.
* debian/patches/03_ffmpeg.diff: updated to fix FTBFS due to libswscale API
  change (cherry-pick from Gentoo #234383).

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/*
2
 
 * Various utilities for ffmpeg system
 
2
 * various utility functions for use within FFmpeg
3
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4
4
 *
5
5
 * This file is part of FFmpeg.
19
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
20
 */
21
21
#include "avformat.h"
22
 
#include "allformats.h"
23
22
#include "opt.h"
 
23
#include "avstring.h"
 
24
#include "riff.h"
 
25
#include <sys/time.h>
 
26
#include <time.h>
24
27
 
25
28
#undef NDEBUG
26
29
#include <assert.h>
27
30
 
28
31
/**
29
32
 * @file libavformat/utils.c
30
 
 * Various utility functions for using ffmpeg library.
 
33
 * various utility functions for use within FFmpeg
31
34
 */
32
35
 
33
36
static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den);
34
37
static void av_frac_add(AVFrac *f, int64_t incr);
35
38
 
36
 
/** head of registered input format linked list. */
 
39
/** head of registered input format linked list */
37
40
AVInputFormat *first_iformat = NULL;
38
 
/** head of registered output format linked list. */
 
41
/** head of registered output format linked list */
39
42
AVOutputFormat *first_oformat = NULL;
40
43
 
 
44
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
 
41
56
void av_register_input_format(AVInputFormat *format)
42
57
{
43
58
    AVInputFormat **p;
97
112
        return guess_format("image2", NULL, NULL);
98
113
    }
99
114
#endif
100
 
    /* find the proper file type */
 
115
    /* Find the proper file type. */
101
116
    fmt_found = NULL;
102
117
    score_max = 0;
103
118
    fmt = first_oformat;
139
154
    return fmt;
140
155
}
141
156
 
142
 
/**
143
 
 * Guesses the codec id based upon muxer and filename.
144
 
 */
145
157
enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
146
158
                            const char *filename, const char *mime_type, enum CodecType type){
147
159
    if(type == CODEC_TYPE_VIDEO){
161
173
        return CODEC_ID_NONE;
162
174
}
163
175
 
164
 
/**
165
 
 * finds AVInputFormat based on input format's short name.
166
 
 */
167
176
AVInputFormat *av_find_input_format(const char *short_name)
168
177
{
169
178
    AVInputFormat *fmt;
176
185
 
177
186
/* memory handling */
178
187
 
179
 
/**
180
 
 * Default packet destructor.
181
 
 */
182
188
void av_destruct_packet(AVPacket *pkt)
183
189
{
184
190
    av_free(pkt->data);
185
191
    pkt->data = NULL; pkt->size = 0;
186
192
}
187
193
 
188
 
/**
189
 
 * Allocate the payload of a packet and intialized its fields to default values.
190
 
 *
191
 
 * @param pkt packet
192
 
 * @param size wanted payload size
193
 
 * @return 0 if OK. AVERROR_xxx otherwise.
194
 
 */
 
194
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
 
195
205
int av_new_packet(AVPacket *pkt, int size)
196
206
{
197
207
    uint8_t *data;
198
208
    if((unsigned)size > (unsigned)size + FF_INPUT_BUFFER_PADDING_SIZE)
199
 
        return AVERROR_NOMEM;
 
209
        return AVERROR(ENOMEM);
200
210
    data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
201
211
    if (!data)
202
 
        return AVERROR_NOMEM;
 
212
        return AVERROR(ENOMEM);
203
213
    memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
204
214
 
205
215
    av_init_packet(pkt);
209
219
    return 0;
210
220
}
211
221
 
212
 
/**
213
 
 * Allocate and read the payload of a packet and intialized its fields to default values.
214
 
 *
215
 
 * @param pkt packet
216
 
 * @param size wanted payload size
217
 
 * @return >0 (read size) if OK. AVERROR_xxx otherwise.
218
 
 */
219
222
int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
220
223
{
221
224
    int ret= av_new_packet(pkt, size);
234
237
    return ret;
235
238
}
236
239
 
237
 
/* This is a hack - the packet memory allocation stuff is broken. The
238
 
   packet is allocated if it was not really allocated */
239
240
int av_dup_packet(AVPacket *pkt)
240
241
{
241
242
    if (pkt->destruct != av_destruct_packet) {
242
243
        uint8_t *data;
243
 
        /* we duplicate the packet and don't forget to put the padding
244
 
           again */
 
244
        /* We duplicate the packet and don't forget to add the padding again. */
245
245
        if((unsigned)pkt->size > (unsigned)pkt->size + FF_INPUT_BUFFER_PADDING_SIZE)
246
 
            return AVERROR_NOMEM;
 
246
            return AVERROR(ENOMEM);
247
247
        data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
248
248
        if (!data) {
249
 
            return AVERROR_NOMEM;
 
249
            return AVERROR(ENOMEM);
250
250
        }
251
251
        memcpy(data, pkt->data, pkt->size);
252
252
        memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
256
256
    return 0;
257
257
}
258
258
 
259
 
/**
260
 
 * Check whether filename actually is a numbered sequence generator.
261
 
 *
262
 
 * @param filename possible numbered sequence string
263
 
 * @return 1 if a valid numbered sequence string, 0 otherwise.
264
 
 */
265
259
int av_filename_number_test(const char *filename)
266
260
{
267
261
    char buf[1024];
268
262
    return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
269
263
}
270
264
 
271
 
/**
272
 
 * Guess file format.
273
 
 *
274
 
 * @param is_opened whether the file is already opened, determines whether
275
 
 *                  demuxers with or without AVFMT_NOFILE are probed
276
 
 */
277
 
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
 
265
static AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
278
266
{
279
267
    AVInputFormat *fmt1, *fmt;
280
 
    int score, score_max;
 
268
    int score;
281
269
 
282
270
    fmt = NULL;
283
 
    score_max = 0;
284
271
    for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
285
272
        if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
286
273
            continue;
292
279
                score = 50;
293
280
            }
294
281
        }
295
 
        if (score > score_max) {
296
 
            score_max = score;
 
282
        if (score > *score_max) {
 
283
            *score_max = score;
297
284
            fmt = fmt1;
298
 
        }
 
285
        }else if (score == *score_max)
 
286
            fmt = NULL;
299
287
    }
300
288
    return fmt;
301
289
}
302
290
 
 
291
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
 
303
296
/************************************************************/
304
297
/* input media file */
305
298
 
315
308
}
316
309
 
317
310
#define OFFSET(x) offsetof(AVFormatContext,x)
318
 
#define DEFAULT 0 //should be NAN but it doesnt work as its not a constant in glibc as required by ANSI/ISO C
 
311
#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
319
312
//these names are too long to be readable
320
313
#define E AV_OPT_FLAG_ENCODING_PARAM
321
314
#define D AV_OPT_FLAG_DECODING_PARAM
329
322
{"genpts", "generate pts", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_GENPTS, INT_MIN, INT_MAX, D, "fflags"},
330
323
{"track", " set the track number", OFFSET(track), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
331
324
{"year", "set the year", OFFSET(year), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, E},
332
 
{"analyzeduration", NULL, OFFSET(max_analyze_duration), FF_OPT_TYPE_INT, 3*AV_TIME_BASE, 0, INT_MAX, D},
 
325
{"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},
 
326
{"cryptokey", "decryption key", OFFSET(key), FF_OPT_TYPE_BINARY, 0, 0, 0, D},
 
327
{"indexmem", "max memory used for timestamp index (per stream)", OFFSET(max_index_size), FF_OPT_TYPE_INT, 1<<20, 0, INT_MAX, D},
 
328
{"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 */
333
329
{NULL},
334
330
};
335
331
 
358
354
    return ic;
359
355
}
360
356
 
361
 
/**
362
 
 * Allocates all the structures needed to read an input stream.
363
 
 *        This does not open the needed codecs for decoding the stream[s].
364
 
 */
365
357
int av_open_input_stream(AVFormatContext **ic_ptr,
366
358
                         ByteIOContext *pb, const char *filename,
367
359
                         AVInputFormat *fmt, AVFormatParameters *ap)
380
372
    else
381
373
        ic = *ic_ptr;
382
374
    if (!ic) {
383
 
        err = AVERROR_NOMEM;
 
375
        err = AVERROR(ENOMEM);
384
376
        goto fail;
385
377
    }
386
378
    ic->iformat = fmt;
387
 
    if (pb)
388
 
        ic->pb = *pb;
 
379
    ic->pb = pb;
389
380
    ic->duration = AV_NOPTS_VALUE;
390
381
    ic->start_time = AV_NOPTS_VALUE;
391
 
    pstrcpy(ic->filename, sizeof(ic->filename), filename);
 
382
    av_strlcpy(ic->filename, filename, sizeof(ic->filename));
392
383
 
393
384
    /* allocate private data */
394
385
    if (fmt->priv_data_size > 0) {
395
386
        ic->priv_data = av_mallocz(fmt->priv_data_size);
396
387
        if (!ic->priv_data) {
397
 
            err = AVERROR_NOMEM;
 
388
            err = AVERROR(ENOMEM);
398
389
            goto fail;
399
390
        }
400
391
    } else {
406
397
        goto fail;
407
398
 
408
399
    if (pb && !ic->data_offset)
409
 
        ic->data_offset = url_ftell(&ic->pb);
 
400
        ic->data_offset = url_ftell(ic->pb);
410
401
 
411
402
    *ic_ptr = ic;
412
403
    return 0;
419
410
    return err;
420
411
}
421
412
 
422
 
/** Size of probe buffer, for guessing file type from file contents. */
 
413
/** size of probe buffer, for guessing file type from file contents */
423
414
#define PROBE_BUF_MIN 2048
424
415
#define PROBE_BUF_MAX (1<<20)
425
416
 
426
 
/**
427
 
 * Open a media file as input. The codec are not opened. Only the file
428
 
 * header (if present) is read.
429
 
 *
430
 
 * @param ic_ptr the opened media file handle is put here
431
 
 * @param filename filename to open.
432
 
 * @param fmt if non NULL, force the file format to use
433
 
 * @param buf_size optional buffer size (zero if default is OK)
434
 
 * @param ap additionnal parameters needed when opening the file (NULL if default)
435
 
 * @return 0 if OK. AVERROR_xxx otherwise.
436
 
 */
437
417
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
438
418
                       AVInputFormat *fmt,
439
419
                       int buf_size,
440
420
                       AVFormatParameters *ap)
441
421
{
442
 
    int err, must_open_file, file_opened, probe_size;
 
422
    int err, probe_size;
443
423
    AVProbeData probe_data, *pd = &probe_data;
444
 
    ByteIOContext pb1, *pb = &pb1;
 
424
    ByteIOContext *pb = NULL;
445
425
 
446
 
    file_opened = 0;
447
426
    pd->filename = "";
448
427
    if (filename)
449
428
        pd->filename = filename;
451
430
    pd->buf_size = 0;
452
431
 
453
432
    if (!fmt) {
454
 
        /* guess format if no file can be opened  */
 
433
        /* guess format if no file can be opened */
455
434
        fmt = av_probe_input_format(pd, 0);
456
435
    }
457
436
 
458
 
    /* do not open file if the format does not need it. XXX: specific
 
437
    /* Do not open file if the format does not need it. XXX: specific
459
438
       hack needed to handle RTSP/TCP */
460
 
    must_open_file = 1;
461
 
    if (fmt && (fmt->flags & AVFMT_NOFILE)) {
462
 
        must_open_file = 0;
463
 
        pb= NULL; //FIXME this or memset(pb, 0, sizeof(ByteIOContext)); otherwise its uninitalized
464
 
    }
465
 
 
466
 
    if (!fmt || must_open_file) {
 
439
    if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
467
440
        /* if no file needed do not try to open one */
468
 
        if (url_fopen(pb, filename, URL_RDONLY) < 0) {
469
 
            err = AVERROR_IO;
 
441
        if ((err=url_fopen(&pb, filename, URL_RDONLY)) < 0) {
470
442
            goto fail;
471
443
        }
472
 
        file_opened = 1;
473
444
        if (buf_size > 0) {
474
445
            url_setbufsize(pb, buf_size);
475
446
        }
476
447
 
477
448
        for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
 
449
            int score= probe_size < PROBE_BUF_MAX ? AVPROBE_SCORE_MAX/4 : 0;
478
450
            /* read probe data */
479
 
            pd->buf= av_realloc(pd->buf, probe_size);
 
451
            pd->buf= av_realloc(pd->buf, probe_size + AVPROBE_PADDING_SIZE);
480
452
            pd->buf_size = get_buffer(pb, pd->buf, probe_size);
 
453
            memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
481
454
            if (url_fseek(pb, 0, SEEK_SET) < 0) {
482
455
                url_fclose(pb);
483
 
                if (url_fopen(pb, filename, URL_RDONLY) < 0) {
484
 
                    file_opened = 0;
485
 
                    err = AVERROR_IO;
 
456
                if (url_fopen(&pb, filename, URL_RDONLY) < 0) {
 
457
                    pb = NULL;
 
458
                    err = AVERROR(EIO);
486
459
                    goto fail;
487
460
                }
488
461
            }
489
462
            /* guess file format */
490
 
            fmt = av_probe_input_format(pd, 1);
 
463
            fmt = av_probe_input_format2(pd, 1, &score);
491
464
        }
492
465
        av_freep(&pd->buf);
493
466
    }
498
471
        goto fail;
499
472
    }
500
473
 
501
 
    /* XXX: suppress this hack for redirectors */
502
 
#ifdef CONFIG_NETWORK
503
 
    if (fmt == &redir_demuxer) {
504
 
        err = redir_open(ic_ptr, pb);
505
 
        url_fclose(pb);
506
 
        return err;
507
 
    }
508
 
#endif
509
 
 
510
 
    /* check filename in case of an image number is expected */
 
474
    /* check filename in case an image number is expected */
511
475
    if (fmt->flags & AVFMT_NEEDNUMBER) {
512
476
        if (!av_filename_number_test(filename)) {
513
477
            err = AVERROR_NUMEXPECTED;
520
484
    return 0;
521
485
 fail:
522
486
    av_freep(&pd->buf);
523
 
    if (file_opened)
 
487
    if (pb)
524
488
        url_fclose(pb);
525
489
    *ic_ptr = NULL;
526
490
    return err;
529
493
 
530
494
/*******************************************************/
531
495
 
532
 
/**
533
 
 * Read a transport packet from a media file.
534
 
 *
535
 
 * This function is absolete and should never be used.
536
 
 * Use av_read_frame() instead.
537
 
 *
538
 
 * @param s media file handle
539
 
 * @param pkt is filled
540
 
 * @return 0 if OK. AVERROR_xxx if error.
541
 
 */
542
496
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
543
497
{
544
 
    return s->iformat->read_packet(s, pkt);
 
498
    int ret;
 
499
    AVStream *st;
 
500
    av_init_packet(pkt);
 
501
    ret= s->iformat->read_packet(s, pkt);
 
502
    if (ret < 0)
 
503
        return ret;
 
504
    st= s->streams[pkt->stream_index];
 
505
 
 
506
    switch(st->codec->codec_type){
 
507
    case CODEC_TYPE_VIDEO:
 
508
        if(s->video_codec_id)   st->codec->codec_id= s->video_codec_id;
 
509
        break;
 
510
    case CODEC_TYPE_AUDIO:
 
511
        if(s->audio_codec_id)   st->codec->codec_id= s->audio_codec_id;
 
512
        break;
 
513
    case CODEC_TYPE_SUBTITLE:
 
514
        if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
 
515
        break;
 
516
    }
 
517
 
 
518
    return ret;
545
519
}
546
520
 
547
521
/**********************************************************/
548
522
 
549
523
/**
550
 
 * Get the number of samples of an audio frame. Return (-1) if error.
 
524
 * Get the number of samples of an audio frame. Return -1 on error.
551
525
 */
552
526
static int get_audio_frame_size(AVCodecContext *enc, int size)
553
527
{
574
548
 
575
549
 
576
550
/**
577
 
 * Return the frame duration in seconds, return 0 if not available.
 
551
 * Return the frame duration in seconds. Return 0 if not available.
578
552
 */
579
553
static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
580
554
                                   AVCodecParserContext *pc, AVPacket *pkt)
631
605
    return 0;
632
606
}
633
607
 
634
 
static int64_t lsb2full(int64_t lsb, int64_t last_ts, int lsb_bits){
635
 
    int64_t mask = lsb_bits < 64 ? (1LL<<lsb_bits)-1 : -1LL;
636
 
    int64_t delta= last_ts - mask/2;
637
 
    return  ((lsb - delta)&mask) + delta;
 
608
static void update_initial_timestamps(AVFormatContext *s, int stream_index,
 
609
                                      int64_t dts, int64_t pts)
 
610
{
 
611
    AVStream *st= s->streams[stream_index];
 
612
    AVPacketList *pktl= s->packet_buffer;
 
613
 
 
614
    if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE)
 
615
        return;
 
616
 
 
617
    st->first_dts= dts - st->cur_dts;
 
618
    st->cur_dts= dts;
 
619
 
 
620
    for(; pktl; pktl= pktl->next){
 
621
        if(pktl->pkt.stream_index != stream_index)
 
622
            continue;
 
623
        //FIXME think more about this check
 
624
        if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
 
625
            pktl->pkt.pts += st->first_dts;
 
626
 
 
627
        if(pktl->pkt.dts != AV_NOPTS_VALUE)
 
628
            pktl->pkt.dts += st->first_dts;
 
629
 
 
630
        if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
 
631
            st->start_time= pktl->pkt.pts;
 
632
    }
 
633
    if (st->start_time == AV_NOPTS_VALUE)
 
634
        st->start_time = pts;
 
635
}
 
636
 
 
637
static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
 
638
{
 
639
    AVPacketList *pktl= s->packet_buffer;
 
640
 
 
641
    assert(pkt->duration && !st->cur_dts);
 
642
 
 
643
    for(; pktl; pktl= pktl->next){
 
644
        if(pktl->pkt.stream_index != pkt->stream_index)
 
645
            continue;
 
646
        if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
 
647
           && !pktl->pkt.duration){
 
648
            pktl->pkt.pts= pktl->pkt.dts= st->cur_dts;
 
649
            st->cur_dts += pkt->duration;
 
650
            pktl->pkt.duration= pkt->duration;
 
651
        }else
 
652
            break;
 
653
    }
638
654
}
639
655
 
640
656
static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
641
657
                               AVCodecParserContext *pc, AVPacket *pkt)
642
658
{
643
 
    int num, den, presentation_delayed;
644
 
    /* handle wrapping */
645
 
    if(st->cur_dts != AV_NOPTS_VALUE){
 
659
    int num, den, presentation_delayed, delay, i;
 
660
    int64_t offset;
 
661
 
 
662
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
 
663
       /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
 
664
        pkt->dts -= 1LL<<st->pts_wrap_bits;
 
665
    }
 
666
 
 
667
    if (pkt->duration == 0) {
 
668
        compute_frame_duration(&num, &den, st, pc, pkt);
 
669
        if (den && num) {
 
670
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
 
671
 
 
672
            if(st->cur_dts == 0 && pkt->duration != 0)
 
673
                update_initial_durations(s, st, pkt);
 
674
        }
 
675
    }
 
676
 
 
677
    /* correct timestamps with byte offset if demuxers only have timestamps
 
678
       on packet boundaries */
 
679
    if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
 
680
        /* this will estimate bitrate based on this frame's duration and size */
 
681
        offset = av_rescale(pc->offset, pkt->duration, pkt->size);
646
682
        if(pkt->pts != AV_NOPTS_VALUE)
647
 
            pkt->pts= lsb2full(pkt->pts, st->cur_dts, st->pts_wrap_bits);
 
683
            pkt->pts += offset;
648
684
        if(pkt->dts != AV_NOPTS_VALUE)
649
 
            pkt->dts= lsb2full(pkt->dts, st->cur_dts, st->pts_wrap_bits);
650
 
    }
651
 
 
652
 
    if (pkt->duration == 0) {
653
 
        compute_frame_duration(&num, &den, st, pc, pkt);
654
 
        if (den && num) {
655
 
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
656
 
        }
657
 
    }
658
 
 
659
 
    if(is_intra_only(st->codec))
660
 
        pkt->flags |= PKT_FLAG_KEY;
661
 
 
662
 
    /* do we have a video B frame ? */
 
685
            pkt->dts += offset;
 
686
    }
 
687
 
 
688
    /* do we have a video B-frame ? */
 
689
    delay= st->codec->has_b_frames;
663
690
    presentation_delayed = 0;
664
 
    if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
665
 
        /* XXX: need has_b_frame, but cannot get it if the codec is
666
 
           not initialized */
667
 
        if ((   st->codec->codec_id == CODEC_ID_H264
668
 
             || st->codec->has_b_frames) &&
669
 
            pc && pc->pict_type != FF_B_TYPE)
670
 
            presentation_delayed = 1;
671
 
        /* this may be redundant, but it shouldnt hurt */
672
 
        if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
673
 
            presentation_delayed = 1;
674
 
    }
 
691
    /* XXX: need has_b_frame, but cannot get it if the codec is
 
692
        not initialized */
 
693
    if (delay &&
 
694
        pc && pc->pict_type != FF_B_TYPE)
 
695
        presentation_delayed = 1;
 
696
    /* This may be redundant, but it should not hurt. */
 
697
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
 
698
        presentation_delayed = 1;
675
699
 
676
700
    if(st->cur_dts == AV_NOPTS_VALUE){
677
 
        if(presentation_delayed) st->cur_dts = -pkt->duration;
678
 
        else                     st->cur_dts = 0;
 
701
        st->cur_dts = 0; //FIXME maybe set it to 0 during init
679
702
    }
680
703
 
681
704
//    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);
682
705
    /* interpolate PTS and DTS if they are not present */
683
 
    if (presentation_delayed) {
684
 
        /* DTS = decompression time stamp */
685
 
        /* PTS = presentation time stamp */
686
 
        if (pkt->dts == AV_NOPTS_VALUE) {
687
 
            /* if we know the last pts, use it */
688
 
            if(st->last_IP_pts != AV_NOPTS_VALUE)
689
 
                st->cur_dts = pkt->dts = st->last_IP_pts;
690
 
            else
 
706
    if(delay <=1){
 
707
        if (presentation_delayed) {
 
708
            /* DTS = decompression timestamp */
 
709
            /* PTS = presentation timestamp */
 
710
            if (pkt->dts == AV_NOPTS_VALUE)
 
711
                pkt->dts = st->last_IP_pts;
 
712
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
 
713
            if (pkt->dts == AV_NOPTS_VALUE)
691
714
                pkt->dts = st->cur_dts;
692
 
        } else {
693
 
            st->cur_dts = pkt->dts;
694
 
        }
695
 
        /* this is tricky: the dts must be incremented by the duration
696
 
           of the frame we are displaying, i.e. the last I or P frame */
697
 
        if (st->last_IP_duration == 0)
698
 
            st->cur_dts += pkt->duration;
699
 
        else
700
 
            st->cur_dts += st->last_IP_duration;
701
 
        st->last_IP_duration  = pkt->duration;
702
 
        st->last_IP_pts= pkt->pts;
703
 
        /* cannot compute PTS if not present (we can compute it only
704
 
           by knowing the futur */
705
 
    } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
706
 
        if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
707
 
            int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
708
 
            int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
709
 
            if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
710
 
                pkt->pts += pkt->duration;
711
 
//                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);
 
715
 
 
716
            /* this is tricky: the dts must be incremented by the duration
 
717
            of the frame we are displaying, i.e. the last I- or P-frame */
 
718
            if (st->last_IP_duration == 0)
 
719
                st->last_IP_duration = pkt->duration;
 
720
            st->cur_dts = pkt->dts + st->last_IP_duration;
 
721
            st->last_IP_duration  = pkt->duration;
 
722
            st->last_IP_pts= pkt->pts;
 
723
            /* cannot compute PTS if not present (we can compute it only
 
724
            by knowing the future */
 
725
        } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
 
726
            if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
 
727
                int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
 
728
                int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
 
729
                if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
 
730
                    pkt->pts += pkt->duration;
 
731
    //                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);
 
732
                }
712
733
            }
713
 
        }
714
734
 
715
 
        /* presentation is not delayed : PTS and DTS are the same */
716
 
        if (pkt->pts == AV_NOPTS_VALUE) {
717
 
            if (pkt->dts == AV_NOPTS_VALUE) {
 
735
            /* presentation is not delayed : PTS and DTS are the same */
 
736
            if(pkt->pts == AV_NOPTS_VALUE)
 
737
                pkt->pts = pkt->dts;
 
738
            update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
 
739
            if(pkt->pts == AV_NOPTS_VALUE)
718
740
                pkt->pts = st->cur_dts;
719
 
                pkt->dts = st->cur_dts;
720
 
            }
721
 
            else {
722
 
                st->cur_dts = pkt->dts;
723
 
                pkt->pts = pkt->dts;
724
 
            }
725
 
        } else {
726
 
            st->cur_dts = pkt->pts;
727
741
            pkt->dts = pkt->pts;
728
 
        }
729
 
        st->cur_dts += pkt->duration;
730
 
    }
731
 
//    av_log(NULL, AV_LOG_DEBUG, "OUTdelayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts);
 
742
            st->cur_dts = pkt->pts + pkt->duration;
 
743
        }
 
744
    }
 
745
 
 
746
    if(pkt->pts != AV_NOPTS_VALUE){
 
747
        st->pts_buffer[0]= pkt->pts;
 
748
        for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
 
749
            st->pts_buffer[i]= (i-delay-1) * pkt->duration;
 
750
        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
 
751
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
 
752
        if(pkt->dts == AV_NOPTS_VALUE)
 
753
            pkt->dts= st->pts_buffer[0];
 
754
        if(delay>1){
 
755
            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
 
756
        }
 
757
        if(pkt->dts > st->cur_dts)
 
758
            st->cur_dts = pkt->dts;
 
759
    }
 
760
 
 
761
//    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);
732
762
 
733
763
    /* update flags */
734
 
    if (pc) {
 
764
    if(is_intra_only(st->codec))
 
765
        pkt->flags |= PKT_FLAG_KEY;
 
766
    else if (pc) {
735
767
        pkt->flags = 0;
736
 
        /* key frame computation */
737
 
        switch(st->codec->codec_type) {
738
 
        case CODEC_TYPE_VIDEO:
 
768
        /* keyframe computation */
739
769
            if (pc->pict_type == FF_I_TYPE)
740
770
                pkt->flags |= PKT_FLAG_KEY;
741
 
            break;
742
 
        case CODEC_TYPE_AUDIO:
743
 
            pkt->flags |= PKT_FLAG_KEY;
744
 
            break;
745
 
        default:
746
 
            break;
747
 
        }
748
771
    }
749
772
}
750
773
 
758
781
    AVStream *st;
759
782
    int len, ret, i;
760
783
 
 
784
    av_init_packet(pkt);
 
785
 
761
786
    for(;;) {
762
787
        /* select current input stream component */
763
788
        st = s->cur_st;
782
807
                /* return packet if any */
783
808
                if (pkt->size) {
784
809
                got_packet:
 
810
                    pkt->pos = s->cur_pkt.pos;              // Isn't quite accurate but close.
785
811
                    pkt->duration = 0;
786
812
                    pkt->stream_index = st->index;
787
813
                    pkt->pts = st->parser->pts;
790
816
                    compute_pkt_fields(s, st, st->parser, pkt);
791
817
 
792
818
                    if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & PKT_FLAG_KEY){
 
819
                        ff_reduce_index(s, st->index);
793
820
                        av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
794
821
                                           0, 0, AVINDEX_KEYFRAME);
795
822
                    }
819
846
                            goto got_packet;
820
847
                    }
821
848
                }
822
 
                /* no more packets: really terminates parsing */
 
849
                /* no more packets: really terminate parsing */
823
850
                return ret;
824
851
            }
825
852
 
837
864
            if (st->need_parsing && !st->parser) {
838
865
                st->parser = av_parser_init(st->codec->codec_id);
839
866
                if (!st->parser) {
840
 
                    /* no parser available : just output the raw packets */
841
 
                    st->need_parsing = 0;
842
 
                }else if(st->need_parsing == 2){
 
867
                    /* no parser available: just output the raw packets */
 
868
                    st->need_parsing = AVSTREAM_PARSE_NONE;
 
869
                }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
843
870
                    st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
844
871
                }
845
872
                if(st->parser && (s->iformat->flags & AVFMT_GENERIC_INDEX)){
859
886
    return 0;
860
887
}
861
888
 
862
 
/**
863
 
 * Return the next frame of a stream.
864
 
 *
865
 
 * The returned packet is valid
866
 
 * until the next av_read_frame() or until av_close_input_file() and
867
 
 * must be freed with av_free_packet. For video, the packet contains
868
 
 * exactly one frame. For audio, it contains an integer number of
869
 
 * frames if each frame has a known fixed size (e.g. PCM or ADPCM
870
 
 * data). If the audio frames have a variable size (e.g. MPEG audio),
871
 
 * then it contains one frame.
872
 
 *
873
 
 * pkt->pts, pkt->dts and pkt->duration are always set to correct
874
 
 * values in AV_TIME_BASE unit (and guessed if the format cannot
875
 
 * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
876
 
 * has B frames, so it is better to rely on pkt->dts if you do not
877
 
 * decompress the payload.
878
 
 *
879
 
 * @return 0 if OK, < 0 if error or end of file.
880
 
 */
 
889
static AVPacket *add_to_pktbuf(AVFormatContext *s, AVPacket *pkt){
 
890
    AVPacketList *pktl= s->packet_buffer;
 
891
    AVPacketList **plast_pktl= &s->packet_buffer;
 
892
 
 
893
    while(*plast_pktl) plast_pktl= &(*plast_pktl)->next; //FIXME maybe maintain pointer to the last?
 
894
 
 
895
    pktl = av_mallocz(sizeof(AVPacketList));
 
896
    if (!pktl)
 
897
        return NULL;
 
898
 
 
899
    /* add the packet in the buffered packet list */
 
900
    *plast_pktl = pktl;
 
901
    pktl->pkt= *pkt;
 
902
    return &pktl->pkt;
 
903
}
 
904
 
881
905
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
882
906
{
883
907
    AVPacketList *pktl;
913
937
            }
914
938
        }
915
939
        if(genpts){
916
 
            AVPacketList **plast_pktl= &s->packet_buffer;
917
940
            int ret= av_read_frame_internal(s, pkt);
918
941
            if(ret<0){
919
942
                if(pktl && ret != AVERROR(EAGAIN)){
923
946
                    return ret;
924
947
            }
925
948
 
926
 
            /* duplicate the packet */
927
 
            if (av_dup_packet(pkt) < 0)
928
 
                return AVERROR_NOMEM;
929
 
 
930
 
            while(*plast_pktl) plast_pktl= &(*plast_pktl)->next; //FIXME maybe maintain pointer to the last?
931
 
 
932
 
            pktl = av_mallocz(sizeof(AVPacketList));
933
 
            if (!pktl)
934
 
                return AVERROR_NOMEM;
935
 
 
936
 
            /* add the packet in the buffered packet list */
937
 
            *plast_pktl = pktl;
938
 
            pktl->pkt= *pkt;
 
949
            if(av_dup_packet(add_to_pktbuf(s, pkt)) < 0)
 
950
                return AVERROR(ENOMEM);
939
951
        }else{
940
952
            assert(!s->packet_buffer);
941
953
            return av_read_frame_internal(s, pkt);
1006
1018
            st->parser = NULL;
1007
1019
        }
1008
1020
        st->last_IP_pts = AV_NOPTS_VALUE;
1009
 
        st->cur_dts = 0; /* we set the current DTS to an unspecified origin */
 
1021
        st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1010
1022
    }
1011
1023
}
1012
1024
 
1013
 
/**
1014
 
 * Updates cur_dts of all streams based on given timestamp and AVStream.
1015
 
 *
1016
 
 * Stream ref_st unchanged, others set cur_dts in their native timebase
1017
 
 * only needed for timestamp wrapping or if (dts not set and pts!=dts)
1018
 
 * @param timestamp new dts expressed in time_base of param ref_st
1019
 
 * @param ref_st reference stream giving time_base of param timestamp
1020
 
 */
1021
1025
void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1022
1026
    int i;
1023
1027
 
1030
1034
    }
1031
1035
}
1032
1036
 
1033
 
/**
1034
 
 * Add a index entry into a sorted list updateing if it is already there.
1035
 
 *
1036
 
 * @param timestamp timestamp in the timebase of the given stream
1037
 
 */
 
1037
void ff_reduce_index(AVFormatContext *s, int stream_index)
 
1038
{
 
1039
    AVStream *st= s->streams[stream_index];
 
1040
    unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
 
1041
 
 
1042
    if((unsigned)st->nb_index_entries >= max_entries){
 
1043
        int i;
 
1044
        for(i=0; 2*i<st->nb_index_entries; i++)
 
1045
            st->index_entries[i]= st->index_entries[2*i];
 
1046
        st->nb_index_entries= i;
 
1047
    }
 
1048
}
 
1049
 
1038
1050
int av_add_index_entry(AVStream *st,
1039
1051
                            int64_t pos, int64_t timestamp, int size, int distance, int flags)
1040
1052
{
1066
1078
                return -1;
1067
1079
            memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
1068
1080
            st->nb_index_entries++;
1069
 
        }else if(ie->pos == pos && distance < ie->min_distance) //dont reduce the distance
 
1081
        }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1070
1082
            distance= ie->min_distance;
1071
1083
    }
1072
1084
 
1079
1091
    return index;
1080
1092
}
1081
1093
 
1082
 
/**
1083
 
 * build an index for raw streams using a parser.
1084
 
 */
1085
 
static void av_build_index_raw(AVFormatContext *s)
1086
 
{
1087
 
    AVPacket pkt1, *pkt = &pkt1;
1088
 
    int ret;
1089
 
    AVStream *st;
1090
 
 
1091
 
    st = s->streams[0];
1092
 
    av_read_frame_flush(s);
1093
 
    url_fseek(&s->pb, s->data_offset, SEEK_SET);
1094
 
 
1095
 
    for(;;) {
1096
 
        ret = av_read_frame(s, pkt);
1097
 
        if (ret < 0)
1098
 
            break;
1099
 
        if (pkt->stream_index == 0 && st->parser &&
1100
 
            (pkt->flags & PKT_FLAG_KEY)) {
1101
 
            av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
1102
 
                            0, 0, AVINDEX_KEYFRAME);
1103
 
        }
1104
 
        av_free_packet(pkt);
1105
 
    }
1106
 
}
1107
 
 
1108
 
/**
1109
 
 * Returns TRUE if we deal with a raw stream.
1110
 
 *
1111
 
 * Raw codec data and parsing needed.
1112
 
 */
1113
 
static int is_raw_stream(AVFormatContext *s)
1114
 
{
1115
 
    AVStream *st;
1116
 
 
1117
 
    if (s->nb_streams != 1)
1118
 
        return 0;
1119
 
    st = s->streams[0];
1120
 
    if (!st->need_parsing)
1121
 
        return 0;
1122
 
    return 1;
1123
 
}
1124
 
 
1125
 
/**
1126
 
 * Gets the index for a specific timestamp.
1127
 
 * @param flags if AVSEEK_FLAG_BACKWARD then the returned index will correspond to
1128
 
 *                 the timestamp which is <= the requested one, if backward is 0
1129
 
 *                 then it will be >=
1130
 
 *              if AVSEEK_FLAG_ANY seek to any frame, only keyframes otherwise
1131
 
 * @return < 0 if no such timestamp could be found
1132
 
 */
1133
1094
int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1134
1095
                              int flags)
1135
1096
{
1164
1125
 
1165
1126
#define DEBUG_SEEK
1166
1127
 
1167
 
/**
1168
 
 * Does a binary search using av_index_search_timestamp() and AVCodec.read_timestamp().
1169
 
 * this isnt supposed to be called directly by a user application, but by demuxers
1170
 
 * @param target_ts target timestamp in the time base of the given stream
1171
 
 * @param stream_index stream number
1172
 
 */
1173
1128
int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1174
1129
    AVInputFormat *avif= s->iformat;
1175
1130
    int64_t pos_min, pos_max, pos, pos_limit;
1186
1141
 
1187
1142
    ts_max=
1188
1143
    ts_min= AV_NOPTS_VALUE;
1189
 
    pos_limit= -1; //gcc falsely says it may be uninitalized
 
1144
    pos_limit= -1; //gcc falsely says it may be uninitialized
1190
1145
 
1191
1146
    st= s->streams[stream_index];
1192
1147
    if(st->index_entries){
1193
1148
        AVIndexEntry *e;
1194
1149
 
1195
 
        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()
 
1150
        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()
1196
1151
        index= FFMAX(index, 0);
1197
1152
        e= &st->index_entries[index];
1198
1153
 
1227
1182
        return -1;
1228
1183
 
1229
1184
    /* do the seek */
1230
 
    url_fseek(&s->pb, pos, SEEK_SET);
 
1185
    url_fseek(s->pb, pos, SEEK_SET);
1231
1186
 
1232
1187
    av_update_cur_dts(s, st, ts);
1233
1188
 
1234
1189
    return 0;
1235
1190
}
1236
1191
 
1237
 
/**
1238
 
 * Does a binary search using read_timestamp().
1239
 
 * this isnt supposed to be called directly by a user application, but by demuxers
1240
 
 * @param target_ts target timestamp in the time base of the given stream
1241
 
 * @param stream_index stream number
1242
 
 */
1243
1192
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 )){
1244
1193
    int64_t pos, ts;
1245
1194
    int64_t start_pos, filesize;
1258
1207
 
1259
1208
    if(ts_max == AV_NOPTS_VALUE){
1260
1209
        int step= 1024;
1261
 
        filesize = url_fsize(&s->pb);
 
1210
        filesize = url_fsize(s->pb);
1262
1211
        pos_max = filesize - 1;
1263
1212
        do{
1264
1213
            pos_max -= step;
1305
1254
            // bisection, if interpolation failed to change min or max pos last time
1306
1255
            pos = (pos_min + pos_limit)>>1;
1307
1256
        }else{
1308
 
            // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
 
1257
            /* linear search if bisection failed, can only happen if there
 
1258
               are very few or no keyframes between min/max */
1309
1259
            pos=pos_min;
1310
1260
        }
1311
1261
        if(pos <= pos_min)
1322
1272
#ifdef DEBUG_SEEK
1323
1273
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);
1324
1274
#endif
 
1275
        if(ts == AV_NOPTS_VALUE){
 
1276
            av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
 
1277
            return -1;
 
1278
        }
1325
1279
        assert(ts != AV_NOPTS_VALUE);
1326
1280
        if (target_ts <= ts) {
1327
1281
            pos_limit = start_pos - 1;
1360
1314
#endif
1361
1315
 
1362
1316
    pos_min = s->data_offset;
1363
 
    pos_max = url_fsize(&s->pb) - 1;
 
1317
    pos_max = url_fsize(s->pb) - 1;
1364
1318
 
1365
1319
    if     (pos < pos_min) pos= pos_min;
1366
1320
    else if(pos > pos_max) pos= pos_max;
1367
1321
 
1368
 
    url_fseek(&s->pb, pos, SEEK_SET);
 
1322
    url_fseek(s->pb, pos, SEEK_SET);
1369
1323
 
1370
1324
#if 0
1371
1325
    av_update_cur_dts(s, st, ts);
1384
1338
 
1385
1339
    index = av_index_search_timestamp(st, timestamp, flags);
1386
1340
 
1387
 
    if(index < 0){
 
1341
    if(index < 0 || index==st->nb_index_entries-1){
1388
1342
        int i;
1389
1343
        AVPacket pkt;
1390
1344
 
1391
1345
        if(st->index_entries && st->nb_index_entries){
1392
1346
            ie= &st->index_entries[st->nb_index_entries-1];
1393
 
            url_fseek(&s->pb, ie->pos, SEEK_SET);
 
1347
            url_fseek(s->pb, ie->pos, SEEK_SET);
1394
1348
            av_update_cur_dts(s, st, ie->timestamp);
1395
1349
        }else
1396
 
            url_fseek(&s->pb, 0, SEEK_SET);
 
1350
            url_fseek(s->pb, 0, SEEK_SET);
1397
1351
 
1398
1352
        for(i=0;; i++) {
1399
1353
            int ret = av_read_frame(s, &pkt);
1416
1370
            return 0;
1417
1371
    }
1418
1372
    ie = &st->index_entries[index];
1419
 
    url_fseek(&s->pb, ie->pos, SEEK_SET);
 
1373
    url_fseek(s->pb, ie->pos, SEEK_SET);
1420
1374
 
1421
1375
    av_update_cur_dts(s, st, ie->timestamp);
1422
1376
 
1423
1377
    return 0;
1424
1378
}
1425
1379
 
1426
 
/**
1427
 
 * Seek to the key frame at timestamp.
1428
 
 * 'timestamp' in 'stream_index'.
1429
 
 * @param stream_index If stream_index is (-1), a default
1430
 
 * stream is selected, and timestamp is automatically converted
1431
 
 * from AV_TIME_BASE units to the stream specific time_base.
1432
 
 * @param timestamp timestamp in AVStream.time_base units
1433
 
 *        or if there is no stream specified then in AV_TIME_BASE units
1434
 
 * @param flags flags which select direction and seeking mode
1435
 
 * @return >= 0 on success
1436
 
 */
1437
1380
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1438
1381
{
1439
1382
    int ret;
1473
1416
/*******************************************************/
1474
1417
 
1475
1418
/**
1476
 
 * Returns TRUE if the stream has accurate timings in any stream.
 
1419
 * Returns TRUE if the stream has accurate duration in any stream.
1477
1420
 *
1478
 
 * @return TRUE if the stream has accurate timings for at least one component.
 
1421
 * @return TRUE if the stream has accurate duration for at least one component.
1479
1422
 */
1480
 
static int av_has_timings(AVFormatContext *ic)
 
1423
static int av_has_duration(AVFormatContext *ic)
1481
1424
{
1482
1425
    int i;
1483
1426
    AVStream *st;
1484
1427
 
1485
1428
    for(i = 0;i < ic->nb_streams; i++) {
1486
1429
        st = ic->streams[i];
1487
 
        if (st->start_time != AV_NOPTS_VALUE &&
1488
 
            st->duration != AV_NOPTS_VALUE)
 
1430
        if (st->duration != AV_NOPTS_VALUE)
1489
1431
            return 1;
1490
1432
    }
1491
1433
    return 0;
1499
1441
static void av_update_stream_timings(AVFormatContext *ic)
1500
1442
{
1501
1443
    int64_t start_time, start_time1, end_time, end_time1;
 
1444
    int64_t duration, duration1;
1502
1445
    int i;
1503
1446
    AVStream *st;
1504
1447
 
1505
1448
    start_time = INT64_MAX;
1506
1449
    end_time = INT64_MIN;
 
1450
    duration = INT64_MIN;
1507
1451
    for(i = 0;i < ic->nb_streams; i++) {
1508
1452
        st = ic->streams[i];
1509
 
        if (st->start_time != AV_NOPTS_VALUE) {
 
1453
        if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1510
1454
            start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1511
1455
            if (start_time1 < start_time)
1512
1456
                start_time = start_time1;
1517
1461
                    end_time = end_time1;
1518
1462
            }
1519
1463
        }
 
1464
        if (st->duration != AV_NOPTS_VALUE) {
 
1465
            duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
 
1466
            if (duration1 > duration)
 
1467
                duration = duration1;
 
1468
        }
1520
1469
    }
1521
1470
    if (start_time != INT64_MAX) {
1522
1471
        ic->start_time = start_time;
1523
1472
        if (end_time != INT64_MIN) {
1524
 
            ic->duration = end_time - start_time;
1525
 
            if (ic->file_size > 0) {
1526
 
                /* compute the bit rate */
1527
 
                ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1528
 
                    (double)ic->duration;
1529
 
            }
1530
 
        }
1531
 
    }
1532
 
 
 
1473
            if (end_time - start_time > duration)
 
1474
                duration = end_time - start_time;
 
1475
        }
 
1476
    }
 
1477
    if (duration != INT64_MIN) {
 
1478
        ic->duration = duration;
 
1479
        if (ic->file_size > 0) {
 
1480
            /* compute the bitrate */
 
1481
            ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
 
1482
                (double)ic->duration;
 
1483
        }
 
1484
    }
1533
1485
}
1534
1486
 
1535
1487
static void fill_all_stream_timings(AVFormatContext *ic)
1574
1526
            for(i = 0; i < ic->nb_streams; i++) {
1575
1527
                st = ic->streams[i];
1576
1528
                duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1577
 
                if (st->start_time == AV_NOPTS_VALUE ||
1578
 
                    st->duration == AV_NOPTS_VALUE) {
1579
 
                    st->start_time = 0;
 
1529
                if (st->duration == AV_NOPTS_VALUE)
1580
1530
                    st->duration = duration;
1581
 
                }
1582
1531
            }
1583
1532
        }
1584
1533
    }
1613
1562
 
1614
1563
    /* we read the first packets to get the first PTS (not fully
1615
1564
       accurate, but it is enough now) */
1616
 
    url_fseek(&ic->pb, 0, SEEK_SET);
 
1565
    url_fseek(ic->pb, 0, SEEK_SET);
1617
1566
    read_size = 0;
1618
1567
    for(;;) {
1619
1568
        if (read_size >= DURATION_MAX_READ_SIZE)
1646
1595
    if (offset < 0)
1647
1596
        offset = 0;
1648
1597
 
1649
 
    url_fseek(&ic->pb, offset, SEEK_SET);
 
1598
    url_fseek(ic->pb, offset, SEEK_SET);
1650
1599
    read_size = 0;
1651
1600
    for(;;) {
1652
1601
        if (read_size >= DURATION_MAX_READ_SIZE)
1653
1602
            break;
1654
 
        /* if all info is available, we can stop */
1655
 
        for(i = 0;i < ic->nb_streams; i++) {
1656
 
            st = ic->streams[i];
1657
 
            if (st->duration == AV_NOPTS_VALUE)
1658
 
                break;
1659
 
        }
1660
 
        if (i == ic->nb_streams)
1661
 
            break;
1662
1603
 
1663
1604
        ret = av_read_packet(ic, pkt);
1664
1605
        if (ret != 0)
1665
1606
            break;
1666
1607
        read_size += pkt->size;
1667
1608
        st = ic->streams[pkt->stream_index];
1668
 
        if (pkt->pts != AV_NOPTS_VALUE) {
 
1609
        if (pkt->pts != AV_NOPTS_VALUE &&
 
1610
            st->start_time != AV_NOPTS_VALUE) {
1669
1611
            end_time = pkt->pts;
1670
1612
            duration = end_time - st->start_time;
1671
1613
            if (duration > 0) {
1679
1621
 
1680
1622
    fill_all_stream_timings(ic);
1681
1623
 
1682
 
    url_fseek(&ic->pb, old_offset, SEEK_SET);
 
1624
    url_fseek(ic->pb, old_offset, SEEK_SET);
 
1625
    for(i=0; i<ic->nb_streams; i++){
 
1626
        st= ic->streams[i];
 
1627
        st->cur_dts= st->first_dts;
 
1628
        st->last_IP_pts = AV_NOPTS_VALUE;
 
1629
    }
1683
1630
}
1684
1631
 
1685
1632
static void av_estimate_timings(AVFormatContext *ic, offset_t old_offset)
1690
1637
    if (ic->iformat->flags & AVFMT_NOFILE) {
1691
1638
        file_size = 0;
1692
1639
    } else {
1693
 
        file_size = url_fsize(&ic->pb);
 
1640
        file_size = url_fsize(ic->pb);
1694
1641
        if (file_size < 0)
1695
1642
            file_size = 0;
1696
1643
    }
1698
1645
 
1699
1646
    if ((!strcmp(ic->iformat->name, "mpeg") ||
1700
1647
         !strcmp(ic->iformat->name, "mpegts")) &&
1701
 
        file_size && !ic->pb.is_streamed) {
 
1648
        file_size && !url_is_streamed(ic->pb)) {
1702
1649
        /* get accurate estimate from the PTSes */
1703
1650
        av_estimate_timings_from_pts(ic, old_offset);
1704
 
    } else if (av_has_timings(ic)) {
1705
 
        /* at least one components has timings - we use them for all
 
1651
    } else if (av_has_duration(ic)) {
 
1652
        /* at least one component has timings - we use them for all
1706
1653
           the components */
1707
1654
        fill_all_stream_timings(ic);
1708
1655
    } else {
1709
 
        /* less precise: use bit rate info */
 
1656
        /* less precise: use bitrate info */
1710
1657
        av_estimate_timings_from_bit_rate(ic);
1711
1658
    }
1712
1659
    av_update_stream_timings(ic);
1743
1690
        val = 1;
1744
1691
        break;
1745
1692
    }
1746
 
    return (val != 0);
 
1693
    return (enc->codec_id != CODEC_ID_NONE && val != 0);
1747
1694
}
1748
1695
 
1749
1696
static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1766
1713
    switch(st->codec->codec_type) {
1767
1714
    case CODEC_TYPE_VIDEO:
1768
1715
        ret = avcodec_decode_video(st->codec, &picture,
1769
 
                                   &got_picture, (uint8_t *)data, size);
 
1716
                                   &got_picture, data, size);
1770
1717
        break;
1771
1718
    case CODEC_TYPE_AUDIO:
1772
1719
        data_size = FFMAX(size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
1774
1721
        if (!samples)
1775
1722
            goto fail;
1776
1723
        ret = avcodec_decode_audio2(st->codec, samples,
1777
 
                                    &data_size, (uint8_t *)data, size);
 
1724
                                    &data_size, data, size);
1778
1725
        av_free(samples);
1779
1726
        break;
1780
1727
    default:
1785
1732
    return ret;
1786
1733
}
1787
1734
 
 
1735
static int set_codec_from_probe_data(AVStream *st, AVProbeData *pd, int score)
 
1736
{
 
1737
    AVInputFormat *fmt;
 
1738
    fmt = av_probe_input_format2(pd, 1, &score);
 
1739
 
 
1740
    if (fmt) {
 
1741
        if (strncmp(fmt->name, "mp3", 3) == 0)
 
1742
            st->codec->codec_id = CODEC_ID_MP3;
 
1743
        else if (strncmp(fmt->name, "ac3", 3) == 0)
 
1744
            st->codec->codec_id = CODEC_ID_AC3;
 
1745
    }
 
1746
    return !!fmt;
 
1747
}
 
1748
 
 
1749
unsigned int codec_get_tag(const AVCodecTag *tags, int id)
 
1750
{
 
1751
    while (tags->id != CODEC_ID_NONE) {
 
1752
        if (tags->id == id)
 
1753
            return tags->tag;
 
1754
        tags++;
 
1755
    }
 
1756
    return 0;
 
1757
}
 
1758
 
 
1759
enum CodecID codec_get_id(const AVCodecTag *tags, unsigned int tag)
 
1760
{
 
1761
    int i;
 
1762
    for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
 
1763
        if(tag == tags[i].tag)
 
1764
            return tags[i].id;
 
1765
    }
 
1766
    for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
 
1767
        if(   toupper((tag >> 0)&0xFF) == toupper((tags[i].tag >> 0)&0xFF)
 
1768
           && toupper((tag >> 8)&0xFF) == toupper((tags[i].tag >> 8)&0xFF)
 
1769
           && toupper((tag >>16)&0xFF) == toupper((tags[i].tag >>16)&0xFF)
 
1770
           && toupper((tag >>24)&0xFF) == toupper((tags[i].tag >>24)&0xFF))
 
1771
            return tags[i].id;
 
1772
    }
 
1773
    return CODEC_ID_NONE;
 
1774
}
 
1775
 
 
1776
unsigned int av_codec_get_tag(const AVCodecTag *tags[4], enum CodecID id)
 
1777
{
 
1778
    int i;
 
1779
    for(i=0; tags && tags[i]; i++){
 
1780
        int tag= codec_get_tag(tags[i], id);
 
1781
        if(tag) return tag;
 
1782
    }
 
1783
    return 0;
 
1784
}
 
1785
 
 
1786
enum CodecID av_codec_get_id(const AVCodecTag *tags[4], unsigned int tag)
 
1787
{
 
1788
    int i;
 
1789
    for(i=0; tags && tags[i]; i++){
 
1790
        enum CodecID id= codec_get_id(tags[i], tag);
 
1791
        if(id!=CODEC_ID_NONE) return id;
 
1792
    }
 
1793
    return CODEC_ID_NONE;
 
1794
}
 
1795
 
1788
1796
/* absolute maximum size we read until we abort */
1789
1797
#define MAX_READ_SIZE        5000000
1790
1798
 
1794
1802
    else        return ((int[]){24,30,60,12,15})[i-60*12]*1000*12;
1795
1803
}
1796
1804
 
1797
 
/**
1798
 
 * Read packets of a media file to get stream information. This
1799
 
 * is useful for file formats with no headers such as MPEG. This
1800
 
 * function also computes the real frame rate in case of mpeg2 repeat
1801
 
 * frame mode.
1802
 
 * The logical file position is not changed by this function;
1803
 
 * examined packets may be buffered for later processing.
1804
 
 *
1805
 
 * @param ic media file handle
1806
 
 * @return >=0 if OK. AVERROR_xxx if error.
1807
 
 * @todo let user decide somehow what information is needed so we dont waste time geting stuff the user doesnt need
 
1805
/*
 
1806
 * Is the time base unreliable.
 
1807
 * This is a heuristic to balance between quick acceptance of the values in
 
1808
 * the headers vs. some extra checks.
 
1809
 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
 
1810
 * MPEG-2 commonly misuses field repeat flags to store different framerates.
 
1811
 * And there are "variable" fps files this needs to detect as well.
1808
1812
 */
 
1813
static int tb_unreliable(AVCodecContext *c){
 
1814
    if(   c->time_base.den >= 101L*c->time_base.num
 
1815
       || c->time_base.den <    5L*c->time_base.num
 
1816
/*       || c->codec_tag == ff_get_fourcc("DIVX")
 
1817
       || c->codec_tag == ff_get_fourcc("XVID")*/
 
1818
       || c->codec_id == CODEC_ID_MPEG2VIDEO)
 
1819
        return 1;
 
1820
    return 0;
 
1821
}
 
1822
 
1809
1823
int av_find_stream_info(AVFormatContext *ic)
1810
1824
{
1811
1825
    int i, count, ret, read_size, j;
1812
1826
    AVStream *st;
1813
1827
    AVPacket pkt1, *pkt;
1814
 
    AVPacketList *pktl=NULL, **ppktl;
1815
1828
    int64_t last_dts[MAX_STREAMS];
1816
1829
    int duration_count[MAX_STREAMS]={0};
1817
1830
    double (*duration_error)[MAX_STD_TIMEBASES];
1818
 
    offset_t old_offset = url_ftell(&ic->pb);
 
1831
    offset_t old_offset = url_ftell(ic->pb);
 
1832
    int64_t codec_info_duration[MAX_STREAMS]={0};
 
1833
    int codec_info_nb_frames[MAX_STREAMS]={0};
 
1834
    AVProbeData probe_data[MAX_STREAMS];
 
1835
    int codec_identified[MAX_STREAMS]={0};
1819
1836
 
1820
1837
    duration_error = av_mallocz(MAX_STREAMS * sizeof(*duration_error));
1821
 
    if (!duration_error) return AVERROR_NOMEM;
 
1838
    if (!duration_error) return AVERROR(ENOMEM);
1822
1839
 
1823
1840
    for(i=0;i<ic->nb_streams;i++) {
1824
1841
        st = ic->streams[i];
1831
1848
        //only for the split stuff
1832
1849
        if (!st->parser) {
1833
1850
            st->parser = av_parser_init(st->codec->codec_id);
1834
 
            if(st->need_parsing == 2 && st->parser){
 
1851
            if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
1835
1852
                st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1836
1853
            }
1837
1854
        }
1841
1858
        last_dts[i]= AV_NOPTS_VALUE;
1842
1859
    }
1843
1860
 
 
1861
    memset(probe_data, 0, sizeof(probe_data));
1844
1862
    count = 0;
1845
1863
    read_size = 0;
1846
 
    ppktl = &ic->packet_buffer;
1847
1864
    for(;;) {
1848
1865
        /* check if one codec still needs to be handled */
1849
1866
        for(i=0;i<ic->nb_streams;i++) {
1851
1868
            if (!has_codec_parameters(st->codec))
1852
1869
                break;
1853
1870
            /* variable fps and no guess at the real fps */
1854
 
            if(   st->codec->time_base.den >= 101LL*st->codec->time_base.num
 
1871
            if(   tb_unreliable(st->codec)
1855
1872
               && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)
1856
1873
                break;
1857
1874
            if(st->parser && st->parser->parser->split && !st->codec->extradata)
1858
1875
                break;
 
1876
            if(st->first_dts == AV_NOPTS_VALUE)
 
1877
                break;
1859
1878
        }
1860
1879
        if (i == ic->nb_streams) {
1861
1880
            /* NOTE: if the format has no header, then we need to read
1892
1911
            break;
1893
1912
        }
1894
1913
 
1895
 
        pktl = av_mallocz(sizeof(AVPacketList));
1896
 
        if (!pktl) {
1897
 
            ret = AVERROR_NOMEM;
1898
 
            break;
1899
 
        }
1900
 
 
1901
 
        /* add the packet in the buffered packet list */
1902
 
        *ppktl = pktl;
1903
 
        ppktl = &pktl->next;
1904
 
 
1905
 
        pkt = &pktl->pkt;
1906
 
        *pkt = pkt1;
1907
 
 
1908
 
        /* duplicate the packet */
1909
 
        if (av_dup_packet(pkt) < 0) {
1910
 
            ret = AVERROR_NOMEM;
1911
 
            break;
1912
 
        }
 
1914
        pkt= add_to_pktbuf(ic, &pkt1);
 
1915
        if(av_dup_packet(pkt) < 0)
 
1916
            return AVERROR(ENOMEM);
1913
1917
 
1914
1918
        read_size += pkt->size;
1915
1919
 
1916
1920
        st = ic->streams[pkt->stream_index];
1917
 
        if(st->codec_info_nb_frames>1) //FIXME move codec_info_nb_frames and codec_info_duration from AVStream into this func
1918
 
            st->codec_info_duration += pkt->duration;
 
1921
        if(codec_info_nb_frames[st->index]>1)
 
1922
            codec_info_duration[st->index] += pkt->duration;
1919
1923
        if (pkt->duration != 0)
1920
 
            st->codec_info_nb_frames++;
 
1924
            codec_info_nb_frames[st->index]++;
1921
1925
 
1922
1926
        {
1923
1927
            int index= pkt->stream_index;
1930
1934
//                if(st->codec->codec_type == CODEC_TYPE_VIDEO)
1931
1935
//                    av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
1932
1936
                if(duration_count[index] < 2)
1933
 
                    memset(duration_error, 0, MAX_STREAMS * sizeof(*duration_error));
 
1937
                    memset(duration_error[index], 0, sizeof(*duration_error));
1934
1938
                for(i=1; i<MAX_STD_TIMEBASES; i++){
1935
1939
                    int framerate= get_std_framerate(i);
1936
1940
                    int ticks= lrintf(dur*framerate/(1001*12));
1938
1942
                    duration_error[index][i] += error*error;
1939
1943
                }
1940
1944
                duration_count[index]++;
1941
 
 
1942
 
                if(st->codec_info_nb_frames == 0 && 0)
1943
 
                    st->codec_info_duration += duration;
1944
1945
            }
1945
1946
            if(last == AV_NOPTS_VALUE || duration_count[index]<=1)
1946
1947
                last_dts[pkt->stream_index]= pkt->dts;
 
1948
 
 
1949
            if (st->codec->codec_id == CODEC_ID_NONE) {
 
1950
                AVProbeData *pd = &(probe_data[st->index]);
 
1951
                pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
 
1952
                memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
 
1953
                pd->buf_size += pkt->size;
 
1954
                memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
 
1955
            }
1947
1956
        }
1948
1957
        if(st->parser && st->parser->parser->split && !st->codec->extradata){
1949
1958
            int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
1957
1966
 
1958
1967
        /* if still no information, we try to open the codec and to
1959
1968
           decompress the frame. We try to avoid that in most cases as
1960
 
           it takes longer and uses more memory. For MPEG4, we need to
1961
 
           decompress for Quicktime. */
 
1969
           it takes longer and uses more memory. For MPEG-4, we need to
 
1970
           decompress for QuickTime. */
1962
1971
        if (!has_codec_parameters(st->codec) /*&&
1963
1972
            (st->codec->codec_id == CODEC_ID_FLV1 ||
1964
1973
             st->codec->codec_id == CODEC_ID_H264 ||
1976
1985
             (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
1977
1986
            try_decode_frame(st, pkt->data, pkt->size);
1978
1987
 
1979
 
        if (av_rescale_q(st->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
 
1988
        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) {
1980
1989
            break;
1981
1990
        }
1982
1991
        count++;
1983
1992
    }
1984
1993
 
1985
 
    // close codecs which where opened in try_decode_frame()
 
1994
    // close codecs which were opened in try_decode_frame()
1986
1995
    for(i=0;i<ic->nb_streams;i++) {
1987
1996
        st = ic->streams[i];
1988
1997
        if(st->codec->codec)
1995
2004
                st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
1996
2005
 
1997
2006
            if(duration_count[i]
1998
 
               && (st->codec->time_base.num*101LL <= st->codec->time_base.den || st->codec->codec_id == CODEC_ID_MPEG2VIDEO) /*&&
1999
 
               //FIXME we should not special case mpeg2, but this needs testing with non mpeg2 ...
 
2007
               && tb_unreliable(st->codec) /*&&
 
2008
               //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2000
2009
               st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den*/){
2001
2010
                double best_error= 2*av_q2d(st->time_base);
2002
2011
                best_error= best_error*best_error*duration_count[i]*1000*12*30;
2023
2032
                }
2024
2033
            }
2025
2034
        }else if(st->codec->codec_type == CODEC_TYPE_AUDIO) {
 
2035
            if (st->codec->codec_id == CODEC_ID_NONE && probe_data[st->index].buf_size > 0) {
 
2036
                codec_identified[st->index] = set_codec_from_probe_data(st, &(probe_data[st->index]), 1);
 
2037
                if (codec_identified[st->index]) {
 
2038
                    st->need_parsing = AVSTREAM_PARSE_FULL;
 
2039
                }
 
2040
            }
2026
2041
            if(!st->codec->bits_per_sample)
2027
2042
                st->codec->bits_per_sample= av_get_bits_per_sample(st->codec->codec_id);
2028
2043
        }
2029
2044
    }
2030
2045
 
2031
2046
    av_estimate_timings(ic, old_offset);
 
2047
 
 
2048
    for(i=0;i<ic->nb_streams;i++) {
 
2049
        st = ic->streams[i];
 
2050
        if (codec_identified[st->index])
 
2051
            break;
 
2052
    }
 
2053
    //FIXME this is a mess
 
2054
    if(i!=ic->nb_streams){
 
2055
        av_read_frame_flush(ic);
 
2056
        for(i=0;i<ic->nb_streams;i++) {
 
2057
            st = ic->streams[i];
 
2058
            if (codec_identified[st->index]) {
 
2059
                av_seek_frame(ic, st->index, 0.0, 0);
 
2060
            }
 
2061
            st->cur_dts= st->first_dts;
 
2062
        }
 
2063
        url_fseek(ic->pb, ic->data_offset, SEEK_SET);
 
2064
    }
 
2065
 
2032
2066
#if 0
2033
 
    /* correct DTS for b frame streams with no timestamps */
 
2067
    /* correct DTS for B-frame streams with no timestamps */
2034
2068
    for(i=0;i<ic->nb_streams;i++) {
2035
2069
        st = ic->streams[i];
2036
2070
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2055
2089
#endif
2056
2090
 
2057
2091
    av_free(duration_error);
 
2092
    for(i=0;i<MAX_STREAMS;i++){
 
2093
        av_freep(&(probe_data[i].buf));
 
2094
    }
2058
2095
 
2059
2096
    return ret;
2060
2097
}
2061
2098
 
2062
2099
/*******************************************************/
2063
2100
 
2064
 
/**
2065
 
 * start playing a network based stream (e.g. RTSP stream) at the
2066
 
 * current position
2067
 
 */
2068
2101
int av_read_play(AVFormatContext *s)
2069
2102
{
2070
 
    if (!s->iformat->read_play)
2071
 
        return AVERROR_NOTSUPP;
2072
 
    return s->iformat->read_play(s);
 
2103
    if (s->iformat->read_play)
 
2104
        return s->iformat->read_play(s);
 
2105
    if (s->pb)
 
2106
        return av_url_read_fpause(s->pb, 0);
 
2107
    return AVERROR(ENOSYS);
2073
2108
}
2074
2109
 
2075
 
/**
2076
 
 * Pause a network based stream (e.g. RTSP stream).
2077
 
 *
2078
 
 * Use av_read_play() to resume it.
2079
 
 */
2080
2110
int av_read_pause(AVFormatContext *s)
2081
2111
{
2082
 
    if (!s->iformat->read_pause)
2083
 
        return AVERROR_NOTSUPP;
2084
 
    return s->iformat->read_pause(s);
 
2112
    if (s->iformat->read_pause)
 
2113
        return s->iformat->read_pause(s);
 
2114
    if (s->pb)
 
2115
        return av_url_read_fpause(s->pb, 1);
 
2116
    return AVERROR(ENOSYS);
2085
2117
}
2086
2118
 
2087
 
/**
2088
 
 * Close a media file (but not its codecs).
2089
 
 *
2090
 
 * @param s media file handle
2091
 
 */
2092
 
void av_close_input_file(AVFormatContext *s)
 
2119
void av_close_input_stream(AVFormatContext *s)
2093
2120
{
2094
 
    int i, must_open_file;
 
2121
    int i;
2095
2122
    AVStream *st;
2096
2123
 
2097
2124
    /* free previous packet */
2109
2136
        av_free(st->index_entries);
2110
2137
        av_free(st->codec->extradata);
2111
2138
        av_free(st->codec);
 
2139
        av_free(st->filename);
2112
2140
        av_free(st);
2113
2141
    }
 
2142
    for(i=s->nb_programs-1; i>=0; i--) {
 
2143
        av_freep(&s->programs[i]->provider_name);
 
2144
        av_freep(&s->programs[i]->name);
 
2145
        av_freep(&s->programs[i]->stream_index);
 
2146
        av_freep(&s->programs[i]);
 
2147
    }
 
2148
    av_freep(&s->programs);
2114
2149
    flush_packet_queue(s);
2115
 
    must_open_file = 1;
2116
 
    if (s->iformat->flags & AVFMT_NOFILE) {
2117
 
        must_open_file = 0;
2118
 
    }
2119
 
    if (must_open_file) {
2120
 
        url_fclose(&s->pb);
2121
 
    }
2122
2150
    av_freep(&s->priv_data);
2123
2151
    av_free(s);
2124
2152
}
2125
2153
 
2126
 
/**
2127
 
 * Add a new stream to a media file.
2128
 
 *
2129
 
 * Can only be called in the read_header() function. If the flag
2130
 
 * AVFMTCTX_NOHEADER is in the format context, then new streams
2131
 
 * can be added in read_packet too.
2132
 
 *
2133
 
 * @param s media file handle
2134
 
 * @param id file format dependent stream id
2135
 
 */
 
2154
void av_close_input_file(AVFormatContext *s)
 
2155
{
 
2156
    ByteIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
 
2157
    av_close_input_stream(s);
 
2158
    if (pb)
 
2159
        url_fclose(pb);
 
2160
}
 
2161
 
2136
2162
AVStream *av_new_stream(AVFormatContext *s, int id)
2137
2163
{
2138
2164
    AVStream *st;
2155
2181
    st->start_time = AV_NOPTS_VALUE;
2156
2182
    st->duration = AV_NOPTS_VALUE;
2157
2183
    st->cur_dts = AV_NOPTS_VALUE;
 
2184
    st->first_dts = AV_NOPTS_VALUE;
2158
2185
 
2159
 
    /* default pts settings is MPEG like */
 
2186
    /* default pts setting is MPEG-like */
2160
2187
    av_set_pts_info(st, 33, 1, 90000);
2161
2188
    st->last_IP_pts = AV_NOPTS_VALUE;
2162
2189
    for(i=0; i<MAX_REORDER_DELAY+1; i++)
2166
2193
    return st;
2167
2194
}
2168
2195
 
 
2196
AVProgram *av_new_program(AVFormatContext *ac, int id)
 
2197
{
 
2198
    AVProgram *program=NULL;
 
2199
    int i;
 
2200
 
 
2201
#ifdef DEBUG_SI
 
2202
    av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id);
 
2203
#endif
 
2204
 
 
2205
    for(i=0; i<ac->nb_programs; i++)
 
2206
        if(ac->programs[i]->id == id)
 
2207
            program = ac->programs[i];
 
2208
 
 
2209
    if(!program){
 
2210
        program = av_mallocz(sizeof(AVProgram));
 
2211
        if (!program)
 
2212
            return NULL;
 
2213
        dynarray_add(&ac->programs, &ac->nb_programs, program);
 
2214
        program->discard = AVDISCARD_NONE;
 
2215
    }
 
2216
    program->id = id;
 
2217
 
 
2218
    return program;
 
2219
}
 
2220
 
 
2221
void av_set_program_name(AVProgram *program, char *provider_name, char *name)
 
2222
{
 
2223
    assert(!provider_name == !name);
 
2224
    if(name){
 
2225
        av_free(program->provider_name);
 
2226
        av_free(program->         name);
 
2227
        program->provider_name = av_strdup(provider_name);
 
2228
        program->         name = av_strdup(         name);
 
2229
    }
 
2230
}
 
2231
 
 
2232
 
2169
2233
/************************************************************/
2170
2234
/* output media file */
2171
2235
 
2176
2240
    if (s->oformat->priv_data_size > 0) {
2177
2241
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
2178
2242
        if (!s->priv_data)
2179
 
            return AVERROR_NOMEM;
 
2243
            return AVERROR(ENOMEM);
2180
2244
    } else
2181
2245
        s->priv_data = NULL;
2182
2246
 
2188
2252
    return 0;
2189
2253
}
2190
2254
 
2191
 
/**
2192
 
 * allocate the stream private data and write the stream header to an
2193
 
 * output media file
2194
 
 *
2195
 
 * @param s media file handle
2196
 
 * @return 0 if OK. AVERROR_xxx if error.
2197
 
 */
2198
2255
int av_write_header(AVFormatContext *s)
2199
2256
{
2200
2257
    int ret, i;
2227
2284
            if(st->codec->codec_tag){
2228
2285
                //FIXME
2229
2286
                //check that tag + id is in the table
2230
 
                //if neither is in the table -> ok
 
2287
                //if neither is in the table -> OK
2231
2288
                //if tag is in the table with another id -> FAIL
2232
2289
                //if id is in the table with another tag -> FAIL unless strict < ?
2233
2290
            }else
2238
2295
    if (!s->priv_data && s->oformat->priv_data_size > 0) {
2239
2296
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
2240
2297
        if (!s->priv_data)
2241
 
            return AVERROR_NOMEM;
 
2298
            return AVERROR(ENOMEM);
2242
2299
    }
2243
2300
 
2244
2301
    if(s->oformat->write_header){
2325
2382
    case CODEC_TYPE_AUDIO:
2326
2383
        frame_size = get_audio_frame_size(st->codec, pkt->size);
2327
2384
 
2328
 
        /* HACK/FIXME, we skip the initial 0-size packets as they are most likely equal to the encoder delay,
2329
 
           but it would be better if we had the real timestamps from the encoder */
 
2385
        /* HACK/FIXME, we skip the initial 0 size packets as they are most
 
2386
           likely equal to the encoder delay, but it would be better if we
 
2387
           had the real timestamps from the encoder */
2330
2388
        if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2331
2389
            av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2332
2390
        }
2344
2402
    int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
2345
2403
 
2346
2404
//    if(pkt->dts < 0)
2347
 
//        pkt->dts= 0;  //this happens for low_delay=0 and b frames, FIXME, needs further invstigation about what we should do here
 
2405
//        pkt->dts= 0;  //this happens for low_delay=0 and B-frames, FIXME, needs further investigation about what we should do here
2348
2406
 
2349
2407
    if (pkt->pts != AV_NOPTS_VALUE)
2350
2408
        pkt->pts &= pts_mask;
2352
2410
        pkt->dts &= pts_mask;
2353
2411
}
2354
2412
 
2355
 
/**
2356
 
 * Write a packet to an output media file.
2357
 
 *
2358
 
 * The packet shall contain one audio or video frame.
2359
 
 * The packet must be correctly interleaved according to the container specification,
2360
 
 * if not then av_interleaved_write_frame must be used
2361
 
 *
2362
 
 * @param s media file handle
2363
 
 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2364
 
 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2365
 
 */
2366
2413
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2367
2414
{
2368
2415
    int ret;
2375
2422
 
2376
2423
    ret= s->oformat->write_packet(s, pkt);
2377
2424
    if(!ret)
2378
 
        ret= url_ferror(&s->pb);
 
2425
        ret= url_ferror(s->pb);
2379
2426
    return ret;
2380
2427
}
2381
2428
 
2382
 
/**
2383
 
 * Interleave a packet per DTS in an output media file.
2384
 
 *
2385
 
 * Packets with pkt->destruct == av_destruct_packet will be freed inside this function,
2386
 
 * so they cannot be used after it, note calling av_free_packet() on them is still safe.
2387
 
 *
2388
 
 * @param s media file handle
2389
 
 * @param out the interleaved packet will be output here
2390
 
 * @param in the input packet
2391
 
 * @param flush 1 if no further packets are available as input and all
2392
 
 *              remaining packets should be output
2393
 
 * @return 1 if a packet was output, 0 if no packet could be output,
2394
 
 *         < 0 if an error occured
2395
 
 */
2396
2429
int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2397
2430
    AVPacketList *pktl, **next_point, *this_pktl;
2398
2431
    int stream_count=0;
2406
2439
        this_pktl = av_mallocz(sizeof(AVPacketList));
2407
2440
        this_pktl->pkt= *pkt;
2408
2441
        if(pkt->destruct == av_destruct_packet)
2409
 
            pkt->destruct= NULL; // non shared -> must keep original from being freed
 
2442
            pkt->destruct= NULL; // not shared -> must keep original from being freed
2410
2443
        else
2411
2444
            av_dup_packet(&this_pktl->pkt);  //shared -> must dup
2412
2445
 
2447
2480
}
2448
2481
 
2449
2482
/**
2450
 
 * Interleaves a AVPacket correctly so it can be muxed.
 
2483
 * Interleaves an AVPacket correctly so it can be muxed.
2451
2484
 * @param out the interleaved packet will be output here
2452
2485
 * @param in the input packet
2453
2486
 * @param flush 1 if no further packets are available as input and all
2454
2487
 *              remaining packets should be output
2455
2488
 * @return 1 if a packet was output, 0 if no packet could be output,
2456
 
 *         < 0 if an error occured
 
2489
 *         < 0 if an error occurred
2457
2490
 */
2458
2491
static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2459
2492
    if(s->oformat->interleave_packet)
2462
2495
        return av_interleave_packet_per_dts(s, out, in, flush);
2463
2496
}
2464
2497
 
2465
 
/**
2466
 
 * Writes a packet to an output media file ensuring correct interleaving.
2467
 
 *
2468
 
 * The packet must contain one audio or video frame.
2469
 
 * If the packets are already correctly interleaved the application should
2470
 
 * call av_write_frame() instead as its slightly faster, its also important
2471
 
 * to keep in mind that completly non interleaved input will need huge amounts
2472
 
 * of memory to interleave with this, so its prefereable to interleave at the
2473
 
 * demuxer level
2474
 
 *
2475
 
 * @param s media file handle
2476
 
 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2477
 
 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2478
 
 */
2479
2498
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2480
2499
    AVStream *st= s->streams[ pkt->stream_index];
2481
2500
 
2504
2523
 
2505
2524
        if(ret<0)
2506
2525
            return ret;
2507
 
        if(url_ferror(&s->pb))
2508
 
            return url_ferror(&s->pb);
 
2526
        if(url_ferror(s->pb))
 
2527
            return url_ferror(s->pb);
2509
2528
    }
2510
2529
}
2511
2530
 
2512
 
/**
2513
 
 * @brief Write the stream trailer to an output media file and
2514
 
 *        free the file private data.
2515
 
 *
2516
 
 * @param s media file handle
2517
 
 * @return 0 if OK. AVERROR_xxx if error.
2518
 
 */
2519
2531
int av_write_trailer(AVFormatContext *s)
2520
2532
{
2521
2533
    int ret, i;
2535
2547
 
2536
2548
        if(ret<0)
2537
2549
            goto fail;
2538
 
        if(url_ferror(&s->pb))
 
2550
        if(url_ferror(s->pb))
2539
2551
            goto fail;
2540
2552
    }
2541
2553
 
2543
2555
        ret = s->oformat->write_trailer(s);
2544
2556
fail:
2545
2557
    if(ret == 0)
2546
 
       ret=url_ferror(&s->pb);
 
2558
       ret=url_ferror(s->pb);
2547
2559
    for(i=0;i<s->nb_streams;i++)
2548
2560
        av_freep(&s->streams[i]->priv_data);
2549
2561
    av_freep(&s->priv_data);
2550
2562
    return ret;
2551
2563
}
2552
2564
 
 
2565
void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
 
2566
{
 
2567
    int i, j;
 
2568
    AVProgram *program=NULL;
 
2569
    void *tmp;
 
2570
 
 
2571
    for(i=0; i<ac->nb_programs; i++){
 
2572
        if(ac->programs[i]->id != progid)
 
2573
            continue;
 
2574
        program = ac->programs[i];
 
2575
        for(j=0; j<program->nb_stream_indexes; j++)
 
2576
            if(program->stream_index[j] == idx)
 
2577
                return;
 
2578
 
 
2579
        tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
 
2580
        if(!tmp)
 
2581
            return;
 
2582
        program->stream_index = tmp;
 
2583
        program->stream_index[program->nb_stream_indexes++] = idx;
 
2584
        return;
 
2585
    }
 
2586
}
 
2587
 
2553
2588
/* "user interface" functions */
 
2589
static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
 
2590
{
 
2591
    char buf[256];
 
2592
    int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
 
2593
    AVStream *st = ic->streams[i];
 
2594
    int g = ff_gcd(st->time_base.num, st->time_base.den);
 
2595
    avcodec_string(buf, sizeof(buf), st->codec, is_output);
 
2596
    av_log(NULL, AV_LOG_INFO, "    Stream #%d.%d", index, i);
 
2597
    /* the pid is an important information, so we display it */
 
2598
    /* XXX: add a generic system */
 
2599
    if (flags & AVFMT_SHOW_IDS)
 
2600
        av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
 
2601
    if (strlen(st->language) > 0)
 
2602
        av_log(NULL, AV_LOG_INFO, "(%s)", st->language);
 
2603
    av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);
 
2604
    av_log(NULL, AV_LOG_INFO, ": %s", buf);
 
2605
    if(st->codec->codec_type == CODEC_TYPE_VIDEO){
 
2606
        if(st->r_frame_rate.den && st->r_frame_rate.num)
 
2607
            av_log(NULL, AV_LOG_INFO, ", %5.2f tb(r)", av_q2d(st->r_frame_rate));
 
2608
/*      else if(st->time_base.den && st->time_base.num)
 
2609
            av_log(NULL, AV_LOG_INFO, ", %5.2f tb(m)", 1/av_q2d(st->time_base));*/
 
2610
        else
 
2611
            av_log(NULL, AV_LOG_INFO, ", %5.2f tb(c)", 1/av_q2d(st->codec->time_base));
 
2612
    }
 
2613
    av_log(NULL, AV_LOG_INFO, "\n");
 
2614
}
2554
2615
 
2555
2616
void dump_format(AVFormatContext *ic,
2556
2617
                 int index,
2557
2618
                 const char *url,
2558
2619
                 int is_output)
2559
2620
{
2560
 
    int i, flags;
2561
 
    char buf[256];
 
2621
    int i;
2562
2622
 
2563
2623
    av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2564
2624
            is_output ? "Output" : "Input",
2575
2635
            secs %= 60;
2576
2636
            hours = mins / 60;
2577
2637
            mins %= 60;
2578
 
            av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%01d", hours, mins, secs,
2579
 
                   (10 * us) / AV_TIME_BASE);
 
2638
            av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
 
2639
                   (100 * us) / AV_TIME_BASE);
2580
2640
        } else {
2581
2641
            av_log(NULL, AV_LOG_INFO, "N/A");
2582
2642
        }
2596
2656
        }
2597
2657
        av_log(NULL, AV_LOG_INFO, "\n");
2598
2658
    }
2599
 
    for(i=0;i<ic->nb_streams;i++) {
2600
 
        AVStream *st = ic->streams[i];
2601
 
        int g= ff_gcd(st->time_base.num, st->time_base.den);
2602
 
        avcodec_string(buf, sizeof(buf), st->codec, is_output);
2603
 
        av_log(NULL, AV_LOG_INFO, "  Stream #%d.%d", index, i);
2604
 
        /* the pid is an important information, so we display it */
2605
 
        /* XXX: add a generic system */
2606
 
        if (is_output)
2607
 
            flags = ic->oformat->flags;
2608
 
        else
2609
 
            flags = ic->iformat->flags;
2610
 
        if (flags & AVFMT_SHOW_IDS) {
2611
 
            av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2612
 
        }
2613
 
        if (strlen(st->language) > 0) {
2614
 
            av_log(NULL, AV_LOG_INFO, "(%s)", st->language);
2615
 
        }
2616
 
        av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);
2617
 
        av_log(NULL, AV_LOG_INFO, ": %s", buf);
2618
 
        if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2619
 
            if(st->r_frame_rate.den && st->r_frame_rate.num)
2620
 
                av_log(NULL, AV_LOG_INFO, ", %5.2f fps(r)", av_q2d(st->r_frame_rate));
2621
 
/*            else if(st->time_base.den && st->time_base.num)
2622
 
                av_log(NULL, AV_LOG_INFO, ", %5.2f fps(m)", 1/av_q2d(st->time_base));*/
2623
 
            else
2624
 
                av_log(NULL, AV_LOG_INFO, ", %5.2f fps(c)", 1/av_q2d(st->codec->time_base));
2625
 
        }
2626
 
        av_log(NULL, AV_LOG_INFO, "\n");
2627
 
    }
 
2659
    if(ic->nb_programs) {
 
2660
        int j, k;
 
2661
        for(j=0; j<ic->nb_programs; j++) {
 
2662
            av_log(NULL, AV_LOG_INFO, "  Program %d %s\n", ic->programs[j]->id,
 
2663
                   ic->programs[j]->name ? ic->programs[j]->name : "");
 
2664
            for(k=0; k<ic->programs[j]->nb_stream_indexes; k++)
 
2665
                dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
 
2666
         }
 
2667
    } else
 
2668
    for(i=0;i<ic->nb_streams;i++)
 
2669
        dump_stream_format(ic, i, index, is_output);
2628
2670
}
2629
2671
 
2630
 
typedef struct {
2631
 
    const char *abv;
2632
 
    int width, height;
2633
 
    int frame_rate, frame_rate_base;
2634
 
} AbvEntry;
2635
 
 
2636
 
static AbvEntry frame_abvs[] = {
2637
 
    { "ntsc",      720, 480, 30000, 1001 },
2638
 
    { "pal",       720, 576,    25,    1 },
2639
 
    { "qntsc",     352, 240, 30000, 1001 }, /* VCD compliant ntsc */
2640
 
    { "qpal",      352, 288,    25,    1 }, /* VCD compliant pal */
2641
 
    { "sntsc",     640, 480, 30000, 1001 }, /* square pixel ntsc */
2642
 
    { "spal",      768, 576,    25,    1 }, /* square pixel pal */
2643
 
    { "film",      352, 240,    24,    1 },
2644
 
    { "ntsc-film", 352, 240, 24000, 1001 },
2645
 
    { "sqcif",     128,  96,     0,    0 },
2646
 
    { "qcif",      176, 144,     0,    0 },
2647
 
    { "cif",       352, 288,     0,    0 },
2648
 
    { "4cif",      704, 576,     0,    0 },
2649
 
};
2650
 
 
2651
 
/**
2652
 
 * parses width and height out of string str.
2653
 
 */
2654
2672
int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2655
2673
{
2656
 
    int i;
2657
 
    int n = sizeof(frame_abvs) / sizeof(AbvEntry);
2658
 
    const char *p;
2659
 
    int frame_width = 0, frame_height = 0;
2660
 
 
2661
 
    for(i=0;i<n;i++) {
2662
 
        if (!strcmp(frame_abvs[i].abv, str)) {
2663
 
            frame_width = frame_abvs[i].width;
2664
 
            frame_height = frame_abvs[i].height;
2665
 
            break;
2666
 
        }
2667
 
    }
2668
 
    if (i == n) {
2669
 
        p = str;
2670
 
        frame_width = strtol(p, (char **)&p, 10);
2671
 
        if (*p)
2672
 
            p++;
2673
 
        frame_height = strtol(p, (char **)&p, 10);
2674
 
    }
2675
 
    if (frame_width <= 0 || frame_height <= 0)
2676
 
        return -1;
2677
 
    *width_ptr = frame_width;
2678
 
    *height_ptr = frame_height;
2679
 
    return 0;
2680
 
}
2681
 
 
2682
 
/**
2683
 
 * Converts frame rate from string to a fraction.
2684
 
 *
2685
 
 * First we try to get an exact integer or fractional frame rate.
2686
 
 * If this fails we convert the frame rate to a double and return
2687
 
 * an approximate fraction using the DEFAULT_FRAME_RATE_BASE.
2688
 
 */
2689
 
int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
2690
 
{
2691
 
    int i;
2692
 
    char* cp;
2693
 
 
2694
 
    /* First, we check our abbreviation table */
2695
 
    for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
2696
 
         if (!strcmp(frame_abvs[i].abv, arg)) {
2697
 
             *frame_rate = frame_abvs[i].frame_rate;
2698
 
             *frame_rate_base = frame_abvs[i].frame_rate_base;
2699
 
             return 0;
2700
 
         }
2701
 
 
2702
 
    /* Then, we try to parse it as fraction */
2703
 
    cp = strchr(arg, '/');
2704
 
    if (!cp)
2705
 
        cp = strchr(arg, ':');
2706
 
    if (cp) {
2707
 
        char* cpp;
2708
 
        *frame_rate = strtol(arg, &cpp, 10);
2709
 
        if (cpp != arg || cpp == cp)
2710
 
            *frame_rate_base = strtol(cp+1, &cpp, 10);
2711
 
        else
2712
 
           *frame_rate = 0;
2713
 
    }
2714
 
    else {
2715
 
        /* Finally we give up and parse it as double */
2716
 
        AVRational time_base = av_d2q(strtod(arg, 0), DEFAULT_FRAME_RATE_BASE);
2717
 
        *frame_rate_base = time_base.den;
2718
 
        *frame_rate = time_base.num;
2719
 
    }
2720
 
    if (!*frame_rate || !*frame_rate_base)
2721
 
        return -1;
2722
 
    else
2723
 
        return 0;
2724
 
}
2725
 
 
2726
 
/**
2727
 
 * Converts date string to number of seconds since Jan 1st, 1970.
2728
 
 *
2729
 
 * @code
2730
 
 * Syntax:
2731
 
 * - If not a duration:
2732
 
 *  [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
2733
 
 * Time is localtime unless Z is suffixed to the end. In this case GMT
2734
 
 * Return the date in micro seconds since 1970
2735
 
 *
2736
 
 * - If a duration:
2737
 
 *  HH[:MM[:SS[.m...]]]
2738
 
 *  S+[.m...]
2739
 
 * @endcode
2740
 
 */
2741
 
#ifndef CONFIG_WINCE
 
2674
    return av_parse_video_frame_size(width_ptr, height_ptr, str);
 
2675
}
 
2676
 
 
2677
int parse_frame_rate(int *frame_rate_num, int *frame_rate_den, const char *arg)
 
2678
{
 
2679
    AVRational frame_rate;
 
2680
    int ret = av_parse_video_frame_rate(&frame_rate, arg);
 
2681
    *frame_rate_num= frame_rate.num;
 
2682
    *frame_rate_den= frame_rate.den;
 
2683
    return ret;
 
2684
}
 
2685
 
 
2686
/**
 
2687
 * Gets the current time in microseconds.
 
2688
 */
 
2689
int64_t av_gettime(void)
 
2690
{
 
2691
    struct timeval tv;
 
2692
    gettimeofday(&tv,NULL);
 
2693
    return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
 
2694
}
 
2695
 
2742
2696
int64_t parse_date(const char *datestr, int duration)
2743
2697
{
2744
2698
    const char *p;
2773
2727
    p = datestr;
2774
2728
    q = NULL;
2775
2729
    if (!duration) {
 
2730
        /* parse the year-month-day part */
2776
2731
        for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
2777
2732
            q = small_strptime(p, date_fmt[i], &dt);
2778
2733
            if (q) {
2780
2735
            }
2781
2736
        }
2782
2737
 
 
2738
        /* if the year-month-day part is missing, then take the
 
2739
         * current year-month-day time */
2783
2740
        if (!q) {
2784
2741
            if (is_utc) {
2785
2742
                dt = *gmtime(&now);
2794
2751
        if (*p == 'T' || *p == 't' || *p == ' ')
2795
2752
            p++;
2796
2753
 
 
2754
        /* parse the hour-minute-second part */
2797
2755
        for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
2798
2756
            q = small_strptime(p, time_fmt[i], &dt);
2799
2757
            if (q) {
2801
2759
            }
2802
2760
        }
2803
2761
    } else {
 
2762
        /* parse datestr as a duration */
2804
2763
        if (p[0] == '-') {
2805
2764
            negative = 1;
2806
2765
            ++p;
2807
2766
        }
 
2767
        /* parse datestr as HH:MM:SS */
2808
2768
        q = small_strptime(p, time_fmt[0], &dt);
2809
2769
        if (!q) {
 
2770
            /* parse datestr as S+ */
2810
2771
            dt.tm_sec = strtol(p, (char **)&q, 10);
 
2772
            if (q == p)
 
2773
                /* the parsing didn't succeed */
 
2774
                return INT64_MIN;
2811
2775
            dt.tm_min = 0;
2812
2776
            dt.tm_hour = 0;
2813
2777
        }
2815
2779
 
2816
2780
    /* Now we have all the fields that we can get */
2817
2781
    if (!q) {
2818
 
        if (duration)
2819
 
            return 0;
2820
 
        else
2821
 
            return now * INT64_C(1000000);
 
2782
        return INT64_MIN;
2822
2783
    }
2823
2784
 
2824
2785
    if (duration) {
2834
2795
 
2835
2796
    t *= 1000000;
2836
2797
 
 
2798
    /* parse the .m... part */
2837
2799
    if (*q == '.') {
2838
2800
        int val, n;
2839
2801
        q++;
2846
2808
    }
2847
2809
    return negative ? -t : t;
2848
2810
}
2849
 
#endif /* CONFIG_WINCE */
2850
2811
 
2851
 
/**
2852
 
 * Attempts to find a specific tag in a URL.
2853
 
 *
2854
 
 * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done.
2855
 
 * Return 1 if found.
2856
 
 */
2857
2812
int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2858
2813
{
2859
2814
    const char *p;
2893
2848
    return 0;
2894
2849
}
2895
2850
 
2896
 
/**
2897
 
 * Returns in 'buf' the path with '%d' replaced by number.
2898
 
 
2899
 
 * Also handles the '%0nd' format where 'n' is the total number
2900
 
 * of digits and '%%'.
2901
 
 *
2902
 
 * @param buf destination buffer
2903
 
 * @param buf_size destination buffer size
2904
 
 * @param path numbered sequence string
2905
 
 * @number frame number
2906
 
 * @return 0 if OK, -1 if format error.
2907
 
 */
2908
2851
int av_get_frame_filename(char *buf, int buf_size,
2909
2852
                          const char *path, int number)
2910
2853
{
2960
2903
    return -1;
2961
2904
}
2962
2905
 
2963
 
/**
2964
 
 * Print  nice hexa dump of a buffer
2965
 
 * @param f stream for output
2966
 
 * @param buf buffer
2967
 
 * @param size buffer size
2968
 
 */
2969
 
void av_hex_dump(FILE *f, uint8_t *buf, int size)
 
2906
static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
2970
2907
{
2971
2908
    int len, i, j, c;
 
2909
#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
2972
2910
 
2973
2911
    for(i=0;i<size;i+=16) {
2974
2912
        len = size - i;
2975
2913
        if (len > 16)
2976
2914
            len = 16;
2977
 
        fprintf(f, "%08x ", i);
 
2915
        PRINT("%08x ", i);
2978
2916
        for(j=0;j<16;j++) {
2979
2917
            if (j < len)
2980
 
                fprintf(f, " %02x", buf[i+j]);
 
2918
                PRINT(" %02x", buf[i+j]);
2981
2919
            else
2982
 
                fprintf(f, "   ");
 
2920
                PRINT("   ");
2983
2921
        }
2984
 
        fprintf(f, " ");
 
2922
        PRINT(" ");
2985
2923
        for(j=0;j<len;j++) {
2986
2924
            c = buf[i+j];
2987
2925
            if (c < ' ' || c > '~')
2988
2926
                c = '.';
2989
 
            fprintf(f, "%c", c);
 
2927
            PRINT("%c", c);
2990
2928
        }
2991
 
        fprintf(f, "\n");
 
2929
        PRINT("\n");
2992
2930
    }
2993
 
}
2994
 
 
2995
 
/**
2996
 
 * Print on 'f' a nice dump of a packet
2997
 
 * @param f stream for output
2998
 
 * @param pkt packet to dump
2999
 
 * @param dump_payload true if the payload must be displayed too
3000
 
 */
 
2931
#undef PRINT
 
2932
}
 
2933
 
 
2934
void av_hex_dump(FILE *f, uint8_t *buf, int size)
 
2935
{
 
2936
    hex_dump_internal(NULL, f, 0, buf, size);
 
2937
}
 
2938
 
 
2939
void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
 
2940
{
 
2941
    hex_dump_internal(avcl, NULL, level, buf, size);
 
2942
}
 
2943
 
3001
2944
 //FIXME needs to know the time_base
3002
 
void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
 
2945
static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload)
3003
2946
{
3004
 
    fprintf(f, "stream #%d:\n", pkt->stream_index);
3005
 
    fprintf(f, "  keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
3006
 
    fprintf(f, "  duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
 
2947
#define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
 
2948
    PRINT("stream #%d:\n", pkt->stream_index);
 
2949
    PRINT("  keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
 
2950
    PRINT("  duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
3007
2951
    /* DTS is _always_ valid after av_read_frame() */
3008
 
    fprintf(f, "  dts=");
 
2952
    PRINT("  dts=");
3009
2953
    if (pkt->dts == AV_NOPTS_VALUE)
3010
 
        fprintf(f, "N/A");
 
2954
        PRINT("N/A");
3011
2955
    else
3012
 
        fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
3013
 
    /* PTS may be not known if B frames are present */
3014
 
    fprintf(f, "  pts=");
 
2956
        PRINT("%0.3f", (double)pkt->dts / AV_TIME_BASE);
 
2957
    /* PTS may not be known if B-frames are present. */
 
2958
    PRINT("  pts=");
3015
2959
    if (pkt->pts == AV_NOPTS_VALUE)
3016
 
        fprintf(f, "N/A");
 
2960
        PRINT("N/A");
3017
2961
    else
3018
 
        fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
3019
 
    fprintf(f, "\n");
3020
 
    fprintf(f, "  size=%d\n", pkt->size);
 
2962
        PRINT("%0.3f", (double)pkt->pts / AV_TIME_BASE);
 
2963
    PRINT("\n");
 
2964
    PRINT("  size=%d\n", pkt->size);
 
2965
#undef PRINT
3021
2966
    if (dump_payload)
3022
2967
        av_hex_dump(f, pkt->data, pkt->size);
3023
2968
}
3024
2969
 
 
2970
void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
 
2971
{
 
2972
    pkt_dump_internal(NULL, f, 0, pkt, dump_payload);
 
2973
}
 
2974
 
 
2975
void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
 
2976
{
 
2977
    pkt_dump_internal(avcl, NULL, level, pkt, dump_payload);
 
2978
}
 
2979
 
3025
2980
void url_split(char *proto, int proto_size,
3026
2981
               char *authorization, int authorization_size,
3027
2982
               char *hostname, int hostname_size,
3029
2984
               char *path, int path_size,
3030
2985
               const char *url)
3031
2986
{
3032
 
    const char *p;
3033
 
    char *q;
3034
 
    int port;
3035
 
 
3036
 
    port = -1;
3037
 
 
3038
 
    p = url;
3039
 
    q = proto;
3040
 
    while (*p != ':' && *p != '\0') {
3041
 
        if ((q - proto) < proto_size - 1)
3042
 
            *q++ = *p;
3043
 
        p++;
3044
 
    }
3045
 
    if (proto_size > 0)
3046
 
        *q = '\0';
3047
 
    if (authorization_size > 0)
3048
 
        authorization[0] = '\0';
3049
 
    if (*p == '\0') {
3050
 
        if (proto_size > 0)
3051
 
            proto[0] = '\0';
3052
 
        if (hostname_size > 0)
3053
 
            hostname[0] = '\0';
3054
 
        p = url;
 
2987
    const char *p, *ls, *at, *col, *brk;
 
2988
 
 
2989
    if (port_ptr)               *port_ptr = -1;
 
2990
    if (proto_size > 0)         proto[0] = 0;
 
2991
    if (authorization_size > 0) authorization[0] = 0;
 
2992
    if (hostname_size > 0)      hostname[0] = 0;
 
2993
    if (path_size > 0)          path[0] = 0;
 
2994
 
 
2995
    /* parse protocol */
 
2996
    if ((p = strchr(url, ':'))) {
 
2997
        av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
 
2998
        p++; /* skip ':' */
 
2999
        if (*p == '/') p++;
 
3000
        if (*p == '/') p++;
3055
3001
    } else {
3056
 
        char *at,*slash; // PETR: position of '@' character and '/' character
3057
 
 
3058
 
        p++;
3059
 
        if (*p == '/')
3060
 
            p++;
3061
 
        if (*p == '/')
3062
 
            p++;
3063
 
        at = strchr(p,'@'); // PETR: get the position of '@'
3064
 
        slash = strchr(p,'/');  // PETR: get position of '/' - end of hostname
3065
 
        if (at && slash && at > slash) at = NULL; // PETR: not interested in '@' behind '/'
3066
 
 
3067
 
        q = at ? authorization : hostname;  // PETR: if '@' exists starting with auth.
3068
 
 
3069
 
         while ((at || *p != ':') && *p != '/' && *p != '?' && *p != '\0') { // PETR:
3070
 
            if (*p == '@') {    // PETR: passed '@'
3071
 
              if (authorization_size > 0)
3072
 
                  *q = '\0';
3073
 
              q = hostname;
3074
 
              at = NULL;
3075
 
            } else if (!at) {   // PETR: hostname
3076
 
              if ((q - hostname) < hostname_size - 1)
3077
 
                  *q++ = *p;
3078
 
            } else {
3079
 
              if ((q - authorization) < authorization_size - 1)
3080
 
                *q++ = *p;
3081
 
            }
3082
 
            p++;
3083
 
        }
3084
 
        if (hostname_size > 0)
3085
 
            *q = '\0';
3086
 
        if (*p == ':') {
3087
 
            p++;
3088
 
            port = strtoul(p, (char **)&p, 10);
3089
 
        }
3090
 
    }
3091
 
    if (port_ptr)
3092
 
        *port_ptr = port;
3093
 
    pstrcpy(path, path_size, p);
 
3002
        /* no protocol means plain filename */
 
3003
        av_strlcpy(path, url, path_size);
 
3004
        return;
 
3005
    }
 
3006
 
 
3007
    /* separate path from hostname */
 
3008
    ls = strchr(p, '/');
 
3009
    if(!ls)
 
3010
        ls = strchr(p, '?');
 
3011
    if(ls)
 
3012
        av_strlcpy(path, ls, path_size);
 
3013
    else
 
3014
        ls = &p[strlen(p)]; // XXX
 
3015
 
 
3016
    /* the rest is hostname, use that to parse auth/port */
 
3017
    if (ls != p) {
 
3018
        /* authorization (user[:pass]@hostname) */
 
3019
        if ((at = strchr(p, '@')) && at < ls) {
 
3020
            av_strlcpy(authorization, p,
 
3021
                       FFMIN(authorization_size, at + 1 - p));
 
3022
            p = at + 1; /* skip '@' */
 
3023
        }
 
3024
 
 
3025
        if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
 
3026
            /* [host]:port */
 
3027
            av_strlcpy(hostname, p + 1,
 
3028
                       FFMIN(hostname_size, brk - p));
 
3029
            if (brk[1] == ':' && port_ptr)
 
3030
                *port_ptr = atoi(brk + 2);
 
3031
        } else if ((col = strchr(p, ':')) && col < ls) {
 
3032
            av_strlcpy(hostname, p,
 
3033
                       FFMIN(col + 1 - p, hostname_size));
 
3034
            if (port_ptr) *port_ptr = atoi(col + 1);
 
3035
        } else
 
3036
            av_strlcpy(hostname, p,
 
3037
                       FFMIN(ls + 1 - p, hostname_size));
 
3038
    }
3094
3039
}
3095
3040
 
3096
 
/**
3097
 
 * Set the pts for a given stream.
3098
 
 *
3099
 
 * @param s stream
3100
 
 * @param pts_wrap_bits number of bits effectively used by the pts
3101
 
 *        (used for wrap control, 33 is the value for MPEG)
3102
 
 * @param pts_num numerator to convert to seconds (MPEG: 1)
3103
 
 * @param pts_den denominator to convert to seconds (MPEG: 90000)
3104
 
 */
3105
3041
void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3106
3042
                     int pts_num, int pts_den)
3107
3043
{
3135
3071
}
3136
3072
 
3137
3073
/**
3138
 
 * Fractionnal addition to f: f = f + (incr / f->den).
 
3074
 * Fractional addition to f: f = f + (incr / f->den).
3139
3075
 *
3140
3076
 * @param f fractional number
3141
3077
 * @param incr increment, can be positive or negative