Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ 61c7c3e3

History | View | Annotate | Download (82.6 KB)

1
/*
2
 * Various utilities for ffmpeg system
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 */
19
#include "avformat.h"
20

    
21
#undef NDEBUG
22
#include <assert.h>
23

    
24
AVInputFormat *first_iformat = NULL;
25
AVOutputFormat *first_oformat = NULL;
26
AVImageFormat *first_image_format = NULL;
27

    
28
void av_register_input_format(AVInputFormat *format)
29
{
30
    AVInputFormat **p;
31
    p = &first_iformat;
32
    while (*p != NULL) p = &(*p)->next;
33
    *p = format;
34
    format->next = NULL;
35
}
36

    
37
void av_register_output_format(AVOutputFormat *format)
38
{
39
    AVOutputFormat **p;
40
    p = &first_oformat;
41
    while (*p != NULL) p = &(*p)->next;
42
    *p = format;
43
    format->next = NULL;
44
}
45

    
46
int match_ext(const char *filename, const char *extensions)
47
{
48
    const char *ext, *p;
49
    char ext1[32], *q;
50

    
51
    if(!filename)
52
        return 0;
53
    
54
    ext = strrchr(filename, '.');
55
    if (ext) {
56
        ext++;
57
        p = extensions;
58
        for(;;) {
59
            q = ext1;
60
            while (*p != '\0' && *p != ',') 
61
                *q++ = *p++;
62
            *q = '\0';
63
            if (!strcasecmp(ext1, ext)) 
64
                return 1;
65
            if (*p == '\0') 
66
                break;
67
            p++;
68
        }
69
    }
70
    return 0;
71
}
72

    
73
AVOutputFormat *guess_format(const char *short_name, const char *filename, 
74
                             const char *mime_type)
75
{
76
    AVOutputFormat *fmt, *fmt_found;
77
    int score_max, score;
78

    
79
    /* specific test for image sequences */
80
    if (!short_name && filename && 
81
        filename_number_test(filename) >= 0 &&
82
        av_guess_image2_codec(filename) != CODEC_ID_NONE) {
83
        return guess_format("image2", NULL, NULL);
84
    }
85
    if (!short_name && filename && 
86
        filename_number_test(filename) >= 0 &&
87
        guess_image_format(filename)) {
88
        return guess_format("image", NULL, NULL);
89
    }
90

    
91
    /* find the proper file type */
92
    fmt_found = NULL;
93
    score_max = 0;
94
    fmt = first_oformat;
95
    while (fmt != NULL) {
96
        score = 0;
97
        if (fmt->name && short_name && !strcmp(fmt->name, short_name))
98
            score += 100;
99
        if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
100
            score += 10;
101
        if (filename && fmt->extensions && 
102
            match_ext(filename, fmt->extensions)) {
103
            score += 5;
104
        }
105
        if (score > score_max) {
106
            score_max = score;
107
            fmt_found = fmt;
108
        }
109
        fmt = fmt->next;
110
    }
111
    return fmt_found;
112
}   
113

    
114
AVOutputFormat *guess_stream_format(const char *short_name, const char *filename, 
115
                             const char *mime_type)
116
{
117
    AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
118

    
119
    if (fmt) {
120
        AVOutputFormat *stream_fmt;
121
        char stream_format_name[64];
122

    
123
        snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
124
        stream_fmt = guess_format(stream_format_name, NULL, NULL);
125

    
126
        if (stream_fmt)
127
            fmt = stream_fmt;
128
    }
129

    
130
    return fmt;
131
}
132

    
133
/**
134
 * guesses the codec id based upon muxer and filename.
135
 */
136
enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name, 
137
                            const char *filename, const char *mime_type, enum CodecType type){
138
    if(type == CODEC_TYPE_VIDEO){
139
        enum CodecID codec_id= CODEC_ID_NONE;
140

    
141
        if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
142
            codec_id= av_guess_image2_codec(filename);
143
        }
144
        if(codec_id == CODEC_ID_NONE)
145
            codec_id= fmt->video_codec;
146
        return codec_id;
147
    }else if(type == CODEC_TYPE_AUDIO)
148
        return fmt->audio_codec;
149
    else
150
        return CODEC_ID_NONE;
151
}
152

    
153
AVInputFormat *av_find_input_format(const char *short_name)
154
{
155
    AVInputFormat *fmt;
156
    for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
157
        if (!strcmp(fmt->name, short_name))
158
            return fmt;
159
    }
160
    return NULL;
161
}
162

    
163
/* memory handling */
164

    
165
/**
166
 * Default packet destructor 
167
 */
168
static void av_destruct_packet(AVPacket *pkt)
169
{
170
    av_free(pkt->data);
171
    pkt->data = NULL; pkt->size = 0;
172
}
173

    
174
/**
175
 * Allocate the payload of a packet and intialized its fields to default values.
176
 *
177
 * @param pkt packet
178
 * @param size wanted payload size
179
 * @return 0 if OK. AVERROR_xxx otherwise.
180
 */
181
int av_new_packet(AVPacket *pkt, int size)
182
{
183
    void *data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
184
    if (!data)
185
        return AVERROR_NOMEM;
186
    memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
187

    
188
    av_init_packet(pkt);
189
    pkt->data = data; 
190
    pkt->size = size;
191
    pkt->destruct = av_destruct_packet;
192
    return 0;
193
}
194

    
195
/* This is a hack - the packet memory allocation stuff is broken. The
196
   packet is allocated if it was not really allocated */
197
int av_dup_packet(AVPacket *pkt)
198
{
199
    if (pkt->destruct != av_destruct_packet) {
200
        uint8_t *data;
201
        /* we duplicate the packet and don't forget to put the padding
202
           again */
203
        data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
204
        if (!data) {
205
            return AVERROR_NOMEM;
206
        }
207
        memcpy(data, pkt->data, pkt->size);
208
        memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
209
        pkt->data = data;
210
        pkt->destruct = av_destruct_packet;
211
    }
212
    return 0;
213
}
214

    
215
/* fifo handling */
216

    
217
int fifo_init(FifoBuffer *f, int size)
218
{
219
    f->buffer = av_malloc(size);
220
    if (!f->buffer)
221
        return -1;
222
    f->end = f->buffer + size;
223
    f->wptr = f->rptr = f->buffer;
224
    return 0;
225
}
226

    
227
void fifo_free(FifoBuffer *f)
228
{
229
    av_free(f->buffer);
230
}
231

    
232
int fifo_size(FifoBuffer *f, uint8_t *rptr)
233
{
234
    int size;
235

    
236
    if (f->wptr >= rptr) {
237
        size = f->wptr - rptr;
238
    } else {
239
        size = (f->end - rptr) + (f->wptr - f->buffer);
240
    }
241
    return size;
242
}
243

    
244
/* get data from the fifo (return -1 if not enough data) */
245
int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
246
{
247
    uint8_t *rptr = *rptr_ptr;
248
    int size, len;
249

    
250
    if (f->wptr >= rptr) {
251
        size = f->wptr - rptr;
252
    } else {
253
        size = (f->end - rptr) + (f->wptr - f->buffer);
254
    }
255
    
256
    if (size < buf_size)
257
        return -1;
258
    while (buf_size > 0) {
259
        len = f->end - rptr;
260
        if (len > buf_size)
261
            len = buf_size;
262
        memcpy(buf, rptr, len);
263
        buf += len;
264
        rptr += len;
265
        if (rptr >= f->end)
266
            rptr = f->buffer;
267
        buf_size -= len;
268
    }
269
    *rptr_ptr = rptr;
270
    return 0;
271
}
272

    
273
void fifo_write(FifoBuffer *f, uint8_t *buf, int size, uint8_t **wptr_ptr)
274
{
275
    int len;
276
    uint8_t *wptr;
277
    wptr = *wptr_ptr;
278
    while (size > 0) {
279
        len = f->end - wptr;
280
        if (len > size)
281
            len = size;
282
        memcpy(wptr, buf, len);
283
        wptr += len;
284
        if (wptr >= f->end)
285
            wptr = f->buffer;
286
        buf += len;
287
        size -= len;
288
    }
289
    *wptr_ptr = wptr;
290
}
291

    
292
/* get data from the fifo (return -1 if not enough data) */
293
int put_fifo(ByteIOContext *pb, FifoBuffer *f, int buf_size, uint8_t **rptr_ptr)
294
{
295
    uint8_t *rptr = *rptr_ptr;
296
    int size, len;
297

    
298
    if (f->wptr >= rptr) {
299
        size = f->wptr - rptr;
300
    } else {
301
        size = (f->end - rptr) + (f->wptr - f->buffer);
302
    }
303
    
304
    if (size < buf_size)
305
        return -1;
306
    while (buf_size > 0) {
307
        len = f->end - rptr;
308
        if (len > buf_size)
309
            len = buf_size;
310
        put_buffer(pb, rptr, len);
311
        rptr += len;
312
        if (rptr >= f->end)
313
            rptr = f->buffer;
314
        buf_size -= len;
315
    }
316
    *rptr_ptr = rptr;
317
    return 0;
318
}
319

    
320
int filename_number_test(const char *filename)
321
{
322
    char buf[1024];
323
    if(!filename)
324
        return -1;
325
    return get_frame_filename(buf, sizeof(buf), filename, 1);
326
}
327

    
328
/* guess file format */
329
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
330
{
331
    AVInputFormat *fmt1, *fmt;
332
    int score, score_max;
333

    
334
    fmt = NULL;
335
    score_max = 0;
336
    for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
337
        if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
338
            continue;
339
        score = 0;
340
        if (fmt1->read_probe) {
341
            score = fmt1->read_probe(pd);
342
        } else if (fmt1->extensions) {
343
            if (match_ext(pd->filename, fmt1->extensions)) {
344
                score = 50;
345
            }
346
        } 
347
        if (score > score_max) {
348
            score_max = score;
349
            fmt = fmt1;
350
        }
351
    }
352
    return fmt;
353
}
354

    
355
/************************************************************/
356
/* input media file */
357

    
358
/**
359
 * open a media file from an IO stream. 'fmt' must be specified.
360
 */
361

    
362
static const char* format_to_name(void* ptr)
363
{
364
    AVFormatContext* fc = (AVFormatContext*) ptr;
365
    if(fc->iformat) return fc->iformat->name;
366
    else if(fc->oformat) return fc->oformat->name;
367
    else return "NULL";
368
}
369

    
370
static const AVClass av_format_context_class = { "AVFormatContext", format_to_name };
371

    
372
AVFormatContext *av_alloc_format_context(void)
373
{
374
    AVFormatContext *ic;
375
    ic = av_mallocz(sizeof(AVFormatContext));
376
    if (!ic) return ic;
377
    ic->av_class = &av_format_context_class;
378
    return ic;
379
}
380

    
381
int av_open_input_stream(AVFormatContext **ic_ptr, 
382
                         ByteIOContext *pb, const char *filename, 
383
                         AVInputFormat *fmt, AVFormatParameters *ap)
384
{
385
    int err;
386
    AVFormatContext *ic;
387

    
388
    ic = av_alloc_format_context();
389
    if (!ic) {
390
        err = AVERROR_NOMEM;
391
        goto fail;
392
    }
393
    ic->iformat = fmt;
394
    if (pb)
395
        ic->pb = *pb;
396
    ic->duration = AV_NOPTS_VALUE;
397
    ic->start_time = AV_NOPTS_VALUE;
398
    pstrcpy(ic->filename, sizeof(ic->filename), filename);
399

    
400
    /* allocate private data */
401
    if (fmt->priv_data_size > 0) {
402
        ic->priv_data = av_mallocz(fmt->priv_data_size);
403
        if (!ic->priv_data) {
404
            err = AVERROR_NOMEM;
405
            goto fail;
406
        }
407
    } else {
408
        ic->priv_data = NULL;
409
    }
410

    
411
    err = ic->iformat->read_header(ic, ap);
412
    if (err < 0)
413
        goto fail;
414

    
415
    if (pb)
416
        ic->data_offset = url_ftell(&ic->pb);
417

    
418
    *ic_ptr = ic;
419
    return 0;
420
 fail:
421
    if (ic) {
422
        av_freep(&ic->priv_data);
423
    }
424
    av_free(ic);
425
    *ic_ptr = NULL;
426
    return err;
427
}
428

    
429
#define PROBE_BUF_SIZE 2048
430

    
431
/**
432
 * Open a media file as input. The codec are not opened. Only the file
433
 * header (if present) is read.
434
 *
435
 * @param ic_ptr the opened media file handle is put here
436
 * @param filename filename to open.
437
 * @param fmt if non NULL, force the file format to use
438
 * @param buf_size optional buffer size (zero if default is OK)
439
 * @param ap additionnal parameters needed when opening the file (NULL if default)
440
 * @return 0 if OK. AVERROR_xxx otherwise.
441
 */
442
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename, 
443
                       AVInputFormat *fmt,
444
                       int buf_size,
445
                       AVFormatParameters *ap)
446
{
447
    int err, must_open_file, file_opened;
448
    uint8_t buf[PROBE_BUF_SIZE];
449
    AVProbeData probe_data, *pd = &probe_data;
450
    ByteIOContext pb1, *pb = &pb1;
451
    
452
    file_opened = 0;
453
    pd->filename = "";
454
    if (filename)
455
        pd->filename = filename;
456
    pd->buf = buf;
457
    pd->buf_size = 0;
458

    
459
    if (!fmt) {
460
        /* guess format if no file can be opened  */
461
        fmt = av_probe_input_format(pd, 0);
462
    }
463

    
464
    /* do not open file if the format does not need it. XXX: specific
465
       hack needed to handle RTSP/TCP */
466
    must_open_file = 1;
467
    if (fmt && (fmt->flags & AVFMT_NOFILE)) {
468
        must_open_file = 0;
469
        pb= NULL; //FIXME this or memset(pb, 0, sizeof(ByteIOContext)); otherwise its uninitalized
470
    }
471

    
472
    if (!fmt || must_open_file) {
473
        /* if no file needed do not try to open one */
474
        if (url_fopen(pb, filename, URL_RDONLY) < 0) {
475
            err = AVERROR_IO;
476
            goto fail;
477
        }
478
        file_opened = 1;
479
        if (buf_size > 0) {
480
            url_setbufsize(pb, buf_size);
481
        }
482
        if (!fmt) {
483
            /* read probe data */
484
            pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
485
            if (url_fseek(pb, 0, SEEK_SET) == (offset_t)-EPIPE) {
486
                url_fclose(pb);
487
                if (url_fopen(pb, filename, URL_RDONLY) < 0) {
488
                    err = AVERROR_IO;
489
                    goto fail;
490
                }
491
            }
492
        }
493
    }
494
    
495
    /* guess file format */
496
    if (!fmt) {
497
        fmt = av_probe_input_format(pd, 1);
498
    }
499

    
500
    /* if still no format found, error */
501
    if (!fmt) {
502
        err = AVERROR_NOFMT;
503
        goto fail;
504
    }
505
        
506
    /* XXX: suppress this hack for redirectors */
507
#ifdef CONFIG_NETWORK
508
    if (fmt == &redir_demux) {
509
        err = redir_open(ic_ptr, pb);
510
        url_fclose(pb);
511
        return err;
512
    }
513
#endif
514

    
515
    /* check filename in case of an image number is expected */
516
    if (fmt->flags & AVFMT_NEEDNUMBER) {
517
        if (filename_number_test(filename) < 0) { 
518
            err = AVERROR_NUMEXPECTED;
519
            goto fail;
520
        }
521
    }
522
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
523
    if (err)
524
        goto fail;
525
    return 0;
526
 fail:
527
    if (file_opened)
528
        url_fclose(pb);
529
    *ic_ptr = NULL;
530
    return err;
531
    
532
}
533

    
534
/*******************************************************/
535

    
536
/**
537
 * Read a transport packet from a media file. This function is
538
 * absolete and should never be used. Use av_read_frame() instead.
539
 * 
540
 * @param s media file handle
541
 * @param pkt is filled 
542
 * @return 0 if OK. AVERROR_xxx if error.  
543
 */
544
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
545
{
546
    return s->iformat->read_packet(s, pkt);
547
}
548

    
549
/**********************************************************/
550

    
551
/* get the number of samples of an audio frame. Return (-1) if error */
552
static int get_audio_frame_size(AVCodecContext *enc, int size)
553
{
554
    int frame_size;
555

    
556
    if (enc->frame_size <= 1) {
557
        /* specific hack for pcm codecs because no frame size is
558
           provided */
559
        switch(enc->codec_id) {
560
        case CODEC_ID_PCM_S16LE:
561
        case CODEC_ID_PCM_S16BE:
562
        case CODEC_ID_PCM_U16LE:
563
        case CODEC_ID_PCM_U16BE:
564
            if (enc->channels == 0)
565
                return -1;
566
            frame_size = size / (2 * enc->channels);
567
            break;
568
        case CODEC_ID_PCM_S8:
569
        case CODEC_ID_PCM_U8:
570
        case CODEC_ID_PCM_MULAW:
571
        case CODEC_ID_PCM_ALAW:
572
            if (enc->channels == 0)
573
                return -1;
574
            frame_size = size / (enc->channels);
575
            break;
576
        default:
577
            /* used for example by ADPCM codecs */
578
            if (enc->bit_rate == 0)
579
                return -1;
580
            frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
581
            break;
582
        }
583
    } else {
584
        frame_size = enc->frame_size;
585
    }
586
    return frame_size;
587
}
588

    
589

    
590
/* return the frame duration in seconds, return 0 if not available */
591
static void compute_frame_duration(int *pnum, int *pden, AVStream *st, 
592
                                   AVCodecParserContext *pc, AVPacket *pkt)
593
{
594
    int frame_size;
595

    
596
    *pnum = 0;
597
    *pden = 0;
598
    switch(st->codec.codec_type) {
599
    case CODEC_TYPE_VIDEO:
600
        *pnum = st->codec.frame_rate_base;
601
        *pden = st->codec.frame_rate;
602
        if (pc && pc->repeat_pict) {
603
            *pden *= 2;
604
            *pnum = (*pnum) * (2 + pc->repeat_pict);
605
        }
606
        break;
607
    case CODEC_TYPE_AUDIO:
608
        frame_size = get_audio_frame_size(&st->codec, pkt->size);
609
        if (frame_size < 0)
610
            break;
611
        *pnum = frame_size;
612
        *pden = st->codec.sample_rate;
613
        break;
614
    default:
615
        break;
616
    }
617
}
618

    
619
static int is_intra_only(AVCodecContext *enc){
620
    if(enc->codec_type == CODEC_TYPE_AUDIO){
621
        return 1;
622
    }else if(enc->codec_type == CODEC_TYPE_VIDEO){
623
        switch(enc->codec_id){
624
        case CODEC_ID_MJPEG:
625
        case CODEC_ID_MJPEGB:
626
        case CODEC_ID_LJPEG:
627
        case CODEC_ID_RAWVIDEO:
628
        case CODEC_ID_DVVIDEO:
629
        case CODEC_ID_HUFFYUV:
630
        case CODEC_ID_ASV1:
631
        case CODEC_ID_ASV2:
632
        case CODEC_ID_VCR1:
633
            return 1;
634
        default: break;
635
        }
636
    }
637
    return 0;
638
}
639

    
640
static int64_t lsb2full(int64_t lsb, int64_t last_ts, int lsb_bits){
641
    int64_t mask = lsb_bits < 64 ? (1LL<<lsb_bits)-1 : -1LL;
642
    int64_t delta= last_ts - mask/2;
643
    return  ((lsb - delta)&mask) + delta;
644
}
645

    
646
static void compute_pkt_fields(AVFormatContext *s, AVStream *st, 
647
                               AVCodecParserContext *pc, AVPacket *pkt)
648
{
649
    int num, den, presentation_delayed;
650

    
651
    /* handle wrapping */
652
    if(st->cur_dts != AV_NOPTS_VALUE){
653
        if(pkt->pts != AV_NOPTS_VALUE)
654
            pkt->pts= lsb2full(pkt->pts, st->cur_dts, st->pts_wrap_bits);
655
        if(pkt->dts != AV_NOPTS_VALUE)
656
            pkt->dts= lsb2full(pkt->dts, st->cur_dts, st->pts_wrap_bits);
657
    }
658
    
659
    if (pkt->duration == 0) {
660
        compute_frame_duration(&num, &den, st, pc, pkt);
661
        if (den && num) {
662
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
663
        }
664
    }
665

    
666
    if(is_intra_only(&st->codec))
667
        pkt->flags |= PKT_FLAG_KEY;
668

    
669
    /* do we have a video B frame ? */
670
    presentation_delayed = 0;
671
    if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
672
        /* XXX: need has_b_frame, but cannot get it if the codec is
673
           not initialized */
674
        if ((st->codec.codec_id == CODEC_ID_MPEG1VIDEO ||
675
             st->codec.codec_id == CODEC_ID_MPEG2VIDEO ||
676
             st->codec.codec_id == CODEC_ID_MPEG4 ||
677
             st->codec.codec_id == CODEC_ID_H264) && 
678
            pc && pc->pict_type != FF_B_TYPE)
679
            presentation_delayed = 1;
680
        /* this may be redundant, but it shouldnt hurt */
681
        if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
682
            presentation_delayed = 1;
683
    }
684
    
685
    if(st->cur_dts == AV_NOPTS_VALUE){
686
        if(presentation_delayed) st->cur_dts = -pkt->duration;
687
        else                     st->cur_dts = 0;
688
    }
689

    
690
//    av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%lld, dts:%lld cur_dts:%lld st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
691
    /* interpolate PTS and DTS if they are not present */
692
    if (presentation_delayed) {
693
        /* DTS = decompression time stamp */
694
        /* PTS = presentation time stamp */
695
        if (pkt->dts == AV_NOPTS_VALUE) {
696
            /* if we know the last pts, use it */
697
            if(st->last_IP_pts != AV_NOPTS_VALUE)
698
                st->cur_dts = pkt->dts = st->last_IP_pts;
699
            else
700
                pkt->dts = st->cur_dts;
701
        } else {
702
            st->cur_dts = pkt->dts;
703
        }
704
        /* this is tricky: the dts must be incremented by the duration
705
           of the frame we are displaying, i.e. the last I or P frame */
706
        if (st->last_IP_duration == 0)
707
            st->cur_dts += pkt->duration;
708
        else
709
            st->cur_dts += st->last_IP_duration;
710
        st->last_IP_duration  = pkt->duration;
711
        st->last_IP_pts= pkt->pts;
712
        /* cannot compute PTS if not present (we can compute it only
713
           by knowing the futur */
714
    } else {
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) {
718
                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
            pkt->dts = pkt->pts;
728
        }
729
        st->cur_dts += pkt->duration;
730
    }
731
//    av_log(NULL, AV_LOG_DEBUG, "OUTdelayed:%d pts:%lld, dts:%lld cur_dts:%lld\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts);
732
    
733
    /* update flags */
734
    if (pc) {
735
        pkt->flags = 0;
736
        /* key frame computation */
737
        switch(st->codec.codec_type) {
738
        case CODEC_TYPE_VIDEO:
739
            if (pc->pict_type == FF_I_TYPE)
740
                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
    }
749

    
750
    /* convert the packet time stamp units */
751
    if(pkt->pts != AV_NOPTS_VALUE)
752
        pkt->pts = av_rescale(pkt->pts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
753
    if(pkt->dts != AV_NOPTS_VALUE)
754
        pkt->dts = av_rescale(pkt->dts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
755

    
756
    /* duration field */
757
    pkt->duration = av_rescale(pkt->duration, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
758
}
759

    
760
void av_destruct_packet_nofree(AVPacket *pkt)
761
{
762
    pkt->data = NULL; pkt->size = 0;
763
}
764

    
765
static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
766
{
767
    AVStream *st;
768
    int len, ret, i;
769

    
770
    for(;;) {
771
        /* select current input stream component */
772
        st = s->cur_st;
773
        if (st) {
774
            if (!st->parser) {
775
                /* no parsing needed: we just output the packet as is */
776
                /* raw data support */
777
                *pkt = s->cur_pkt;
778
                compute_pkt_fields(s, st, NULL, pkt);
779
                s->cur_st = NULL;
780
                return 0;
781
            } else if (s->cur_len > 0) {
782
                len = av_parser_parse(st->parser, &st->codec, &pkt->data, &pkt->size, 
783
                                      s->cur_ptr, s->cur_len,
784
                                      s->cur_pkt.pts, s->cur_pkt.dts);
785
                s->cur_pkt.pts = AV_NOPTS_VALUE;
786
                s->cur_pkt.dts = AV_NOPTS_VALUE;
787
                /* increment read pointer */
788
                s->cur_ptr += len;
789
                s->cur_len -= len;
790
                
791
                /* return packet if any */
792
                if (pkt->size) {
793
                got_packet:
794
                    pkt->duration = 0;
795
                    pkt->stream_index = st->index;
796
                    pkt->pts = st->parser->pts;
797
                    pkt->dts = st->parser->dts;
798
                    pkt->destruct = av_destruct_packet_nofree;
799
                    compute_pkt_fields(s, st, st->parser, pkt);
800
                    return 0;
801
                }
802
            } else {
803
                /* free packet */
804
                av_free_packet(&s->cur_pkt); 
805
                s->cur_st = NULL;
806
            }
807
        } else {
808
            /* read next packet */
809
            ret = av_read_packet(s, &s->cur_pkt);
810
            if (ret < 0) {
811
                if (ret == -EAGAIN)
812
                    return ret;
813
                /* return the last frames, if any */
814
                for(i = 0; i < s->nb_streams; i++) {
815
                    st = s->streams[i];
816
                    if (st->parser) {
817
                        av_parser_parse(st->parser, &st->codec, 
818
                                        &pkt->data, &pkt->size, 
819
                                        NULL, 0, 
820
                                        AV_NOPTS_VALUE, AV_NOPTS_VALUE);
821
                        if (pkt->size)
822
                            goto got_packet;
823
                    }
824
                }
825
                /* no more packets: really terminates parsing */
826
                return ret;
827
            }
828
            
829
            st = s->streams[s->cur_pkt.stream_index];
830

    
831
            s->cur_st = st;
832
            s->cur_ptr = s->cur_pkt.data;
833
            s->cur_len = s->cur_pkt.size;
834
            if (st->need_parsing && !st->parser) {
835
                st->parser = av_parser_init(st->codec.codec_id);
836
                if (!st->parser) {
837
                    /* no parser available : just output the raw packets */
838
                    st->need_parsing = 0;
839
                }
840
            }
841
        }
842
    }
843
}
844

    
845
/**
846
 * Return the next frame of a stream. The returned packet is valid
847
 * until the next av_read_frame() or until av_close_input_file() and
848
 * must be freed with av_free_packet. For video, the packet contains
849
 * exactly one frame. For audio, it contains an integer number of
850
 * frames if each frame has a known fixed size (e.g. PCM or ADPCM
851
 * data). If the audio frames have a variable size (e.g. MPEG audio),
852
 * then it contains one frame.
853
 * 
854
 * pkt->pts, pkt->dts and pkt->duration are always set to correct
855
 * values in AV_TIME_BASE unit (and guessed if the format cannot
856
 * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
857
 * has B frames, so it is better to rely on pkt->dts if you do not
858
 * decompress the payload.
859
 * 
860
 * Return 0 if OK, < 0 if error or end of file.  
861
 */
862
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
863
{
864
    AVPacketList *pktl;
865

    
866
    pktl = s->packet_buffer;
867
    if (pktl) {
868
        /* read packet from packet buffer, if there is data */
869
        *pkt = pktl->pkt;
870
        s->packet_buffer = pktl->next;
871
        av_free(pktl);
872
        return 0;
873
    } else {
874
        return av_read_frame_internal(s, pkt);
875
    }
876
}
877

    
878
/* XXX: suppress the packet queue */
879
static void flush_packet_queue(AVFormatContext *s)
880
{
881
    AVPacketList *pktl;
882

    
883
    for(;;) {
884
        pktl = s->packet_buffer;
885
        if (!pktl) 
886
            break;
887
        s->packet_buffer = pktl->next;
888
        av_free_packet(&pktl->pkt);
889
        av_free(pktl);
890
    }
891
}
892

    
893
/*******************************************************/
894
/* seek support */
895

    
896
int av_find_default_stream_index(AVFormatContext *s)
897
{
898
    int i;
899
    AVStream *st;
900

    
901
    if (s->nb_streams <= 0)
902
        return -1;
903
    for(i = 0; i < s->nb_streams; i++) {
904
        st = s->streams[i];
905
        if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
906
            return i;
907
        }
908
    }
909
    return 0;
910
}
911

    
912
/* flush the frame reader */
913
static void av_read_frame_flush(AVFormatContext *s)
914
{
915
    AVStream *st;
916
    int i;
917

    
918
    flush_packet_queue(s);
919

    
920
    /* free previous packet */
921
    if (s->cur_st) {
922
        if (s->cur_st->parser)
923
            av_free_packet(&s->cur_pkt);
924
        s->cur_st = NULL;
925
    }
926
    /* fail safe */
927
    s->cur_ptr = NULL;
928
    s->cur_len = 0;
929
    
930
    /* for each stream, reset read state */
931
    for(i = 0; i < s->nb_streams; i++) {
932
        st = s->streams[i];
933
        
934
        if (st->parser) {
935
            av_parser_close(st->parser);
936
            st->parser = NULL;
937
        }
938
        st->last_IP_pts = AV_NOPTS_VALUE;
939
        st->cur_dts = 0; /* we set the current DTS to an unspecified origin */
940
    }
941
}
942

    
943
/**
944
 * updates cur_dts of all streams based on given timestamp and AVStream.
945
 * stream ref_st unchanged, others set cur_dts in their native timebase
946
 * only needed for timestamp wrapping or if (dts not set and pts!=dts)
947
 * @param timestamp new dts expressed in time_base of param ref_st
948
 * @param ref_st reference stream giving time_base of param timestamp
949
 */
950
static void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
951
    int i;
952

    
953
    for(i = 0; i < s->nb_streams; i++) {
954
        AVStream *st = s->streams[i];
955

    
956
        st->cur_dts = av_rescale(timestamp, 
957
                                 st->time_base.den * (int64_t)ref_st->time_base.num,
958
                                 st->time_base.num * (int64_t)ref_st->time_base.den);
959
    }
960
}
961

    
962
/**
963
 * add a index entry into a sorted list updateing if it is already there.
964
 * @param timestamp timestamp in the timebase of the given stream
965
 */
966
int av_add_index_entry(AVStream *st,
967
                            int64_t pos, int64_t timestamp, int distance, int flags)
968
{
969
    AVIndexEntry *entries, *ie;
970
    int index;
971
    
972
    entries = av_fast_realloc(st->index_entries,
973
                              &st->index_entries_allocated_size,
974
                              (st->nb_index_entries + 1) * 
975
                              sizeof(AVIndexEntry));
976
    st->index_entries= entries;
977

    
978
    index= av_index_search_timestamp(st, timestamp, 0);
979

    
980
    if(index<0){
981
        index= st->nb_index_entries++;
982
        ie= &entries[index];
983
        assert(index==0 || ie[-1].timestamp < timestamp);
984
    }else{
985
        ie= &entries[index];
986
        if(ie->timestamp != timestamp){
987
            if(ie->timestamp <= timestamp)
988
                return -1;
989
            memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
990
            st->nb_index_entries++;
991
        }else if(ie->pos == pos && distance < ie->min_distance) //dont reduce the distance
992
            distance= ie->min_distance;
993
    }
994

    
995
    ie->pos = pos;
996
    ie->timestamp = timestamp;
997
    ie->min_distance= distance;
998
    ie->flags = flags;
999
    
1000
    return index;
1001
}
1002

    
1003
/* build an index for raw streams using a parser */
1004
static void av_build_index_raw(AVFormatContext *s)
1005
{
1006
    AVPacket pkt1, *pkt = &pkt1;
1007
    int ret;
1008
    AVStream *st;
1009

    
1010
    st = s->streams[0];
1011
    av_read_frame_flush(s);
1012
    url_fseek(&s->pb, s->data_offset, SEEK_SET);
1013

    
1014
    for(;;) {
1015
        ret = av_read_frame(s, pkt);
1016
        if (ret < 0)
1017
            break;
1018
        if (pkt->stream_index == 0 && st->parser &&
1019
            (pkt->flags & PKT_FLAG_KEY)) {
1020
            int64_t dts= av_rescale(pkt->dts, st->time_base.den, AV_TIME_BASE*(int64_t)st->time_base.num);
1021
            av_add_index_entry(st, st->parser->frame_offset, dts, 
1022
                            0, AVINDEX_KEYFRAME);
1023
        }
1024
        av_free_packet(pkt);
1025
    }
1026
}
1027

    
1028
/* return TRUE if we deal with a raw stream (raw codec data and
1029
   parsing needed) */
1030
static int is_raw_stream(AVFormatContext *s)
1031
{
1032
    AVStream *st;
1033

    
1034
    if (s->nb_streams != 1)
1035
        return 0;
1036
    st = s->streams[0];
1037
    if (!st->need_parsing)
1038
        return 0;
1039
    return 1;
1040
}
1041

    
1042
/**
1043
 * gets the index for a specific timestamp.
1044
 * @param backward if non zero then the returned index will correspond to 
1045
 *                 the timestamp which is <= the requested one, if backward is 0 
1046
 *                 then it will be >=
1047
 * @return < 0 if no such timestamp could be found
1048
 */
1049
int av_index_search_timestamp(AVStream *st, int wanted_timestamp, int backward)
1050
{
1051
    AVIndexEntry *entries= st->index_entries;
1052
    int nb_entries= st->nb_index_entries;
1053
    int a, b, m;
1054
    int64_t timestamp;
1055

    
1056
    a = - 1;
1057
    b = nb_entries;
1058

    
1059
    while (b - a > 1) {
1060
        m = (a + b) >> 1;
1061
        timestamp = entries[m].timestamp;
1062
        if(timestamp >= wanted_timestamp)
1063
            b = m;
1064
        if(timestamp <= wanted_timestamp)
1065
            a = m;
1066
    }
1067
    m= backward ? a : b;
1068

    
1069
    if(m == nb_entries) 
1070
        return -1;
1071
    return  m;
1072
}
1073

    
1074
#define DEBUG_SEEK
1075

    
1076
/**
1077
 * Does a binary search using av_index_search_timestamp() and AVCodec.read_timestamp().
1078
 * this isnt supposed to be called directly by a user application, but by demuxers
1079
 * @param target_ts target timestamp in the time base of the given stream
1080
 * @param stream_index stream number
1081
 */
1082
int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1083
    AVInputFormat *avif= s->iformat;
1084
    int64_t pos_min, pos_max, pos, pos_limit;
1085
    int64_t ts_min, ts_max, ts;
1086
    int64_t start_pos;
1087
    int index, no_change;
1088
    AVStream *st;
1089

    
1090
    if (stream_index < 0)
1091
        return -1;
1092
    
1093
#ifdef DEBUG_SEEK
1094
    av_log(s, AV_LOG_DEBUG, "read_seek: %d %lld\n", stream_index, target_ts);
1095
#endif
1096

    
1097
    ts_max=
1098
    ts_min= AV_NOPTS_VALUE;
1099
    pos_limit= -1; //gcc falsely says it may be uninitalized
1100

    
1101
    st= s->streams[stream_index];
1102
    if(st->index_entries){
1103
        AVIndexEntry *e;
1104

    
1105
        index= av_index_search_timestamp(st, target_ts, 1);
1106
        index= FFMAX(index, 0);
1107
        e= &st->index_entries[index];
1108

    
1109
        if(e->timestamp <= target_ts || e->pos == e->min_distance){
1110
            pos_min= e->pos;
1111
            ts_min= e->timestamp;
1112
#ifdef DEBUG_SEEK
1113
        av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%llx dts_min=%lld\n", 
1114
               pos_min,ts_min);
1115
#endif
1116
        }else{
1117
            assert(index==0);
1118
        }
1119
        index++;
1120
        if(index < st->nb_index_entries){
1121
            e= &st->index_entries[index];
1122
            assert(e->timestamp >= target_ts);
1123
            pos_max= e->pos;
1124
            ts_max= e->timestamp;
1125
            pos_limit= pos_max - e->min_distance;
1126
#ifdef DEBUG_SEEK
1127
        av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%llx pos_limit=0x%llx dts_max=%lld\n", 
1128
               pos_max,pos_limit, ts_max);
1129
#endif
1130
        }
1131
    }
1132

    
1133
    if(ts_min == AV_NOPTS_VALUE){
1134
        pos_min = s->data_offset;
1135
        ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1136
        if (ts_min == AV_NOPTS_VALUE)
1137
            return -1;
1138
    }
1139

    
1140
    if(ts_max == AV_NOPTS_VALUE){
1141
        int step= 1024;
1142
        pos_max = url_filesize(url_fileno(&s->pb)) - 1;
1143
        do{
1144
            pos_max -= step;
1145
            ts_max = avif->read_timestamp(s, stream_index, &pos_max, pos_max + step);
1146
            step += step;
1147
        }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1148
        if (ts_max == AV_NOPTS_VALUE)
1149
            return -1;
1150
        
1151
        for(;;){
1152
            int64_t tmp_pos= pos_max + 1;
1153
            int64_t tmp_ts= avif->read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1154
            if(tmp_ts == AV_NOPTS_VALUE)
1155
                break;
1156
            ts_max= tmp_ts;
1157
            pos_max= tmp_pos;
1158
        }
1159
        pos_limit= pos_max;
1160
    }
1161

    
1162
    no_change=0;
1163
    while (pos_min < pos_limit) {
1164
#ifdef DEBUG_SEEK
1165
        av_log(s, AV_LOG_DEBUG, "pos_min=0x%llx pos_max=0x%llx dts_min=%lld dts_max=%lld\n", 
1166
               pos_min, pos_max,
1167
               ts_min, ts_max);
1168
#endif
1169
        assert(pos_limit <= pos_max);
1170

    
1171
        if(no_change==0){
1172
            int64_t approximate_keyframe_distance= pos_max - pos_limit;
1173
            // interpolate position (better than dichotomy)
1174
            pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1175
                + pos_min - approximate_keyframe_distance;
1176
        }else if(no_change==1){
1177
            // bisection, if interpolation failed to change min or max pos last time
1178
            pos = (pos_min + pos_limit)>>1;
1179
        }else{
1180
            // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
1181
            pos=pos_min;
1182
        }
1183
        if(pos <= pos_min)
1184
            pos= pos_min + 1;
1185
        else if(pos > pos_limit)
1186
            pos= pos_limit;
1187
        start_pos= pos;
1188

    
1189
        ts = avif->read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1190
        if(pos == pos_max)
1191
            no_change++;
1192
        else
1193
            no_change=0;
1194
#ifdef DEBUG_SEEK
1195
av_log(s, AV_LOG_DEBUG, "%Ld %Ld %Ld / %Ld %Ld %Ld target:%Ld limit:%Ld start:%Ld noc:%d\n", pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, start_pos, no_change);
1196
#endif
1197
        assert(ts != AV_NOPTS_VALUE);
1198
        if (target_ts <= ts) {
1199
            pos_limit = start_pos - 1;
1200
            pos_max = pos;
1201
            ts_max = ts;
1202
        }
1203
        if (target_ts >= ts) {
1204
            pos_min = pos;
1205
            ts_min = ts;
1206
        }
1207
    }
1208
    
1209
    pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1210
    ts  = (flags & AVSEEK_FLAG_BACKWARD) ?  ts_min :  ts_max;
1211
#ifdef DEBUG_SEEK
1212
    pos_min = pos;
1213
    ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1214
    pos_min++;
1215
    ts_max = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1216
    av_log(s, AV_LOG_DEBUG, "pos=0x%llx %lld<=%lld<=%lld\n", 
1217
           pos, ts_min, target_ts, ts_max);
1218
#endif
1219
    /* do the seek */
1220
    url_fseek(&s->pb, pos, SEEK_SET);
1221

    
1222
    av_update_cur_dts(s, st, ts);
1223

    
1224
    return 0;
1225
}
1226

    
1227
static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1228
    AVInputFormat *avif= s->iformat;
1229
    int64_t pos_min, pos_max;
1230
#if 0
1231
    AVStream *st;
1232

1233
    if (stream_index < 0)
1234
        return -1;
1235

1236
    st= s->streams[stream_index];
1237
#endif
1238

    
1239
    pos_min = s->data_offset;
1240
    pos_max = url_filesize(url_fileno(&s->pb)) - 1;
1241

    
1242
    if     (pos < pos_min) pos= pos_min;
1243
    else if(pos > pos_max) pos= pos_max;
1244

    
1245
    url_fseek(&s->pb, pos, SEEK_SET);
1246

    
1247
#if 0
1248
    av_update_cur_dts(s, st, ts);
1249
#endif
1250
    return 0;
1251
}
1252

    
1253
static int av_seek_frame_generic(AVFormatContext *s, 
1254
                                 int stream_index, int64_t timestamp, int flags)
1255
{
1256
    int index;
1257
    AVStream *st;
1258
    AVIndexEntry *ie;
1259

    
1260
    if (!s->index_built) {
1261
        if (is_raw_stream(s)) {
1262
            av_build_index_raw(s);
1263
        } else {
1264
            return -1;
1265
        }
1266
        s->index_built = 1;
1267
    }
1268

    
1269
    st = s->streams[stream_index];
1270
    index = av_index_search_timestamp(st, timestamp, flags & AVSEEK_FLAG_BACKWARD);
1271
    if (index < 0)
1272
        return -1;
1273

    
1274
    /* now we have found the index, we can seek */
1275
    ie = &st->index_entries[index];
1276
    av_read_frame_flush(s);
1277
    url_fseek(&s->pb, ie->pos, SEEK_SET);
1278

    
1279
    av_update_cur_dts(s, st, ie->timestamp);
1280

    
1281
    return 0;
1282
}
1283

    
1284
/**
1285
 * Seek to the key frame at timestamp.
1286
 * 'timestamp' in 'stream_index'.
1287
 * @param stream_index If stream_index is (-1), a default
1288
 * stream is selected, and timestamp is automatically converted 
1289
 * from AV_TIME_BASE units to the stream specific time_base.
1290
 * @param timestamp timestamp in AVStream.time_base units
1291
 * @param flags flags which select direction and seeking mode
1292
 * @return >= 0 on success
1293
 */
1294
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1295
{
1296
    int ret;
1297
    AVStream *st;
1298
    
1299
    av_read_frame_flush(s);
1300
    
1301
    if(flags & AVSEEK_FLAG_BYTE)
1302
        return av_seek_frame_byte(s, stream_index, timestamp, flags);
1303
    
1304
    if(stream_index < 0){
1305
        stream_index= av_find_default_stream_index(s);
1306
        if(stream_index < 0)
1307
            return -1;
1308
            
1309
        st= s->streams[stream_index];
1310
       /* timestamp for default must be expressed in AV_TIME_BASE units */
1311
        timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1312
    }
1313
    st= s->streams[stream_index];
1314

    
1315
    /* first, we try the format specific seek */
1316
    if (s->iformat->read_seek)
1317
        ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1318
    else
1319
        ret = -1;
1320
    if (ret >= 0) {
1321
        return 0;
1322
    }
1323

    
1324
    if(s->iformat->read_timestamp)
1325
        return av_seek_frame_binary(s, stream_index, timestamp, flags);
1326
    else
1327
        return av_seek_frame_generic(s, stream_index, timestamp, flags);
1328
}
1329

    
1330
/*******************************************************/
1331

    
1332
/* return TRUE if the stream has accurate timings for at least one component */
1333
static int av_has_timings(AVFormatContext *ic)
1334
{
1335
    int i;
1336
    AVStream *st;
1337

    
1338
    for(i = 0;i < ic->nb_streams; i++) {
1339
        st = ic->streams[i];
1340
        if (st->start_time != AV_NOPTS_VALUE &&
1341
            st->duration != AV_NOPTS_VALUE)
1342
            return 1;
1343
    }
1344
    return 0;
1345
}
1346

    
1347
/* estimate the stream timings from the one of each components. Also
1348
   compute the global bitrate if possible */
1349
static void av_update_stream_timings(AVFormatContext *ic)
1350
{
1351
    int64_t start_time, end_time, end_time1;
1352
    int i;
1353
    AVStream *st;
1354

    
1355
    start_time = MAXINT64;
1356
    end_time = MININT64;
1357
    for(i = 0;i < ic->nb_streams; i++) {
1358
        st = ic->streams[i];
1359
        if (st->start_time != AV_NOPTS_VALUE) {
1360
            if (st->start_time < start_time)
1361
                start_time = st->start_time;
1362
            if (st->duration != AV_NOPTS_VALUE) {
1363
                end_time1 = st->start_time + st->duration;
1364
                if (end_time1 > end_time)
1365
                    end_time = end_time1;
1366
            }
1367
        }
1368
    }
1369
    if (start_time != MAXINT64) {
1370
        ic->start_time = start_time;
1371
        if (end_time != MAXINT64) {
1372
            ic->duration = end_time - start_time;
1373
            if (ic->file_size > 0) {
1374
                /* compute the bit rate */
1375
                ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE / 
1376
                    (double)ic->duration;
1377
            }
1378
        }
1379
    }
1380

    
1381
}
1382

    
1383
static void fill_all_stream_timings(AVFormatContext *ic)
1384
{
1385
    int i;
1386
    AVStream *st;
1387

    
1388
    av_update_stream_timings(ic);
1389
    for(i = 0;i < ic->nb_streams; i++) {
1390
        st = ic->streams[i];
1391
        if (st->start_time == AV_NOPTS_VALUE) {
1392
            st->start_time = ic->start_time;
1393
            st->duration = ic->duration;
1394
        }
1395
    }
1396
}
1397

    
1398
static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1399
{
1400
    int64_t filesize, duration;
1401
    int bit_rate, i;
1402
    AVStream *st;
1403

    
1404
    /* if bit_rate is already set, we believe it */
1405
    if (ic->bit_rate == 0) {
1406
        bit_rate = 0;
1407
        for(i=0;i<ic->nb_streams;i++) {
1408
            st = ic->streams[i];
1409
            bit_rate += st->codec.bit_rate;
1410
        }
1411
        ic->bit_rate = bit_rate;
1412
    }
1413

    
1414
    /* if duration is already set, we believe it */
1415
    if (ic->duration == AV_NOPTS_VALUE && 
1416
        ic->bit_rate != 0 && 
1417
        ic->file_size != 0)  {
1418
        filesize = ic->file_size;
1419
        if (filesize > 0) {
1420
            duration = (int64_t)((8 * AV_TIME_BASE * (double)filesize) / (double)ic->bit_rate);
1421
            for(i = 0; i < ic->nb_streams; i++) {
1422
                st = ic->streams[i];
1423
                if (st->start_time == AV_NOPTS_VALUE ||
1424
                    st->duration == AV_NOPTS_VALUE) {
1425
                    st->start_time = 0;
1426
                    st->duration = duration;
1427
                }
1428
            }
1429
        }
1430
    }
1431
}
1432

    
1433
#define DURATION_MAX_READ_SIZE 250000
1434

    
1435
/* only usable for MPEG-PS streams */
1436
static void av_estimate_timings_from_pts(AVFormatContext *ic)
1437
{
1438
    AVPacket pkt1, *pkt = &pkt1;
1439
    AVStream *st;
1440
    int read_size, i, ret;
1441
    int64_t start_time, end_time, end_time1;
1442
    int64_t filesize, offset, duration;
1443
    
1444
    /* free previous packet */
1445
    if (ic->cur_st && ic->cur_st->parser)
1446
        av_free_packet(&ic->cur_pkt); 
1447
    ic->cur_st = NULL;
1448

    
1449
    /* flush packet queue */
1450
    flush_packet_queue(ic);
1451

    
1452
    for(i=0;i<ic->nb_streams;i++) {
1453
        st = ic->streams[i];
1454
        if (st->parser) {
1455
            av_parser_close(st->parser);
1456
            st->parser= NULL;
1457
        }
1458
    }
1459
    
1460
    /* we read the first packets to get the first PTS (not fully
1461
       accurate, but it is enough now) */
1462
    url_fseek(&ic->pb, 0, SEEK_SET);
1463
    read_size = 0;
1464
    for(;;) {
1465
        if (read_size >= DURATION_MAX_READ_SIZE)
1466
            break;
1467
        /* if all info is available, we can stop */
1468
        for(i = 0;i < ic->nb_streams; i++) {
1469
            st = ic->streams[i];
1470
            if (st->start_time == AV_NOPTS_VALUE)
1471
                break;
1472
        }
1473
        if (i == ic->nb_streams)
1474
            break;
1475

    
1476
        ret = av_read_packet(ic, pkt);
1477
        if (ret != 0)
1478
            break;
1479
        read_size += pkt->size;
1480
        st = ic->streams[pkt->stream_index];
1481
        if (pkt->pts != AV_NOPTS_VALUE) {
1482
            if (st->start_time == AV_NOPTS_VALUE)
1483
                st->start_time = av_rescale(pkt->pts, st->time_base.num * (int64_t)AV_TIME_BASE, st->time_base.den);
1484
        }
1485
        av_free_packet(pkt);
1486
    }
1487

    
1488
    /* we compute the minimum start_time and use it as default */
1489
    start_time = MAXINT64;
1490
    for(i = 0; i < ic->nb_streams; i++) {
1491
        st = ic->streams[i];
1492
        if (st->start_time != AV_NOPTS_VALUE &&
1493
            st->start_time < start_time)
1494
            start_time = st->start_time;
1495
    }
1496
    if (start_time != MAXINT64)
1497
        ic->start_time = start_time;
1498
    
1499
    /* estimate the end time (duration) */
1500
    /* XXX: may need to support wrapping */
1501
    filesize = ic->file_size;
1502
    offset = filesize - DURATION_MAX_READ_SIZE;
1503
    if (offset < 0)
1504
        offset = 0;
1505

    
1506
    url_fseek(&ic->pb, offset, SEEK_SET);
1507
    read_size = 0;
1508
    for(;;) {
1509
        if (read_size >= DURATION_MAX_READ_SIZE)
1510
            break;
1511
        /* if all info is available, we can stop */
1512
        for(i = 0;i < ic->nb_streams; i++) {
1513
            st = ic->streams[i];
1514
            if (st->duration == AV_NOPTS_VALUE)
1515
                break;
1516
        }
1517
        if (i == ic->nb_streams)
1518
            break;
1519
        
1520
        ret = av_read_packet(ic, pkt);
1521
        if (ret != 0)
1522
            break;
1523
        read_size += pkt->size;
1524
        st = ic->streams[pkt->stream_index];
1525
        if (pkt->pts != AV_NOPTS_VALUE) {
1526
            end_time = av_rescale(pkt->pts, st->time_base.num * (int64_t)AV_TIME_BASE, st->time_base.den);
1527
            duration = end_time - st->start_time;
1528
            if (duration > 0) {
1529
                if (st->duration == AV_NOPTS_VALUE ||
1530
                    st->duration < duration)
1531
                    st->duration = duration;
1532
            }
1533
        }
1534
        av_free_packet(pkt);
1535
    }
1536
    
1537
    /* estimate total duration */
1538
    end_time = MININT64;
1539
    for(i = 0;i < ic->nb_streams; i++) {
1540
        st = ic->streams[i];
1541
        if (st->duration != AV_NOPTS_VALUE) {
1542
            end_time1 = st->start_time + st->duration;
1543
            if (end_time1 > end_time)
1544
                end_time = end_time1;
1545
        }
1546
    }
1547
    
1548
    /* update start_time (new stream may have been created, so we do
1549
       it at the end */
1550
    if (ic->start_time != AV_NOPTS_VALUE) {
1551
        for(i = 0; i < ic->nb_streams; i++) {
1552
            st = ic->streams[i];
1553
            if (st->start_time == AV_NOPTS_VALUE)
1554
                st->start_time = ic->start_time;
1555
        }
1556
    }
1557

    
1558
    if (end_time != MININT64) {
1559
        /* put dummy values for duration if needed */
1560
        for(i = 0;i < ic->nb_streams; i++) {
1561
            st = ic->streams[i];
1562
            if (st->duration == AV_NOPTS_VALUE && 
1563
                st->start_time != AV_NOPTS_VALUE)
1564
                st->duration = end_time - st->start_time;
1565
        }
1566
        ic->duration = end_time - ic->start_time;
1567
    }
1568

    
1569
    url_fseek(&ic->pb, 0, SEEK_SET);
1570
}
1571

    
1572
static void av_estimate_timings(AVFormatContext *ic)
1573
{
1574
    URLContext *h;
1575
    int64_t file_size;
1576

    
1577
    /* get the file size, if possible */
1578
    if (ic->iformat->flags & AVFMT_NOFILE) {
1579
        file_size = 0;
1580
    } else {
1581
        h = url_fileno(&ic->pb);
1582
        file_size = url_filesize(h);
1583
        if (file_size < 0)
1584
            file_size = 0;
1585
    }
1586
    ic->file_size = file_size;
1587

    
1588
    if (ic->iformat == &mpegps_demux) {
1589
        /* get accurate estimate from the PTSes */
1590
        av_estimate_timings_from_pts(ic);
1591
    } else if (av_has_timings(ic)) {
1592
        /* at least one components has timings - we use them for all
1593
           the components */
1594
        fill_all_stream_timings(ic);
1595
    } else {
1596
        /* less precise: use bit rate info */
1597
        av_estimate_timings_from_bit_rate(ic);
1598
    }
1599
    av_update_stream_timings(ic);
1600

    
1601
#if 0
1602
    {
1603
        int i;
1604
        AVStream *st;
1605
        for(i = 0;i < ic->nb_streams; i++) {
1606
            st = ic->streams[i];
1607
        printf("%d: start_time: %0.3f duration: %0.3f\n", 
1608
               i, (double)st->start_time / AV_TIME_BASE, 
1609
               (double)st->duration / AV_TIME_BASE);
1610
        }
1611
        printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n", 
1612
               (double)ic->start_time / AV_TIME_BASE, 
1613
               (double)ic->duration / AV_TIME_BASE,
1614
               ic->bit_rate / 1000);
1615
    }
1616
#endif
1617
}
1618

    
1619
static int has_codec_parameters(AVCodecContext *enc)
1620
{
1621
    int val;
1622
    switch(enc->codec_type) {
1623
    case CODEC_TYPE_AUDIO:
1624
        val = enc->sample_rate;
1625
        break;
1626
    case CODEC_TYPE_VIDEO:
1627
        val = enc->width;
1628
        break;
1629
    default:
1630
        val = 1;
1631
        break;
1632
    }
1633
    return (val != 0);
1634
}
1635

    
1636
static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1637
{
1638
    int16_t *samples;
1639
    AVCodec *codec;
1640
    int got_picture, ret;
1641
    AVFrame picture;
1642
    
1643
    codec = avcodec_find_decoder(st->codec.codec_id);
1644
    if (!codec)
1645
        return -1;
1646
    ret = avcodec_open(&st->codec, codec);
1647
    if (ret < 0)
1648
        return ret;
1649
    switch(st->codec.codec_type) {
1650
    case CODEC_TYPE_VIDEO:
1651
        ret = avcodec_decode_video(&st->codec, &picture, 
1652
                                   &got_picture, (uint8_t *)data, size);
1653
        break;
1654
    case CODEC_TYPE_AUDIO:
1655
        samples = av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
1656
        if (!samples)
1657
            goto fail;
1658
        ret = avcodec_decode_audio(&st->codec, samples, 
1659
                                   &got_picture, (uint8_t *)data, size);
1660
        av_free(samples);
1661
        break;
1662
    default:
1663
        break;
1664
    }
1665
 fail:
1666
    avcodec_close(&st->codec);
1667
    return ret;
1668
}
1669

    
1670
/* absolute maximum size we read until we abort */
1671
#define MAX_READ_SIZE        5000000
1672

    
1673
/* maximum duration until we stop analysing the stream */
1674
#define MAX_STREAM_DURATION  ((int)(AV_TIME_BASE * 1.0))
1675

    
1676
/**
1677
 * Read the beginning of a media file to get stream information. This
1678
 * is useful for file formats with no headers such as MPEG. This
1679
 * function also compute the real frame rate in case of mpeg2 repeat
1680
 * frame mode.
1681
 *
1682
 * @param ic media file handle
1683
 * @return >=0 if OK. AVERROR_xxx if error.  
1684
 */
1685
int av_find_stream_info(AVFormatContext *ic)
1686
{
1687
    int i, count, ret, read_size;
1688
    AVStream *st;
1689
    AVPacket pkt1, *pkt;
1690
    AVPacketList *pktl=NULL, **ppktl;
1691

    
1692
    count = 0;
1693
    read_size = 0;
1694
    ppktl = &ic->packet_buffer;
1695
    for(;;) {
1696
        /* check if one codec still needs to be handled */
1697
        for(i=0;i<ic->nb_streams;i++) {
1698
            st = ic->streams[i];
1699
            if (!has_codec_parameters(&st->codec))
1700
                break;
1701
        }
1702
        if (i == ic->nb_streams) {
1703
            /* NOTE: if the format has no header, then we need to read
1704
               some packets to get most of the streams, so we cannot
1705
               stop here */
1706
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
1707
                /* if we found the info for all the codecs, we can stop */
1708
                ret = count;
1709
                break;
1710
            }
1711
        } else {
1712
            /* we did not get all the codec info, but we read too much data */
1713
            if (read_size >= MAX_READ_SIZE) {
1714
                ret = count;
1715
                break;
1716
            }
1717
        }
1718

    
1719
        /* NOTE: a new stream can be added there if no header in file
1720
           (AVFMTCTX_NOHEADER) */
1721
        ret = av_read_frame_internal(ic, &pkt1);
1722
        if (ret < 0) {
1723
            /* EOF or error */
1724
            ret = -1; /* we could not have all the codec parameters before EOF */
1725
            if ((ic->ctx_flags & AVFMTCTX_NOHEADER) &&
1726
                i == ic->nb_streams)
1727
                ret = 0;
1728
            break;
1729
        }
1730

    
1731
        pktl = av_mallocz(sizeof(AVPacketList));
1732
        if (!pktl) {
1733
            ret = AVERROR_NOMEM;
1734
            break;
1735
        }
1736

    
1737
        /* add the packet in the buffered packet list */
1738
        *ppktl = pktl;
1739
        ppktl = &pktl->next;
1740

    
1741
        pkt = &pktl->pkt;
1742
        *pkt = pkt1;
1743
        
1744
        /* duplicate the packet */
1745
        if (av_dup_packet(pkt) < 0) {
1746
                ret = AVERROR_NOMEM;
1747
                break;
1748
        }
1749

    
1750
        read_size += pkt->size;
1751

    
1752
        st = ic->streams[pkt->stream_index];
1753
        st->codec_info_duration += pkt->duration;
1754
        if (pkt->duration != 0)
1755
            st->codec_info_nb_frames++;
1756

    
1757
        /* if still no information, we try to open the codec and to
1758
           decompress the frame. We try to avoid that in most cases as
1759
           it takes longer and uses more memory. For MPEG4, we need to
1760
           decompress for Quicktime. */
1761
        if (!has_codec_parameters(&st->codec) &&
1762
            (st->codec.codec_id == CODEC_ID_FLV1 ||
1763
             st->codec.codec_id == CODEC_ID_H264 ||
1764
             st->codec.codec_id == CODEC_ID_H263 ||
1765
             st->codec.codec_id == CODEC_ID_H261 ||
1766
             st->codec.codec_id == CODEC_ID_VORBIS ||
1767
             st->codec.codec_id == CODEC_ID_MJPEG ||
1768
             st->codec.codec_id == CODEC_ID_PNG ||
1769
             st->codec.codec_id == CODEC_ID_PAM ||
1770
             st->codec.codec_id == CODEC_ID_PGM ||
1771
             st->codec.codec_id == CODEC_ID_PGMYUV ||
1772
             st->codec.codec_id == CODEC_ID_PBM ||
1773
             st->codec.codec_id == CODEC_ID_PPM ||
1774
             (st->codec.codec_id == CODEC_ID_MPEG4 && !st->need_parsing)))
1775
            try_decode_frame(st, pkt->data, pkt->size);
1776
        
1777
        if (st->codec_info_duration >= MAX_STREAM_DURATION) {
1778
            break;
1779
        }
1780
        count++;
1781
    }
1782

    
1783
    for(i=0;i<ic->nb_streams;i++) {
1784
        st = ic->streams[i];
1785
        if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
1786
            if(st->codec.codec_id == CODEC_ID_RAWVIDEO && !st->codec.codec_tag)
1787
                st->codec.codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec.pix_fmt);
1788
            /* set real frame rate info */
1789
            /* compute the real frame rate for telecine */
1790
            if ((st->codec.codec_id == CODEC_ID_MPEG1VIDEO ||
1791
                 st->codec.codec_id == CODEC_ID_MPEG2VIDEO) &&
1792
                st->codec.sub_id == 2) {
1793
                if (st->codec_info_nb_frames >= 20) {
1794
                    float coded_frame_rate, est_frame_rate;
1795
                    est_frame_rate = ((double)st->codec_info_nb_frames * AV_TIME_BASE) / 
1796
                        (double)st->codec_info_duration ;
1797
                    coded_frame_rate = (double)st->codec.frame_rate /
1798
                        (double)st->codec.frame_rate_base;
1799
#if 0
1800
                    printf("telecine: coded_frame_rate=%0.3f est_frame_rate=%0.3f\n", 
1801
                           coded_frame_rate, est_frame_rate);
1802
#endif
1803
                    /* if we detect that it could be a telecine, we
1804
                       signal it. It would be better to do it at a
1805
                       higher level as it can change in a film */
1806
                    if (coded_frame_rate >= 24.97 && 
1807
                        (est_frame_rate >= 23.5 && est_frame_rate < 24.5)) {
1808
                        st->r_frame_rate = 24024;
1809
                        st->r_frame_rate_base = 1001;
1810
                    }
1811
                }
1812
            }
1813
            /* if no real frame rate, use the codec one */
1814
            if (!st->r_frame_rate){
1815
                st->r_frame_rate      = st->codec.frame_rate;
1816
                st->r_frame_rate_base = st->codec.frame_rate_base;
1817
            }
1818
        }
1819
    }
1820

    
1821
    av_estimate_timings(ic);
1822
#if 0
1823
    /* correct DTS for b frame streams with no timestamps */
1824
    for(i=0;i<ic->nb_streams;i++) {
1825
        st = ic->streams[i];
1826
        if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
1827
            if(b-frames){
1828
                ppktl = &ic->packet_buffer;
1829
                while(ppkt1){
1830
                    if(ppkt1->stream_index != i)
1831
                        continue;
1832
                    if(ppkt1->pkt->dts < 0)
1833
                        break;
1834
                    if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
1835
                        break;
1836
                    ppkt1->pkt->dts -= delta;
1837
                    ppkt1= ppkt1->next;
1838
                }
1839
                if(ppkt1)
1840
                    continue;
1841
                st->cur_dts -= delta;
1842
            }
1843
        }
1844
    }
1845
#endif
1846
    return ret;
1847
}
1848

    
1849
/*******************************************************/
1850

    
1851
/**
1852
 * start playing a network based stream (e.g. RTSP stream) at the
1853
 * current position 
1854
 */
1855
int av_read_play(AVFormatContext *s)
1856
{
1857
    if (!s->iformat->read_play)
1858
        return AVERROR_NOTSUPP;
1859
    return s->iformat->read_play(s);
1860
}
1861

    
1862
/**
1863
 * pause a network based stream (e.g. RTSP stream). Use av_read_play()
1864
 * to resume it.
1865
 */
1866
int av_read_pause(AVFormatContext *s)
1867
{
1868
    if (!s->iformat->read_pause)
1869
        return AVERROR_NOTSUPP;
1870
    return s->iformat->read_pause(s);
1871
}
1872

    
1873
/**
1874
 * Close a media file (but not its codecs)
1875
 *
1876
 * @param s media file handle
1877
 */
1878
void av_close_input_file(AVFormatContext *s)
1879
{
1880
    int i, must_open_file;
1881
    AVStream *st;
1882

    
1883
    /* free previous packet */
1884
    if (s->cur_st && s->cur_st->parser)
1885
        av_free_packet(&s->cur_pkt); 
1886

    
1887
    if (s->iformat->read_close)
1888
        s->iformat->read_close(s);
1889
    for(i=0;i<s->nb_streams;i++) {
1890
        /* free all data in a stream component */
1891
        st = s->streams[i];
1892
        if (st->parser) {
1893
            av_parser_close(st->parser);
1894
        }
1895
        av_free(st->index_entries);
1896
        av_free(st);
1897
    }
1898
    flush_packet_queue(s);
1899
    must_open_file = 1;
1900
    if (s->iformat->flags & AVFMT_NOFILE) {
1901
        must_open_file = 0;
1902
    }
1903
    if (must_open_file) {
1904
        url_fclose(&s->pb);
1905
    }
1906
    av_freep(&s->priv_data);
1907
    av_free(s);
1908
}
1909

    
1910
/**
1911
 * Add a new stream to a media file. Can only be called in the
1912
 * read_header function. If the flag AVFMTCTX_NOHEADER is in the
1913
 * format context, then new streams can be added in read_packet too.
1914
 *
1915
 *
1916
 * @param s media file handle
1917
 * @param id file format dependent stream id 
1918
 */
1919
AVStream *av_new_stream(AVFormatContext *s, int id)
1920
{
1921
    AVStream *st;
1922

    
1923
    if (s->nb_streams >= MAX_STREAMS)
1924
        return NULL;
1925

    
1926
    st = av_mallocz(sizeof(AVStream));
1927
    if (!st)
1928
        return NULL;
1929
    avcodec_get_context_defaults(&st->codec);
1930
    if (s->iformat) {
1931
        /* no default bitrate if decoding */
1932
        st->codec.bit_rate = 0;
1933
    }
1934
    st->index = s->nb_streams;
1935
    st->id = id;
1936
    st->start_time = AV_NOPTS_VALUE;
1937
    st->duration = AV_NOPTS_VALUE;
1938
    st->cur_dts = AV_NOPTS_VALUE;
1939

    
1940
    /* default pts settings is MPEG like */
1941
    av_set_pts_info(st, 33, 1, 90000);
1942
    st->last_IP_pts = AV_NOPTS_VALUE;
1943

    
1944
    s->streams[s->nb_streams++] = st;
1945
    return st;
1946
}
1947

    
1948
/************************************************************/
1949
/* output media file */
1950

    
1951
int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
1952
{
1953
    int ret;
1954
    
1955
    if (s->oformat->priv_data_size > 0) {
1956
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
1957
        if (!s->priv_data)
1958
            return AVERROR_NOMEM;
1959
    } else
1960
        s->priv_data = NULL;
1961
        
1962
    if (s->oformat->set_parameters) {
1963
        ret = s->oformat->set_parameters(s, ap);
1964
        if (ret < 0)
1965
            return ret;
1966
    }
1967
    return 0;
1968
}
1969

    
1970
/**
1971
 * allocate the stream private data and write the stream header to an
1972
 * output media file
1973
 *
1974
 * @param s media file handle
1975
 * @return 0 if OK. AVERROR_xxx if error.  
1976
 */
1977
int av_write_header(AVFormatContext *s)
1978
{
1979
    int ret, i;
1980
    AVStream *st;
1981

    
1982
    ret = s->oformat->write_header(s);
1983
    if (ret < 0)
1984
        return ret;
1985

    
1986
    /* init PTS generation */
1987
    for(i=0;i<s->nb_streams;i++) {
1988
        st = s->streams[i];
1989

    
1990
        switch (st->codec.codec_type) {
1991
        case CODEC_TYPE_AUDIO:
1992
            av_frac_init(&st->pts, 0, 0, 
1993
                         (int64_t)st->time_base.num * st->codec.sample_rate);
1994
            break;
1995
        case CODEC_TYPE_VIDEO:
1996
            av_frac_init(&st->pts, 0, 0, 
1997
                         (int64_t)st->time_base.num * st->codec.frame_rate);
1998
            break;
1999
        default:
2000
            break;
2001
        }
2002
    }
2003
    return 0;
2004
}
2005

    
2006
//FIXME merge with compute_pkt_fields
2007
static void compute_pkt_fields2(AVStream *st, AVPacket *pkt){
2008
    int b_frames = FFMAX(st->codec.has_b_frames, st->codec.max_b_frames);
2009
    int num, den, frame_size;
2010

    
2011
//    av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts:%lld dts:%lld cur_dts:%lld b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, b_frames, pkt->size, pkt->stream_index);
2012
    
2013
/*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2014
        return -1;*/
2015
            
2016
    if(pkt->pts != AV_NOPTS_VALUE)
2017
        pkt->pts = av_rescale(pkt->pts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
2018
    if(pkt->dts != AV_NOPTS_VALUE)
2019
        pkt->dts = av_rescale(pkt->dts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
2020

    
2021
    /* duration field */
2022
    pkt->duration = av_rescale(pkt->duration, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
2023
    if (pkt->duration == 0) {
2024
        compute_frame_duration(&num, &den, st, NULL, pkt);
2025
        if (den && num) {
2026
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
2027
        }
2028
    }
2029

    
2030
    //XXX/FIXME this is a temporary hack until all encoders output pts
2031
    if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !b_frames){
2032
        pkt->dts=
2033
//        pkt->pts= st->cur_dts;
2034
        pkt->pts= st->pts.val;
2035
    }
2036

    
2037
    //calculate dts from pts    
2038
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
2039
        if(b_frames){
2040
            if(st->last_IP_pts == AV_NOPTS_VALUE){
2041
                st->last_IP_pts= -pkt->duration;
2042
            }
2043
            if(st->last_IP_pts < pkt->pts){
2044
                pkt->dts= st->last_IP_pts;
2045
                st->last_IP_pts= pkt->pts;
2046
            }else
2047
                pkt->dts= pkt->pts;
2048
        }else
2049
            pkt->dts= pkt->pts;
2050
    }
2051
    
2052
//    av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%lld dts2:%lld\n", pkt->pts, pkt->dts);
2053
    st->cur_dts= pkt->dts;
2054
    st->pts.val= pkt->dts;
2055

    
2056
    /* update pts */
2057
    switch (st->codec.codec_type) {
2058
    case CODEC_TYPE_AUDIO:
2059
        frame_size = get_audio_frame_size(&st->codec, pkt->size);
2060

    
2061
        /* HACK/FIXME, we skip the initial 0-size packets as they are most likely equal to the encoder delay,
2062
           but it would be better if we had the real timestamps from the encoder */
2063
        if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2064
            av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2065
        }
2066
        break;
2067
    case CODEC_TYPE_VIDEO:
2068
        av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec.frame_rate_base);
2069
        break;
2070
    default:
2071
        break;
2072
    }
2073
}
2074

    
2075
static void truncate_ts(AVStream *st, AVPacket *pkt){
2076
    int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
2077
    
2078
//    if(pkt->dts < 0)
2079
//        pkt->dts= 0;  //this happens for low_delay=0 and b frames, FIXME, needs further invstigation about what we should do here
2080
    
2081
    pkt->pts &= pts_mask;
2082
    pkt->dts &= pts_mask;
2083
}
2084

    
2085
/**
2086
 * Write a packet to an output media file. The packet shall contain
2087
 * one audio or video frame.
2088
 *
2089
 * @param s media file handle
2090
 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2091
 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2092
 */
2093
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2094
{
2095
    int ret;
2096

    
2097
    compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
2098
    
2099
    truncate_ts(s->streams[pkt->stream_index], pkt);
2100

    
2101
    ret= s->oformat->write_packet(s, pkt);
2102
    if(!ret)
2103
        ret= url_ferror(&s->pb);
2104
    return ret;
2105
}
2106

    
2107
/**
2108
 * interleave_packet implementation which will interleave per DTS.
2109
 */
2110
static int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2111
    AVPacketList *pktl, **next_point, *this_pktl;
2112
    int stream_count=0;
2113
    int streams[MAX_STREAMS];
2114

    
2115
    if(pkt){
2116
        AVStream *st= s->streams[ pkt->stream_index];
2117

    
2118
        assert(pkt->destruct != av_destruct_packet); //FIXME
2119

    
2120
        this_pktl = av_mallocz(sizeof(AVPacketList));
2121
        this_pktl->pkt= *pkt;
2122
        av_dup_packet(&this_pktl->pkt);
2123

    
2124
        next_point = &s->packet_buffer;
2125
        while(*next_point){
2126
            AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
2127
            int64_t left=  st2->time_base.num * (int64_t)st ->time_base.den;
2128
            int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2129
            if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
2130
                break;
2131
            next_point= &(*next_point)->next;
2132
        }
2133
        this_pktl->next= *next_point;
2134
        *next_point= this_pktl;
2135
    }
2136
    
2137
    memset(streams, 0, sizeof(streams));
2138
    pktl= s->packet_buffer;
2139
    while(pktl){
2140
//av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
2141
        if(streams[ pktl->pkt.stream_index ] == 0)
2142
            stream_count++;
2143
        streams[ pktl->pkt.stream_index ]++;
2144
        pktl= pktl->next;
2145
    }
2146
    
2147
    if(s->nb_streams == stream_count || (flush && stream_count)){
2148
        pktl= s->packet_buffer;
2149
        *out= pktl->pkt;
2150
        
2151
        s->packet_buffer= pktl->next;        
2152
        av_freep(&pktl);
2153
        return 1;
2154
    }else{
2155
        av_init_packet(out);
2156
        return 0;
2157
    }
2158
}
2159

    
2160
/**
2161
 * Interleaves a AVPacket correctly so it can be muxed.
2162
 * @param out the interleaved packet will be output here
2163
 * @param in the input packet
2164
 * @param flush 1 if no further packets are available as input and all
2165
 *              remaining packets should be output
2166
 * @return 1 if a packet was output, 0 if no packet could be output, 
2167
 *         < 0 if an error occured
2168
 */
2169
static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2170
    if(s->oformat->interleave_packet)
2171
        return s->oformat->interleave_packet(s, out, in, flush);
2172
    else
2173
        return av_interleave_packet_per_dts(s, out, in, flush);
2174
}
2175

    
2176
/**
2177
 * Writes a packet to an output media file ensuring correct interleaving. 
2178
 * The packet shall contain one audio or video frame.
2179
 * If the packets are already correctly interleaved the application should
2180
 * call av_write_frame() instead as its slightly faster, its also important
2181
 * to keep in mind that completly non interleaved input will need huge amounts
2182
 * of memory to interleave with this, so its prefereable to interleave at the
2183
 * demuxer level
2184
 *
2185
 * @param s media file handle
2186
 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2187
 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2188
 */
2189
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2190
    AVStream *st= s->streams[ pkt->stream_index];
2191

    
2192
    compute_pkt_fields2(st, pkt);
2193
    
2194
    //FIXME/XXX/HACK drop zero sized packets
2195
    if(st->codec.codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
2196
        return 0;
2197
    
2198
    if(pkt->dts == AV_NOPTS_VALUE)
2199
        return -1;
2200

    
2201
    for(;;){
2202
        AVPacket opkt;
2203
        int ret= av_interleave_packet(s, &opkt, pkt, 0);
2204
        if(ret<=0) //FIXME cleanup needed for ret<0 ?
2205
            return ret;
2206
        
2207
        truncate_ts(s->streams[opkt.stream_index], &opkt);
2208
        ret= s->oformat->write_packet(s, &opkt);
2209
        
2210
        av_free_packet(&opkt);
2211
        pkt= NULL;
2212
        
2213
        if(ret<0)
2214
            return ret;
2215
        if(url_ferror(&s->pb))
2216
            return url_ferror(&s->pb);
2217
    }
2218
}
2219

    
2220
/**
2221
 * write the stream trailer to an output media file and and free the
2222
 * file private data.
2223
 *
2224
 * @param s media file handle
2225
 * @return 0 if OK. AVERROR_xxx if error.  */
2226
int av_write_trailer(AVFormatContext *s)
2227
{
2228
    int ret, i;
2229
    
2230
    for(;;){
2231
        AVPacket pkt;
2232
        ret= av_interleave_packet(s, &pkt, NULL, 1);
2233
        if(ret<0) //FIXME cleanup needed for ret<0 ?
2234
            goto fail;
2235
        if(!ret)
2236
            break;
2237
        
2238
        truncate_ts(s->streams[pkt.stream_index], &pkt);
2239
        ret= s->oformat->write_packet(s, &pkt);
2240
        
2241
        av_free_packet(&pkt);
2242
        
2243
        if(ret<0)
2244
            goto fail;
2245
        if(url_ferror(&s->pb))
2246
            goto fail;
2247
    }
2248

    
2249
    ret = s->oformat->write_trailer(s);
2250
fail:
2251
    if(ret == 0)
2252
       ret=url_ferror(&s->pb);
2253
    for(i=0;i<s->nb_streams;i++)
2254
        av_freep(&s->streams[i]->priv_data);
2255
    av_freep(&s->priv_data);
2256
    return ret;
2257
}
2258

    
2259
/* "user interface" functions */
2260

    
2261
void dump_format(AVFormatContext *ic,
2262
                 int index, 
2263
                 const char *url,
2264
                 int is_output)
2265
{
2266
    int i, flags;
2267
    char buf[256];
2268

    
2269
    av_log(NULL, AV_LOG_DEBUG, "%s #%d, %s, %s '%s':\n", 
2270
            is_output ? "Output" : "Input",
2271
            index, 
2272
            is_output ? ic->oformat->name : ic->iformat->name, 
2273
            is_output ? "to" : "from", url);
2274
    if (!is_output) {
2275
        av_log(NULL, AV_LOG_DEBUG, "  Duration: ");
2276
        if (ic->duration != AV_NOPTS_VALUE) {
2277
            int hours, mins, secs, us;
2278
            secs = ic->duration / AV_TIME_BASE;
2279
            us = ic->duration % AV_TIME_BASE;
2280
            mins = secs / 60;
2281
            secs %= 60;
2282
            hours = mins / 60;
2283
            mins %= 60;
2284
            av_log(NULL, AV_LOG_DEBUG, "%02d:%02d:%02d.%01d", hours, mins, secs, 
2285
                   (10 * us) / AV_TIME_BASE);
2286
        } else {
2287
            av_log(NULL, AV_LOG_DEBUG, "N/A");
2288
        }
2289
        if (ic->start_time != AV_NOPTS_VALUE) {
2290
            int secs, us;
2291
            av_log(NULL, AV_LOG_DEBUG, ", start: ");
2292
            secs = ic->start_time / AV_TIME_BASE;
2293
            us = ic->start_time % AV_TIME_BASE;
2294
            av_log(NULL, AV_LOG_DEBUG, "%d.%06d",
2295
                   secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2296
        }
2297
        av_log(NULL, AV_LOG_DEBUG, ", bitrate: ");
2298
        if (ic->bit_rate) {
2299
            av_log(NULL, AV_LOG_DEBUG,"%d kb/s", ic->bit_rate / 1000);
2300
        } else {
2301
            av_log(NULL, AV_LOG_DEBUG, "N/A");
2302
        }
2303
        av_log(NULL, AV_LOG_DEBUG, "\n");
2304
    }
2305
    for(i=0;i<ic->nb_streams;i++) {
2306
        AVStream *st = ic->streams[i];
2307
        avcodec_string(buf, sizeof(buf), &st->codec, is_output);
2308
        av_log(NULL, AV_LOG_DEBUG, "  Stream #%d.%d", index, i);
2309
        /* the pid is an important information, so we display it */
2310
        /* XXX: add a generic system */
2311
        if (is_output)
2312
            flags = ic->oformat->flags;
2313
        else
2314
            flags = ic->iformat->flags;
2315
        if (flags & AVFMT_SHOW_IDS) {
2316
            av_log(NULL, AV_LOG_DEBUG, "[0x%x]", st->id);
2317
        }
2318
        av_log(NULL, AV_LOG_DEBUG, ": %s\n", buf);
2319
    }
2320
}
2321

    
2322
typedef struct {
2323
    const char *abv;
2324
    int width, height;
2325
    int frame_rate, frame_rate_base;
2326
} AbvEntry;
2327

    
2328
static AbvEntry frame_abvs[] = {
2329
    { "ntsc",      720, 480, 30000, 1001 },
2330
    { "pal",       720, 576,    25,    1 },
2331
    { "qntsc",     352, 240, 30000, 1001 }, /* VCD compliant ntsc */
2332
    { "qpal",      352, 288,    25,    1 }, /* VCD compliant pal */
2333
    { "sntsc",     640, 480, 30000, 1001 }, /* square pixel ntsc */
2334
    { "spal",      768, 576,    25,    1 }, /* square pixel pal */
2335
    { "film",      352, 240,    24,    1 },
2336
    { "ntsc-film", 352, 240, 24000, 1001 },
2337
    { "sqcif",     128,  96,     0,    0 },
2338
    { "qcif",      176, 144,     0,    0 },
2339
    { "cif",       352, 288,     0,    0 },
2340
    { "4cif",      704, 576,     0,    0 },
2341
};
2342

    
2343
int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2344
{
2345
    int i;
2346
    int n = sizeof(frame_abvs) / sizeof(AbvEntry);
2347
    const char *p;
2348
    int frame_width = 0, frame_height = 0;
2349

    
2350
    for(i=0;i<n;i++) {
2351
        if (!strcmp(frame_abvs[i].abv, str)) {
2352
            frame_width = frame_abvs[i].width;
2353
            frame_height = frame_abvs[i].height;
2354
            break;
2355
        }
2356
    }
2357
    if (i == n) {
2358
        p = str;
2359
        frame_width = strtol(p, (char **)&p, 10);
2360
        if (*p)
2361
            p++;
2362
        frame_height = strtol(p, (char **)&p, 10);
2363
    }
2364
    if (frame_width <= 0 || frame_height <= 0)
2365
        return -1;
2366
    *width_ptr = frame_width;
2367
    *height_ptr = frame_height;
2368
    return 0;
2369
}
2370

    
2371
int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
2372
{
2373
    int i;
2374
    char* cp;
2375
   
2376
    /* First, we check our abbreviation table */
2377
    for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
2378
         if (!strcmp(frame_abvs[i].abv, arg)) {
2379
             *frame_rate = frame_abvs[i].frame_rate;
2380
             *frame_rate_base = frame_abvs[i].frame_rate_base;
2381
             return 0;
2382
         }
2383

    
2384
    /* Then, we try to parse it as fraction */
2385
    cp = strchr(arg, '/');
2386
    if (cp) {
2387
        char* cpp;
2388
        *frame_rate = strtol(arg, &cpp, 10);
2389
        if (cpp != arg || cpp == cp) 
2390
            *frame_rate_base = strtol(cp+1, &cpp, 10);
2391
        else
2392
           *frame_rate = 0;
2393
    } 
2394
    else {
2395
        /* Finally we give up and parse it as double */
2396
        *frame_rate_base = DEFAULT_FRAME_RATE_BASE; //FIXME use av_d2q()
2397
        *frame_rate = (int)(strtod(arg, 0) * (*frame_rate_base) + 0.5);
2398
    }
2399
    if (!*frame_rate || !*frame_rate_base)
2400
        return -1;
2401
    else
2402
        return 0;
2403
}
2404

    
2405
/* Syntax:
2406
 * - If not a duration:
2407
 *  [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
2408
 * Time is localtime unless Z is suffixed to the end. In this case GMT
2409
 * Return the date in micro seconds since 1970 
2410
 * - If duration:
2411
 *  HH[:MM[:SS[.m...]]]
2412
 *  S+[.m...]
2413
 */
2414
int64_t parse_date(const char *datestr, int duration)
2415
{
2416
    const char *p;
2417
    int64_t t;
2418
    struct tm dt;
2419
    int i;
2420
    static const char *date_fmt[] = {
2421
        "%Y-%m-%d",
2422
        "%Y%m%d",
2423
    };
2424
    static const char *time_fmt[] = {
2425
        "%H:%M:%S",
2426
        "%H%M%S",
2427
    };
2428
    const char *q;
2429
    int is_utc, len;
2430
    char lastch;
2431
    int negative = 0;
2432

    
2433
#undef time
2434
    time_t now = time(0);
2435

    
2436
    len = strlen(datestr);
2437
    if (len > 0)
2438
        lastch = datestr[len - 1];
2439
    else
2440
        lastch = '\0';
2441
    is_utc = (lastch == 'z' || lastch == 'Z');
2442

    
2443
    memset(&dt, 0, sizeof(dt));
2444

    
2445
    p = datestr;
2446
    q = NULL;
2447
    if (!duration) {
2448
        for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
2449
            q = small_strptime(p, date_fmt[i], &dt);
2450
            if (q) {
2451
                break;
2452
            }
2453
        }
2454

    
2455
        if (!q) {
2456
            if (is_utc) {
2457
                dt = *gmtime(&now);
2458
            } else {
2459
                dt = *localtime(&now);
2460
            }
2461
            dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
2462
        } else {
2463
            p = q;
2464
        }
2465

    
2466
        if (*p == 'T' || *p == 't' || *p == ' ')
2467
            p++;
2468

    
2469
        for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
2470
            q = small_strptime(p, time_fmt[i], &dt);
2471
            if (q) {
2472
                break;
2473
            }
2474
        }
2475
    } else {
2476
        if (p[0] == '-') {
2477
            negative = 1;
2478
            ++p;
2479
        }
2480
        q = small_strptime(p, time_fmt[0], &dt);
2481
        if (!q) {
2482
            dt.tm_sec = strtol(p, (char **)&q, 10);
2483
            dt.tm_min = 0;
2484
            dt.tm_hour = 0;
2485
        }
2486
    }
2487

    
2488
    /* Now we have all the fields that we can get */
2489
    if (!q) {
2490
        if (duration)
2491
            return 0;
2492
        else
2493
            return now * int64_t_C(1000000);
2494
    }
2495

    
2496
    if (duration) {
2497
        t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2498
    } else {
2499
        dt.tm_isdst = -1;       /* unknown */
2500
        if (is_utc) {
2501
            t = mktimegm(&dt);
2502
        } else {
2503
            t = mktime(&dt);
2504
        }
2505
    }
2506

    
2507
    t *= 1000000;
2508

    
2509
    if (*q == '.') {
2510
        int val, n;
2511
        q++;
2512
        for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
2513
            if (!isdigit(*q)) 
2514
                break;
2515
            val += n * (*q - '0');
2516
        }
2517
        t += val;
2518
    }
2519
    return negative ? -t : t;
2520
}
2521

    
2522
/* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
2523
   1 if found */
2524
int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2525
{
2526
    const char *p;
2527
    char tag[128], *q;
2528

    
2529
    p = info;
2530
    if (*p == '?')
2531
        p++;
2532
    for(;;) {
2533
        q = tag;
2534
        while (*p != '\0' && *p != '=' && *p != '&') {
2535
            if ((q - tag) < sizeof(tag) - 1)
2536
                *q++ = *p;
2537
            p++;
2538
        }
2539
        *q = '\0';
2540
        q = arg;
2541
        if (*p == '=') {
2542
            p++;
2543
            while (*p != '&' && *p != '\0') {
2544
                if ((q - arg) < arg_size - 1) {
2545
                    if (*p == '+')
2546
                        *q++ = ' ';
2547
                    else
2548
                        *q++ = *p;
2549
                }
2550
                p++;
2551
            }
2552
            *q = '\0';
2553
        }
2554
        if (!strcmp(tag, tag1)) 
2555
            return 1;
2556
        if (*p != '&')
2557
            break;
2558
        p++;
2559
    }
2560
    return 0;
2561
}
2562

    
2563
/* Return in 'buf' the path with '%d' replaced by number. Also handles
2564
   the '%0nd' format where 'n' is the total number of digits and
2565
   '%%'. Return 0 if OK, and -1 if format error */
2566
int get_frame_filename(char *buf, int buf_size,
2567
                       const char *path, int number)
2568
{
2569
    const char *p;
2570
    char *q, buf1[20], c;
2571
    int nd, len, percentd_found;
2572

    
2573
    q = buf;
2574
    p = path;
2575
    percentd_found = 0;
2576
    for(;;) {
2577
        c = *p++;
2578
        if (c == '\0')
2579
            break;
2580
        if (c == '%') {
2581
            do {
2582
                nd = 0;
2583
                while (isdigit(*p)) {
2584
                    nd = nd * 10 + *p++ - '0';
2585
                }
2586
                c = *p++;
2587
            } while (isdigit(c));
2588

    
2589
            switch(c) {
2590
            case '%':
2591
                goto addchar;
2592
            case 'd':
2593
                if (percentd_found)
2594
                    goto fail;
2595
                percentd_found = 1;
2596
                snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2597
                len = strlen(buf1);
2598
                if ((q - buf + len) > buf_size - 1)
2599
                    goto fail;
2600
                memcpy(q, buf1, len);
2601
                q += len;
2602
                break;
2603
            default:
2604
                goto fail;
2605
            }
2606
        } else {
2607
        addchar:
2608
            if ((q - buf) < buf_size - 1)
2609
                *q++ = c;
2610
        }
2611
    }
2612
    if (!percentd_found)
2613
        goto fail;
2614
    *q = '\0';
2615
    return 0;
2616
 fail:
2617
    *q = '\0';
2618
    return -1;
2619
}
2620

    
2621
/**
2622
 * Print  nice hexa dump of a buffer
2623
 * @param f stream for output
2624
 * @param buf buffer
2625
 * @param size buffer size
2626
 */
2627
void av_hex_dump(FILE *f, uint8_t *buf, int size)
2628
{
2629
    int len, i, j, c;
2630

    
2631
    for(i=0;i<size;i+=16) {
2632
        len = size - i;
2633
        if (len > 16)
2634
            len = 16;
2635
        fprintf(f, "%08x ", i);
2636
        for(j=0;j<16;j++) {
2637
            if (j < len)
2638
                fprintf(f, " %02x", buf[i+j]);
2639
            else
2640
                fprintf(f, "   ");
2641
        }
2642
        fprintf(f, " ");
2643
        for(j=0;j<len;j++) {
2644
            c = buf[i+j];
2645
            if (c < ' ' || c > '~')
2646
                c = '.';
2647
            fprintf(f, "%c", c);
2648
        }
2649
        fprintf(f, "\n");
2650
    }
2651
}
2652

    
2653
/**
2654
 * Print on 'f' a nice dump of a packet
2655
 * @param f stream for output
2656
 * @param pkt packet to dump
2657
 * @param dump_payload true if the payload must be displayed too
2658
 */
2659
void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
2660
{
2661
    fprintf(f, "stream #%d:\n", pkt->stream_index);
2662
    fprintf(f, "  keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
2663
    fprintf(f, "  duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
2664
    /* DTS is _always_ valid after av_read_frame() */
2665
    fprintf(f, "  dts=");
2666
    if (pkt->dts == AV_NOPTS_VALUE)
2667
        fprintf(f, "N/A");
2668
    else
2669
        fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
2670
    /* PTS may be not known if B frames are present */
2671
    fprintf(f, "  pts=");
2672
    if (pkt->pts == AV_NOPTS_VALUE)
2673
        fprintf(f, "N/A");
2674
    else
2675
        fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
2676
    fprintf(f, "\n");
2677
    fprintf(f, "  size=%d\n", pkt->size);
2678
    if (dump_payload)
2679
        av_hex_dump(f, pkt->data, pkt->size);
2680
}
2681

    
2682
void url_split(char *proto, int proto_size,
2683
               char *authorization, int authorization_size,
2684
               char *hostname, int hostname_size,
2685
               int *port_ptr,
2686
               char *path, int path_size,
2687
               const char *url)
2688
{
2689
    const char *p;
2690
    char *q;
2691
    int port;
2692

    
2693
    port = -1;
2694

    
2695
    p = url;
2696
    q = proto;
2697
    while (*p != ':' && *p != '\0') {
2698
        if ((q - proto) < proto_size - 1)
2699
            *q++ = *p;
2700
        p++;
2701
    }
2702
    if (proto_size > 0)
2703
        *q = '\0';
2704
    if (authorization_size > 0)
2705
        authorization[0] = '\0';
2706
    if (*p == '\0') {
2707
        if (proto_size > 0)
2708
            proto[0] = '\0';
2709
        if (hostname_size > 0)
2710
            hostname[0] = '\0';
2711
        p = url;
2712
    } else {
2713
        char *at,*slash; // PETR: position of '@' character and '/' character
2714

    
2715
        p++;
2716
        if (*p == '/')
2717
            p++;
2718
        if (*p == '/')
2719
            p++;
2720
        at = strchr(p,'@'); // PETR: get the position of '@'
2721
        slash = strchr(p,'/');  // PETR: get position of '/' - end of hostname
2722
        if (at && slash && at > slash) at = NULL; // PETR: not interested in '@' behind '/'
2723

    
2724
        q = at ? authorization : hostname;  // PETR: if '@' exists starting with auth.
2725

    
2726
         while ((at || *p != ':') && *p != '/' && *p != '?' && *p != '\0') { // PETR:
2727
            if (*p == '@') {    // PETR: passed '@'
2728
              if (authorization_size > 0)
2729
                  *q = '\0';
2730
              q = hostname;
2731
              at = NULL;
2732
            } else if (!at) {   // PETR: hostname
2733
              if ((q - hostname) < hostname_size - 1)
2734
                  *q++ = *p;
2735
            } else {
2736
              if ((q - authorization) < authorization_size - 1)
2737
                *q++ = *p;
2738
            }
2739
            p++;
2740
        }
2741
        if (hostname_size > 0)
2742
            *q = '\0';
2743
        if (*p == ':') {
2744
            p++;
2745
            port = strtoul(p, (char **)&p, 10);
2746
        }
2747
    }
2748
    if (port_ptr)
2749
        *port_ptr = port;
2750
    pstrcpy(path, path_size, p);
2751
}
2752

    
2753
/**
2754
 * Set the pts for a given stream
2755
 * @param s stream 
2756
 * @param pts_wrap_bits number of bits effectively used by the pts
2757
 *        (used for wrap control, 33 is the value for MPEG) 
2758
 * @param pts_num numerator to convert to seconds (MPEG: 1) 
2759
 * @param pts_den denominator to convert to seconds (MPEG: 90000)
2760
 */
2761
void av_set_pts_info(AVStream *s, int pts_wrap_bits,
2762
                     int pts_num, int pts_den)
2763
{
2764
    s->pts_wrap_bits = pts_wrap_bits;
2765
    s->time_base.num = pts_num;
2766
    s->time_base.den = pts_den;
2767
}
2768

    
2769
/* fraction handling */
2770

    
2771
/**
2772
 * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
2773
 * as 0 <= num < den.
2774
 *
2775
 * @param f fractional number
2776
 * @param val integer value
2777
 * @param num must be >= 0
2778
 * @param den must be >= 1 
2779
 */
2780
void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
2781
{
2782
    num += (den >> 1);
2783
    if (num >= den) {
2784
        val += num / den;
2785
        num = num % den;
2786
    }
2787
    f->val = val;
2788
    f->num = num;
2789
    f->den = den;
2790
}
2791

    
2792
/* set f to (val + 0.5) */
2793
void av_frac_set(AVFrac *f, int64_t val)
2794
{
2795
    f->val = val;
2796
    f->num = f->den >> 1;
2797
}
2798

    
2799
/**
2800
 * Fractionnal addition to f: f = f + (incr / f->den)
2801
 *
2802
 * @param f fractional number
2803
 * @param incr increment, can be positive or negative
2804
 */
2805
void av_frac_add(AVFrac *f, int64_t incr)
2806
{
2807
    int64_t num, den;
2808

    
2809
    num = f->num + incr;
2810
    den = f->den;
2811
    if (num < 0) {
2812
        f->val += num / den;
2813
        num = num % den;
2814
        if (num < 0) {
2815
            num += den;
2816
            f->val--;
2817
        }
2818
    } else if (num >= den) {
2819
        f->val += num / den;
2820
        num = num % den;
2821
    }
2822
    f->num = num;
2823
}
2824

    
2825
/**
2826
 * register a new image format
2827
 * @param img_fmt Image format descriptor
2828
 */
2829
void av_register_image_format(AVImageFormat *img_fmt)
2830
{
2831
    AVImageFormat **p;
2832

    
2833
    p = &first_image_format;
2834
    while (*p != NULL) p = &(*p)->next;
2835
    *p = img_fmt;
2836
    img_fmt->next = NULL;
2837
}
2838

    
2839
/* guess image format */
2840
AVImageFormat *av_probe_image_format(AVProbeData *pd)
2841
{
2842
    AVImageFormat *fmt1, *fmt;
2843
    int score, score_max;
2844

    
2845
    fmt = NULL;
2846
    score_max = 0;
2847
    for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
2848
        if (fmt1->img_probe) {
2849
            score = fmt1->img_probe(pd);
2850
            if (score > score_max) {
2851
                score_max = score;
2852
                fmt = fmt1;
2853
            }
2854
        }
2855
    }
2856
    return fmt;
2857
}
2858

    
2859
AVImageFormat *guess_image_format(const char *filename)
2860
{
2861
    AVImageFormat *fmt1;
2862

    
2863
    for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
2864
        if (fmt1->extensions && match_ext(filename, fmt1->extensions))
2865
            return fmt1;
2866
    }
2867
    return NULL;
2868
}
2869

    
2870
/**
2871
 * Read an image from a stream. 
2872
 * @param gb byte stream containing the image
2873
 * @param fmt image format, NULL if probing is required
2874
 */
2875
int av_read_image(ByteIOContext *pb, const char *filename,
2876
                  AVImageFormat *fmt,
2877
                  int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
2878
{
2879
    char buf[PROBE_BUF_SIZE];
2880
    AVProbeData probe_data, *pd = &probe_data;
2881
    offset_t pos;
2882
    int ret;
2883

    
2884
    if (!fmt) {
2885
        pd->filename = filename;
2886
        pd->buf = buf;
2887
        pos = url_ftell(pb);
2888
        pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
2889
        url_fseek(pb, pos, SEEK_SET);
2890
        fmt = av_probe_image_format(pd);
2891
    }
2892
    if (!fmt)
2893
        return AVERROR_NOFMT;
2894
    ret = fmt->img_read(pb, alloc_cb, opaque);
2895
    return ret;
2896
}
2897

    
2898
/**
2899
 * Write an image to a stream.
2900
 * @param pb byte stream for the image output
2901
 * @param fmt image format
2902
 * @param img image data and informations
2903
 */
2904
int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
2905
{
2906
    return fmt->img_write(pb, img);
2907
}
2908