Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ cf7eef66

History | View | Annotate | Download (75.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;
25
AVOutputFormat *first_oformat;
26
AVImageFormat *first_image_format;
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
        guess_image_format(filename)) {
83
        return guess_format("image", NULL, NULL);
84
    }
85

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

    
109
AVOutputFormat *guess_stream_format(const char *short_name, const char *filename, 
110
                             const char *mime_type)
111
{
112
    AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
113

    
114
    if (fmt) {
115
        AVOutputFormat *stream_fmt;
116
        char stream_format_name[64];
117

    
118
        snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
119
        stream_fmt = guess_format(stream_format_name, NULL, NULL);
120

    
121
        if (stream_fmt)
122
            fmt = stream_fmt;
123
    }
124

    
125
    return fmt;
126
}
127

    
128
AVInputFormat *av_find_input_format(const char *short_name)
129
{
130
    AVInputFormat *fmt;
131
    for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
132
        if (!strcmp(fmt->name, short_name))
133
            return fmt;
134
    }
135
    return NULL;
136
}
137

    
138
/* memory handling */
139

    
140
/**
141
 * Default packet destructor 
142
 */
143
static void av_destruct_packet(AVPacket *pkt)
144
{
145
    av_free(pkt->data);
146
    pkt->data = NULL; pkt->size = 0;
147
}
148

    
149
/**
150
 * Allocate the payload of a packet and intialized its fields to default values.
151
 *
152
 * @param pkt packet
153
 * @param size wanted payload size
154
 * @return 0 if OK. AVERROR_xxx otherwise.
155
 */
156
int av_new_packet(AVPacket *pkt, int size)
157
{
158
    void *data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
159
    if (!data)
160
        return AVERROR_NOMEM;
161
    memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
162

    
163
    av_init_packet(pkt);
164
    pkt->data = data; 
165
    pkt->size = size;
166
    pkt->destruct = av_destruct_packet;
167
    return 0;
168
}
169

    
170
/* This is a hack - the packet memory allocation stuff is broken. The
171
   packet is allocated if it was not really allocated */
172
int av_dup_packet(AVPacket *pkt)
173
{
174
    if (pkt->destruct != av_destruct_packet) {
175
        uint8_t *data;
176
        /* we duplicate the packet and don't forget to put the padding
177
           again */
178
        data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
179
        if (!data) {
180
            return AVERROR_NOMEM;
181
        }
182
        memcpy(data, pkt->data, pkt->size);
183
        memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
184
        pkt->data = data;
185
        pkt->destruct = av_destruct_packet;
186
    }
187
    return 0;
188
}
189

    
190
/* fifo handling */
191

    
192
int fifo_init(FifoBuffer *f, int size)
193
{
194
    f->buffer = av_malloc(size);
195
    if (!f->buffer)
196
        return -1;
197
    f->end = f->buffer + size;
198
    f->wptr = f->rptr = f->buffer;
199
    return 0;
200
}
201

    
202
void fifo_free(FifoBuffer *f)
203
{
204
    av_free(f->buffer);
205
}
206

    
207
int fifo_size(FifoBuffer *f, uint8_t *rptr)
208
{
209
    int size;
210

    
211
    if (f->wptr >= rptr) {
212
        size = f->wptr - rptr;
213
    } else {
214
        size = (f->end - rptr) + (f->wptr - f->buffer);
215
    }
216
    return size;
217
}
218

    
219
/* get data from the fifo (return -1 if not enough data) */
220
int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
221
{
222
    uint8_t *rptr = *rptr_ptr;
223
    int size, len;
224

    
225
    if (f->wptr >= rptr) {
226
        size = f->wptr - rptr;
227
    } else {
228
        size = (f->end - rptr) + (f->wptr - f->buffer);
229
    }
230
    
231
    if (size < buf_size)
232
        return -1;
233
    while (buf_size > 0) {
234
        len = f->end - rptr;
235
        if (len > buf_size)
236
            len = buf_size;
237
        memcpy(buf, rptr, len);
238
        buf += len;
239
        rptr += len;
240
        if (rptr >= f->end)
241
            rptr = f->buffer;
242
        buf_size -= len;
243
    }
244
    *rptr_ptr = rptr;
245
    return 0;
246
}
247

    
248
void fifo_write(FifoBuffer *f, uint8_t *buf, int size, uint8_t **wptr_ptr)
249
{
250
    int len;
251
    uint8_t *wptr;
252
    wptr = *wptr_ptr;
253
    while (size > 0) {
254
        len = f->end - wptr;
255
        if (len > size)
256
            len = size;
257
        memcpy(wptr, buf, len);
258
        wptr += len;
259
        if (wptr >= f->end)
260
            wptr = f->buffer;
261
        buf += len;
262
        size -= len;
263
    }
264
    *wptr_ptr = wptr;
265
}
266

    
267
int filename_number_test(const char *filename)
268
{
269
    char buf[1024];
270
    if(!filename)
271
        return -1;
272
    return get_frame_filename(buf, sizeof(buf), filename, 1);
273
}
274

    
275
/* guess file format */
276
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
277
{
278
    AVInputFormat *fmt1, *fmt;
279
    int score, score_max;
280

    
281
    fmt = NULL;
282
    score_max = 0;
283
    for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
284
        if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
285
            continue;
286
        score = 0;
287
        if (fmt1->read_probe) {
288
            score = fmt1->read_probe(pd);
289
        } else if (fmt1->extensions) {
290
            if (match_ext(pd->filename, fmt1->extensions)) {
291
                score = 50;
292
            }
293
        } 
294
        if (score > score_max) {
295
            score_max = score;
296
            fmt = fmt1;
297
        }
298
    }
299
    return fmt;
300
}
301

    
302
/************************************************************/
303
/* input media file */
304

    
305
/**
306
 * open a media file from an IO stream. 'fmt' must be specified.
307
 */
308

    
309
static const char* format_to_name(void* ptr)
310
{
311
    AVFormatContext* fc = (AVFormatContext*) ptr;
312
    if(fc->iformat) return fc->iformat->name;
313
    else if(fc->oformat) return fc->oformat->name;
314
    else return "NULL";
315
}
316

    
317
static const AVClass av_format_context_class = { "AVFormatContext", format_to_name };
318

    
319
AVFormatContext *av_alloc_format_context(void)
320
{
321
    AVFormatContext *ic;
322
    ic = av_mallocz(sizeof(AVFormatContext));
323
    if (!ic) return ic;
324
    ic->av_class = &av_format_context_class;
325
    return ic;
326
}
327

    
328
int av_open_input_stream(AVFormatContext **ic_ptr, 
329
                         ByteIOContext *pb, const char *filename, 
330
                         AVInputFormat *fmt, AVFormatParameters *ap)
331
{
332
    int err;
333
    AVFormatContext *ic;
334

    
335
    ic = av_alloc_format_context();
336
    if (!ic) {
337
        err = AVERROR_NOMEM;
338
        goto fail;
339
    }
340
    ic->iformat = fmt;
341
    if (pb)
342
        ic->pb = *pb;
343
    ic->duration = AV_NOPTS_VALUE;
344
    ic->start_time = AV_NOPTS_VALUE;
345
    pstrcpy(ic->filename, sizeof(ic->filename), filename);
346

    
347
    /* allocate private data */
348
    if (fmt->priv_data_size > 0) {
349
        ic->priv_data = av_mallocz(fmt->priv_data_size);
350
        if (!ic->priv_data) {
351
            err = AVERROR_NOMEM;
352
            goto fail;
353
        }
354
    } else {
355
        ic->priv_data = NULL;
356
    }
357

    
358
    err = ic->iformat->read_header(ic, ap);
359
    if (err < 0)
360
        goto fail;
361

    
362
    if (pb)
363
        ic->data_offset = url_ftell(&ic->pb);
364

    
365
    *ic_ptr = ic;
366
    return 0;
367
 fail:
368
    if (ic) {
369
        av_freep(&ic->priv_data);
370
    }
371
    av_free(ic);
372
    *ic_ptr = NULL;
373
    return err;
374
}
375

    
376
#define PROBE_BUF_SIZE 2048
377

    
378
/**
379
 * Open a media file as input. The codec are not opened. Only the file
380
 * header (if present) is read.
381
 *
382
 * @param ic_ptr the opened media file handle is put here
383
 * @param filename filename to open.
384
 * @param fmt if non NULL, force the file format to use
385
 * @param buf_size optional buffer size (zero if default is OK)
386
 * @param ap additionnal parameters needed when opening the file (NULL if default)
387
 * @return 0 if OK. AVERROR_xxx otherwise.
388
 */
389
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename, 
390
                       AVInputFormat *fmt,
391
                       int buf_size,
392
                       AVFormatParameters *ap)
393
{
394
    int err, must_open_file, file_opened;
395
    uint8_t buf[PROBE_BUF_SIZE];
396
    AVProbeData probe_data, *pd = &probe_data;
397
    ByteIOContext pb1, *pb = &pb1;
398
    
399
    file_opened = 0;
400
    pd->filename = "";
401
    if (filename)
402
        pd->filename = filename;
403
    pd->buf = buf;
404
    pd->buf_size = 0;
405

    
406
    if (!fmt) {
407
        /* guess format if no file can be opened  */
408
        fmt = av_probe_input_format(pd, 0);
409
    }
410

    
411
    /* do not open file if the format does not need it. XXX: specific
412
       hack needed to handle RTSP/TCP */
413
    must_open_file = 1;
414
    if (fmt && (fmt->flags & AVFMT_NOFILE)) {
415
        must_open_file = 0;
416
    }
417

    
418
    if (!fmt || must_open_file) {
419
        /* if no file needed do not try to open one */
420
        if (url_fopen(pb, filename, URL_RDONLY) < 0) {
421
            err = AVERROR_IO;
422
            goto fail;
423
        }
424
        file_opened = 1;
425
        if (buf_size > 0) {
426
            url_setbufsize(pb, buf_size);
427
        }
428
        if (!fmt) {
429
            /* read probe data */
430
            pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
431
            url_fseek(pb, 0, SEEK_SET);
432
        }
433
    }
434
    
435
    /* guess file format */
436
    if (!fmt) {
437
        fmt = av_probe_input_format(pd, 1);
438
    }
439

    
440
    /* if still no format found, error */
441
    if (!fmt) {
442
        err = AVERROR_NOFMT;
443
        goto fail;
444
    }
445
        
446
    /* XXX: suppress this hack for redirectors */
447
#ifdef CONFIG_NETWORK
448
    if (fmt == &redir_demux) {
449
        err = redir_open(ic_ptr, pb);
450
        url_fclose(pb);
451
        return err;
452
    }
453
#endif
454

    
455
    /* check filename in case of an image number is expected */
456
    if (fmt->flags & AVFMT_NEEDNUMBER) {
457
        if (filename_number_test(filename) < 0) { 
458
            err = AVERROR_NUMEXPECTED;
459
            goto fail;
460
        }
461
    }
462
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
463
    if (err)
464
        goto fail;
465
    return 0;
466
 fail:
467
    if (file_opened)
468
        url_fclose(pb);
469
    *ic_ptr = NULL;
470
    return err;
471
    
472
}
473

    
474
/*******************************************************/
475

    
476
/**
477
 * Read a transport packet from a media file. This function is
478
 * absolete and should never be used. Use av_read_frame() instead.
479
 * 
480
 * @param s media file handle
481
 * @param pkt is filled 
482
 * @return 0 if OK. AVERROR_xxx if error.  
483
 */
484
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
485
{
486
    return s->iformat->read_packet(s, pkt);
487
}
488

    
489
/**********************************************************/
490

    
491
/* get the number of samples of an audio frame. Return (-1) if error */
492
static int get_audio_frame_size(AVCodecContext *enc, int size)
493
{
494
    int frame_size;
495

    
496
    if (enc->frame_size <= 1) {
497
        /* specific hack for pcm codecs because no frame size is
498
           provided */
499
        switch(enc->codec_id) {
500
        case CODEC_ID_PCM_S16LE:
501
        case CODEC_ID_PCM_S16BE:
502
        case CODEC_ID_PCM_U16LE:
503
        case CODEC_ID_PCM_U16BE:
504
            if (enc->channels == 0)
505
                return -1;
506
            frame_size = size / (2 * enc->channels);
507
            break;
508
        case CODEC_ID_PCM_S8:
509
        case CODEC_ID_PCM_U8:
510
        case CODEC_ID_PCM_MULAW:
511
        case CODEC_ID_PCM_ALAW:
512
            if (enc->channels == 0)
513
                return -1;
514
            frame_size = size / (enc->channels);
515
            break;
516
        default:
517
            /* used for example by ADPCM codecs */
518
            if (enc->bit_rate == 0)
519
                return -1;
520
            frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
521
            break;
522
        }
523
    } else {
524
        frame_size = enc->frame_size;
525
    }
526
    return frame_size;
527
}
528

    
529

    
530
/* return the frame duration in seconds, return 0 if not available */
531
static void compute_frame_duration(int *pnum, int *pden, AVStream *st, 
532
                                   AVCodecParserContext *pc, AVPacket *pkt)
533
{
534
    int frame_size;
535

    
536
    *pnum = 0;
537
    *pden = 0;
538
    switch(st->codec.codec_type) {
539
    case CODEC_TYPE_VIDEO:
540
        *pnum = st->codec.frame_rate_base;
541
        *pden = st->codec.frame_rate;
542
        if (pc && pc->repeat_pict) {
543
            *pden *= 2;
544
            *pnum = (*pnum) * (2 + pc->repeat_pict);
545
        }
546
        break;
547
    case CODEC_TYPE_AUDIO:
548
        frame_size = get_audio_frame_size(&st->codec, pkt->size);
549
        if (frame_size < 0)
550
            break;
551
        *pnum = frame_size;
552
        *pden = st->codec.sample_rate;
553
        break;
554
    default:
555
        break;
556
    }
557
}
558

    
559
static int64_t lsb2full(int64_t lsb, int64_t last_ts, int lsb_bits){
560
    int64_t mask = lsb_bits < 64 ? (1LL<<lsb_bits)-1 : -1LL;
561
    int64_t delta= last_ts - mask/2;
562
    return  ((lsb - delta)&mask) + delta;
563
}
564

    
565
static void compute_pkt_fields(AVFormatContext *s, AVStream *st, 
566
                               AVCodecParserContext *pc, AVPacket *pkt)
567
{
568
    int num, den, presentation_delayed;
569

    
570
    /* handle wrapping */
571
    if(st->cur_dts != AV_NOPTS_VALUE){
572
        if(pkt->pts != AV_NOPTS_VALUE)
573
            pkt->pts= lsb2full(pkt->pts, st->cur_dts, st->pts_wrap_bits);
574
        if(pkt->dts != AV_NOPTS_VALUE)
575
            pkt->dts= lsb2full(pkt->dts, st->cur_dts, st->pts_wrap_bits);
576
    }
577
    
578
    if (pkt->duration == 0) {
579
        compute_frame_duration(&num, &den, st, pc, pkt);
580
        if (den && num) {
581
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
582
        }
583
    }
584

    
585
    /* do we have a video B frame ? */
586
    presentation_delayed = 0;
587
    if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
588
        /* XXX: need has_b_frame, but cannot get it if the codec is
589
           not initialized */
590
        if ((st->codec.codec_id == CODEC_ID_MPEG1VIDEO ||
591
             st->codec.codec_id == CODEC_ID_MPEG2VIDEO ||
592
             st->codec.codec_id == CODEC_ID_MPEG4 ||
593
             st->codec.codec_id == CODEC_ID_H264) && 
594
            pc && pc->pict_type != FF_B_TYPE)
595
            presentation_delayed = 1;
596
        /* this may be redundant, but it shouldnt hurt */
597
        if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
598
            presentation_delayed = 1;
599
    }
600
    
601
    if(st->cur_dts == AV_NOPTS_VALUE){
602
        if(presentation_delayed) st->cur_dts = -pkt->duration;
603
        else                     st->cur_dts = 0;
604
    }
605

    
606
//    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);
607
    /* interpolate PTS and DTS if they are not present */
608
    if (presentation_delayed) {
609
        /* DTS = decompression time stamp */
610
        /* PTS = presentation time stamp */
611
        if (pkt->dts == AV_NOPTS_VALUE) {
612
            /* if we know the last pts, use it */
613
            if(st->last_IP_pts != AV_NOPTS_VALUE)
614
                st->cur_dts = pkt->dts = st->last_IP_pts;
615
            else
616
                pkt->dts = st->cur_dts;
617
        } else {
618
            st->cur_dts = pkt->dts;
619
        }
620
        /* this is tricky: the dts must be incremented by the duration
621
           of the frame we are displaying, i.e. the last I or P frame */
622
        if (st->last_IP_duration == 0)
623
            st->cur_dts += pkt->duration;
624
        else
625
            st->cur_dts += st->last_IP_duration;
626
        st->last_IP_duration  = pkt->duration;
627
        st->last_IP_pts= pkt->pts;
628
        /* cannot compute PTS if not present (we can compute it only
629
           by knowing the futur */
630
    } else {
631
        /* presentation is not delayed : PTS and DTS are the same */
632
        if (pkt->pts == AV_NOPTS_VALUE) {
633
            if (pkt->dts == AV_NOPTS_VALUE) {
634
                pkt->pts = st->cur_dts;
635
                pkt->dts = st->cur_dts;
636
            }
637
            else {
638
                st->cur_dts = pkt->dts;
639
                pkt->pts = pkt->dts;
640
            }
641
        } else {
642
            st->cur_dts = pkt->pts;
643
            pkt->dts = pkt->pts;
644
        }
645
        st->cur_dts += pkt->duration;
646
    }
647
//    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);
648
    
649
    /* update flags */
650
    if (pc) {
651
        pkt->flags = 0;
652
        /* key frame computation */
653
        switch(st->codec.codec_type) {
654
        case CODEC_TYPE_VIDEO:
655
            if (pc->pict_type == FF_I_TYPE)
656
                pkt->flags |= PKT_FLAG_KEY;
657
            break;
658
        case CODEC_TYPE_AUDIO:
659
            pkt->flags |= PKT_FLAG_KEY;
660
            break;
661
        default:
662
            break;
663
        }
664
    }
665

    
666
    /* convert the packet time stamp units */
667
    if(pkt->pts != AV_NOPTS_VALUE)
668
        pkt->pts = av_rescale(pkt->pts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
669
    if(pkt->dts != AV_NOPTS_VALUE)
670
        pkt->dts = av_rescale(pkt->dts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
671

    
672
    /* duration field */
673
    pkt->duration = av_rescale(pkt->duration, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
674
}
675

    
676
static void av_destruct_packet_nofree(AVPacket *pkt)
677
{
678
    pkt->data = NULL; pkt->size = 0;
679
}
680

    
681
static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
682
{
683
    AVStream *st;
684
    int len, ret, i;
685

    
686
    for(;;) {
687
        /* select current input stream component */
688
        st = s->cur_st;
689
        if (st) {
690
            if (!st->parser) {
691
                /* no parsing needed: we just output the packet as is */
692
                /* raw data support */
693
                *pkt = s->cur_pkt;
694
                compute_pkt_fields(s, st, NULL, pkt);
695
                s->cur_st = NULL;
696
                return 0;
697
            } else if (s->cur_len > 0) {
698
                len = av_parser_parse(st->parser, &st->codec, &pkt->data, &pkt->size, 
699
                                      s->cur_ptr, s->cur_len,
700
                                      s->cur_pkt.pts, s->cur_pkt.dts);
701
                s->cur_pkt.pts = AV_NOPTS_VALUE;
702
                s->cur_pkt.dts = AV_NOPTS_VALUE;
703
                /* increment read pointer */
704
                s->cur_ptr += len;
705
                s->cur_len -= len;
706
                
707
                /* return packet if any */
708
                if (pkt->size) {
709
                got_packet:
710
                    pkt->duration = 0;
711
                    pkt->stream_index = st->index;
712
                    pkt->pts = st->parser->pts;
713
                    pkt->dts = st->parser->dts;
714
                    pkt->destruct = av_destruct_packet_nofree;
715
                    compute_pkt_fields(s, st, st->parser, pkt);
716
                    return 0;
717
                }
718
            } else {
719
                /* free packet */
720
                av_free_packet(&s->cur_pkt); 
721
                s->cur_st = NULL;
722
            }
723
        } else {
724
            /* read next packet */
725
            ret = av_read_packet(s, &s->cur_pkt);
726
            if (ret < 0) {
727
                if (ret == -EAGAIN)
728
                    return ret;
729
                /* return the last frames, if any */
730
                for(i = 0; i < s->nb_streams; i++) {
731
                    st = s->streams[i];
732
                    if (st->parser) {
733
                        av_parser_parse(st->parser, &st->codec, 
734
                                        &pkt->data, &pkt->size, 
735
                                        NULL, 0, 
736
                                        AV_NOPTS_VALUE, AV_NOPTS_VALUE);
737
                        if (pkt->size)
738
                            goto got_packet;
739
                    }
740
                }
741
                /* no more packets: really terminates parsing */
742
                return ret;
743
            }
744
            
745
            st = s->streams[s->cur_pkt.stream_index];
746

    
747
            s->cur_st = st;
748
            s->cur_ptr = s->cur_pkt.data;
749
            s->cur_len = s->cur_pkt.size;
750
            if (st->need_parsing && !st->parser) {
751
                st->parser = av_parser_init(st->codec.codec_id);
752
                if (!st->parser) {
753
                    /* no parser available : just output the raw packets */
754
                    st->need_parsing = 0;
755
                }
756
            }
757
        }
758
    }
759
}
760

    
761
/**
762
 * Return the next frame of a stream. The returned packet is valid
763
 * until the next av_read_frame() or until av_close_input_file() and
764
 * must be freed with av_free_packet. For video, the packet contains
765
 * exactly one frame. For audio, it contains an integer number of
766
 * frames if each frame has a known fixed size (e.g. PCM or ADPCM
767
 * data). If the audio frames have a variable size (e.g. MPEG audio),
768
 * then it contains one frame.
769
 * 
770
 * pkt->pts, pkt->dts and pkt->duration are always set to correct
771
 * values in AV_TIME_BASE unit (and guessed if the format cannot
772
 * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
773
 * has B frames, so it is better to rely on pkt->dts if you do not
774
 * decompress the payload.
775
 * 
776
 * Return 0 if OK, < 0 if error or end of file.  
777
 */
778
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
779
{
780
    AVPacketList *pktl;
781

    
782
    pktl = s->packet_buffer;
783
    if (pktl) {
784
        /* read packet from packet buffer, if there is data */
785
        *pkt = pktl->pkt;
786
        s->packet_buffer = pktl->next;
787
        av_free(pktl);
788
        return 0;
789
    } else {
790
        return av_read_frame_internal(s, pkt);
791
    }
792
}
793

    
794
/* XXX: suppress the packet queue */
795
static void flush_packet_queue(AVFormatContext *s)
796
{
797
    AVPacketList *pktl;
798

    
799
    for(;;) {
800
        pktl = s->packet_buffer;
801
        if (!pktl) 
802
            break;
803
        s->packet_buffer = pktl->next;
804
        av_free_packet(&pktl->pkt);
805
        av_free(pktl);
806
    }
807
}
808

    
809
/*******************************************************/
810
/* seek support */
811

    
812
int av_find_default_stream_index(AVFormatContext *s)
813
{
814
    int i;
815
    AVStream *st;
816

    
817
    if (s->nb_streams <= 0)
818
        return -1;
819
    for(i = 0; i < s->nb_streams; i++) {
820
        st = s->streams[i];
821
        if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
822
            return i;
823
        }
824
    }
825
    return 0;
826
}
827

    
828
/* flush the frame reader */
829
static void av_read_frame_flush(AVFormatContext *s)
830
{
831
    AVStream *st;
832
    int i;
833

    
834
    flush_packet_queue(s);
835

    
836
    /* free previous packet */
837
    if (s->cur_st) {
838
        if (s->cur_st->parser)
839
            av_free_packet(&s->cur_pkt);
840
        s->cur_st = NULL;
841
    }
842
    /* fail safe */
843
    s->cur_ptr = NULL;
844
    s->cur_len = 0;
845
    
846
    /* for each stream, reset read state */
847
    for(i = 0; i < s->nb_streams; i++) {
848
        st = s->streams[i];
849
        
850
        if (st->parser) {
851
            av_parser_close(st->parser);
852
            st->parser = NULL;
853
        }
854
        st->last_IP_pts = AV_NOPTS_VALUE;
855
        st->cur_dts = 0; /* we set the current DTS to an unspecified origin */
856
    }
857
}
858

    
859
/**
860
 * add a index entry into a sorted list updateing if it is already there.
861
 * @param timestamp timestamp in the timebase of the given stream
862
 */
863
int av_add_index_entry(AVStream *st,
864
                            int64_t pos, int64_t timestamp, int distance, int flags)
865
{
866
    AVIndexEntry *entries, *ie;
867
    int index;
868
    
869
    entries = av_fast_realloc(st->index_entries,
870
                              &st->index_entries_allocated_size,
871
                              (st->nb_index_entries + 1) * 
872
                              sizeof(AVIndexEntry));
873
    st->index_entries= entries;
874

    
875
    if(st->nb_index_entries){
876
        index= av_index_search_timestamp(st, timestamp);
877
        ie= &entries[index];
878

    
879
        if(ie->timestamp != timestamp){
880
            if(ie->timestamp < timestamp){
881
                index++; //index points to next instead of previous entry, maybe nonexistant
882
                ie= &st->index_entries[index];
883
            }else
884
                assert(index==0);
885
                
886
            if(index != st->nb_index_entries){
887
                assert(index < st->nb_index_entries);
888
                memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
889
            }
890
            st->nb_index_entries++;
891
        }else{
892
            if(ie->pos == pos && distance < ie->min_distance) //dont reduce the distance
893
                distance= ie->min_distance;
894
        }
895
    }else{
896
        index= st->nb_index_entries++;
897
        ie= &entries[index];
898
    }
899
    
900
    ie->pos = pos;
901
    ie->timestamp = timestamp;
902
    ie->min_distance= distance;
903
    ie->flags = flags;
904
    
905
    return index;
906
}
907

    
908
/* build an index for raw streams using a parser */
909
static void av_build_index_raw(AVFormatContext *s)
910
{
911
    AVPacket pkt1, *pkt = &pkt1;
912
    int ret;
913
    AVStream *st;
914

    
915
    st = s->streams[0];
916
    av_read_frame_flush(s);
917
    url_fseek(&s->pb, s->data_offset, SEEK_SET);
918

    
919
    for(;;) {
920
        ret = av_read_frame(s, pkt);
921
        if (ret < 0)
922
            break;
923
        if (pkt->stream_index == 0 && st->parser &&
924
            (pkt->flags & PKT_FLAG_KEY)) {
925
            int64_t dts= av_rescale(pkt->dts, st->time_base.den, AV_TIME_BASE*(int64_t)st->time_base.num);
926
            av_add_index_entry(st, st->parser->frame_offset, dts, 
927
                            0, AVINDEX_KEYFRAME);
928
        }
929
        av_free_packet(pkt);
930
    }
931
}
932

    
933
/* return TRUE if we deal with a raw stream (raw codec data and
934
   parsing needed) */
935
static int is_raw_stream(AVFormatContext *s)
936
{
937
    AVStream *st;
938

    
939
    if (s->nb_streams != 1)
940
        return 0;
941
    st = s->streams[0];
942
    if (!st->need_parsing)
943
        return 0;
944
    return 1;
945
}
946

    
947
/* return the largest index entry whose timestamp is <=
948
   wanted_timestamp */
949
int av_index_search_timestamp(AVStream *st, int wanted_timestamp)
950
{
951
    AVIndexEntry *entries= st->index_entries;
952
    int nb_entries= st->nb_index_entries;
953
    int a, b, m;
954
    int64_t timestamp;
955

    
956
    if (nb_entries <= 0)
957
        return -1;
958
    
959
    a = 0;
960
    b = nb_entries - 1;
961

    
962
    while (a < b) {
963
        m = (a + b + 1) >> 1;
964
        timestamp = entries[m].timestamp;
965
        if (timestamp > wanted_timestamp) {
966
            b = m - 1;
967
        } else {
968
            a = m;
969
        }
970
    }
971
    return a;
972
}
973

    
974
#define DEBUG_SEEK
975

    
976
/**
977
 * Does a binary search using av_index_search_timestamp() and AVCodec.read_timestamp().
978
 * this isnt supposed to be called directly by a user application, but by demuxers
979
 * @param target_ts target timestamp in the time base of the given stream
980
 * @param stream_index stream number
981
 */
982
int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts){
983
    AVInputFormat *avif= s->iformat;
984
    int64_t pos_min, pos_max, pos, pos_limit;
985
    int64_t ts_min, ts_max, ts;
986
    int64_t start_pos;
987
    int index, no_change, i;
988
    AVStream *st;
989

    
990
    if (stream_index < 0)
991
        return -1;
992
    
993
#ifdef DEBUG_SEEK
994
    av_log(s, AV_LOG_DEBUG, "read_seek: %d %lld\n", stream_index, target_ts);
995
#endif
996

    
997
    ts_max=
998
    ts_min= AV_NOPTS_VALUE;
999
    pos_limit= -1; //gcc falsely says it may be uninitalized
1000

    
1001
    st= s->streams[stream_index];
1002
    if(st->index_entries){
1003
        AVIndexEntry *e;
1004

    
1005
        index= av_index_search_timestamp(st, target_ts);
1006
        e= &st->index_entries[index];
1007

    
1008
        if(e->timestamp <= target_ts || e->pos == e->min_distance){
1009
            pos_min= e->pos;
1010
            ts_min= e->timestamp;
1011
#ifdef DEBUG_SEEK
1012
        av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%llx dts_min=%lld\n", 
1013
               pos_min,ts_min);
1014
#endif
1015
        }else{
1016
            assert(index==0);
1017
        }
1018
        index++;
1019
        if(index < st->nb_index_entries){
1020
            e= &st->index_entries[index];
1021
            assert(e->timestamp >= target_ts);
1022
            pos_max= e->pos;
1023
            ts_max= e->timestamp;
1024
            pos_limit= pos_max - e->min_distance;
1025
#ifdef DEBUG_SEEK
1026
        av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%llx pos_limit=0x%llx dts_max=%lld\n", 
1027
               pos_max,pos_limit, ts_max);
1028
#endif
1029
        }
1030
    }
1031

    
1032
    if(ts_min == AV_NOPTS_VALUE){
1033
        pos_min = s->data_offset;
1034
        ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1035
        if (ts_min == AV_NOPTS_VALUE)
1036
            return -1;
1037
    }
1038

    
1039
    if(ts_max == AV_NOPTS_VALUE){
1040
        int step= 1024;
1041
        pos_max = url_filesize(url_fileno(&s->pb)) - 1;
1042
        do{
1043
            pos_max -= step;
1044
            ts_max = avif->read_timestamp(s, stream_index, &pos_max, pos_max + step);
1045
            step += step;
1046
        }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1047
        if (ts_max == AV_NOPTS_VALUE)
1048
            return -1;
1049
        
1050
        for(;;){
1051
            int64_t tmp_pos= pos_max + 1;
1052
            int64_t tmp_ts= avif->read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1053
            if(tmp_ts == AV_NOPTS_VALUE)
1054
                break;
1055
            ts_max= tmp_ts;
1056
            pos_max= tmp_pos;
1057
        }
1058
        pos_limit= pos_max;
1059
    }
1060

    
1061
    no_change=0;
1062
    while (pos_min < pos_limit) {
1063
#ifdef DEBUG_SEEK
1064
        av_log(s, AV_LOG_DEBUG, "pos_min=0x%llx pos_max=0x%llx dts_min=%lld dts_max=%lld\n", 
1065
               pos_min, pos_max,
1066
               ts_min, ts_max);
1067
#endif
1068
        assert(pos_limit <= pos_max);
1069

    
1070
        if(no_change==0){
1071
            int64_t approximate_keyframe_distance= pos_max - pos_limit;
1072
            // interpolate position (better than dichotomy)
1073
            pos = (int64_t)((double)(pos_max - pos_min) *
1074
                            (double)(target_ts - ts_min) /
1075
                            (double)(ts_max - ts_min)) + pos_min - approximate_keyframe_distance;
1076
        }else if(no_change==1){
1077
            // bisection, if interpolation failed to change min or max pos last time
1078
            pos = (pos_min + pos_limit)>>1;
1079
        }else{
1080
            // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
1081
            pos=pos_min;
1082
        }
1083
        if(pos <= pos_min)
1084
            pos= pos_min + 1;
1085
        else if(pos > pos_limit)
1086
            pos= pos_limit;
1087
        start_pos= pos;
1088

    
1089
        ts = avif->read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1090
        if(pos == pos_max)
1091
            no_change++;
1092
        else
1093
            no_change=0;
1094
#ifdef DEBUG_SEEK
1095
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);
1096
#endif
1097
        assert(ts != AV_NOPTS_VALUE);
1098
        if (target_ts < ts) {
1099
            pos_limit = start_pos - 1;
1100
            pos_max = pos;
1101
            ts_max = ts;
1102
        } else {
1103
            pos_min = pos;
1104
            ts_min = ts;
1105
            /* check if we are lucky */
1106
            if (target_ts == ts)
1107
                break;
1108
        }
1109
    }
1110
    
1111
    pos = pos_min;
1112
#ifdef DEBUG_SEEK
1113
    pos_min = pos;
1114
    ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1115
    pos_min++;
1116
    ts_max = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1117
    av_log(s, AV_LOG_DEBUG, "pos=0x%llx %lld<=%lld<=%lld\n", 
1118
           pos, ts_min, target_ts, ts_max);
1119
#endif
1120
    /* do the seek */
1121
    url_fseek(&s->pb, pos, SEEK_SET);
1122

    
1123
    ts= av_rescale(ts_min, AV_TIME_BASE*(int64_t)st->time_base.num, st->time_base.den);
1124
    for(i = 0; i < s->nb_streams; i++) {
1125
        st = s->streams[i];
1126

    
1127
        st->cur_dts = av_rescale(ts, st->time_base.den, AV_TIME_BASE*(int64_t)st->time_base.num);
1128
    }
1129

    
1130
    return 0;
1131
}
1132

    
1133
static int av_seek_frame_generic(AVFormatContext *s, 
1134
                                 int stream_index, int64_t timestamp)
1135
{
1136
    int index, i;
1137
    AVStream *st;
1138
    AVIndexEntry *ie;
1139

    
1140
    if (!s->index_built) {
1141
        if (is_raw_stream(s)) {
1142
            av_build_index_raw(s);
1143
        } else {
1144
            return -1;
1145
        }
1146
        s->index_built = 1;
1147
    }
1148

    
1149
    st = s->streams[stream_index];
1150
    index = av_index_search_timestamp(st, timestamp);
1151
    if (index < 0)
1152
        return -1;
1153

    
1154
    /* now we have found the index, we can seek */
1155
    ie = &st->index_entries[index];
1156
    av_read_frame_flush(s);
1157
    url_fseek(&s->pb, ie->pos, SEEK_SET);
1158
    
1159
    timestamp= av_rescale(ie->timestamp, AV_TIME_BASE*(int64_t)st->time_base.num, st->time_base.den);
1160
    for(i = 0; i < s->nb_streams; i++) {
1161
        st = s->streams[i];
1162

    
1163
        st->cur_dts = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE*(int64_t)st->time_base.num);
1164
    }
1165

    
1166
    return 0;
1167
}
1168

    
1169
/**
1170
 * Seek to the key frame just before the frame at timestamp
1171
 * 'timestamp' in 'stream_index'.
1172
 * @param stream_index If stream_index is (-1), a default
1173
 * stream is selected
1174
 * @param timestamp timestamp in AV_TIME_BASE units
1175
 * @return >= 0 on success
1176
 */
1177
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp)
1178
{
1179
    int ret;
1180
    AVStream *st;
1181
    
1182
    av_read_frame_flush(s);
1183
    
1184
    if(stream_index < 0){
1185
        stream_index= av_find_default_stream_index(s);
1186
        if(stream_index < 0)
1187
            return -1;
1188
    }
1189
    st= s->streams[stream_index];
1190

    
1191
    timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1192

    
1193
    /* first, we try the format specific seek */
1194
    if (s->iformat->read_seek)
1195
        ret = s->iformat->read_seek(s, stream_index, timestamp);
1196
    else
1197
        ret = -1;
1198
    if (ret >= 0) {
1199
        return 0;
1200
    }
1201

    
1202
    if(s->iformat->read_timestamp)
1203
        return av_seek_frame_binary(s, stream_index, timestamp);
1204
    else
1205
        return av_seek_frame_generic(s, stream_index, timestamp);
1206
}
1207

    
1208
/*******************************************************/
1209

    
1210
/* return TRUE if the stream has accurate timings for at least one component */
1211
static int av_has_timings(AVFormatContext *ic)
1212
{
1213
    int i;
1214
    AVStream *st;
1215

    
1216
    for(i = 0;i < ic->nb_streams; i++) {
1217
        st = ic->streams[i];
1218
        if (st->start_time != AV_NOPTS_VALUE &&
1219
            st->duration != AV_NOPTS_VALUE)
1220
            return 1;
1221
    }
1222
    return 0;
1223
}
1224

    
1225
/* estimate the stream timings from the one of each components. Also
1226
   compute the global bitrate if possible */
1227
static void av_update_stream_timings(AVFormatContext *ic)
1228
{
1229
    int64_t start_time, end_time, end_time1;
1230
    int i;
1231
    AVStream *st;
1232

    
1233
    start_time = MAXINT64;
1234
    end_time = MININT64;
1235
    for(i = 0;i < ic->nb_streams; i++) {
1236
        st = ic->streams[i];
1237
        if (st->start_time != AV_NOPTS_VALUE) {
1238
            if (st->start_time < start_time)
1239
                start_time = st->start_time;
1240
            if (st->duration != AV_NOPTS_VALUE) {
1241
                end_time1 = st->start_time + st->duration;
1242
                if (end_time1 > end_time)
1243
                    end_time = end_time1;
1244
            }
1245
        }
1246
    }
1247
    if (start_time != MAXINT64) {
1248
        ic->start_time = start_time;
1249
        if (end_time != MAXINT64) {
1250
            ic->duration = end_time - start_time;
1251
            if (ic->file_size > 0) {
1252
                /* compute the bit rate */
1253
                ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE / 
1254
                    (double)ic->duration;
1255
            }
1256
        }
1257
    }
1258

    
1259
}
1260

    
1261
static void fill_all_stream_timings(AVFormatContext *ic)
1262
{
1263
    int i;
1264
    AVStream *st;
1265

    
1266
    av_update_stream_timings(ic);
1267
    for(i = 0;i < ic->nb_streams; i++) {
1268
        st = ic->streams[i];
1269
        if (st->start_time == AV_NOPTS_VALUE) {
1270
            st->start_time = ic->start_time;
1271
            st->duration = ic->duration;
1272
        }
1273
    }
1274
}
1275

    
1276
static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1277
{
1278
    int64_t filesize, duration;
1279
    int bit_rate, i;
1280
    AVStream *st;
1281

    
1282
    /* if bit_rate is already set, we believe it */
1283
    if (ic->bit_rate == 0) {
1284
        bit_rate = 0;
1285
        for(i=0;i<ic->nb_streams;i++) {
1286
            st = ic->streams[i];
1287
            bit_rate += st->codec.bit_rate;
1288
        }
1289
        ic->bit_rate = bit_rate;
1290
    }
1291

    
1292
    /* if duration is already set, we believe it */
1293
    if (ic->duration == AV_NOPTS_VALUE && 
1294
        ic->bit_rate != 0 && 
1295
        ic->file_size != 0)  {
1296
        filesize = ic->file_size;
1297
        if (filesize > 0) {
1298
            duration = (int64_t)((8 * AV_TIME_BASE * (double)filesize) / (double)ic->bit_rate);
1299
            for(i = 0; i < ic->nb_streams; i++) {
1300
                st = ic->streams[i];
1301
                if (st->start_time == AV_NOPTS_VALUE ||
1302
                    st->duration == AV_NOPTS_VALUE) {
1303
                    st->start_time = 0;
1304
                    st->duration = duration;
1305
                }
1306
            }
1307
        }
1308
    }
1309
}
1310

    
1311
#define DURATION_MAX_READ_SIZE 250000
1312

    
1313
/* only usable for MPEG-PS streams */
1314
static void av_estimate_timings_from_pts(AVFormatContext *ic)
1315
{
1316
    AVPacket pkt1, *pkt = &pkt1;
1317
    AVStream *st;
1318
    int read_size, i, ret;
1319
    int64_t start_time, end_time, end_time1;
1320
    int64_t filesize, offset, duration;
1321
    
1322
    /* free previous packet */
1323
    if (ic->cur_st && ic->cur_st->parser)
1324
        av_free_packet(&ic->cur_pkt); 
1325
    ic->cur_st = NULL;
1326

    
1327
    /* flush packet queue */
1328
    flush_packet_queue(ic);
1329
    
1330

    
1331
    /* we read the first packets to get the first PTS (not fully
1332
       accurate, but it is enough now) */
1333
    url_fseek(&ic->pb, 0, SEEK_SET);
1334
    read_size = 0;
1335
    for(;;) {
1336
        if (read_size >= DURATION_MAX_READ_SIZE)
1337
            break;
1338
        /* if all info is available, we can stop */
1339
        for(i = 0;i < ic->nb_streams; i++) {
1340
            st = ic->streams[i];
1341
            if (st->start_time == AV_NOPTS_VALUE)
1342
                break;
1343
        }
1344
        if (i == ic->nb_streams)
1345
            break;
1346

    
1347
        ret = av_read_packet(ic, pkt);
1348
        if (ret != 0)
1349
            break;
1350
        read_size += pkt->size;
1351
        st = ic->streams[pkt->stream_index];
1352
        if (pkt->pts != AV_NOPTS_VALUE) {
1353
            if (st->start_time == AV_NOPTS_VALUE)
1354
                st->start_time = av_rescale(pkt->pts, st->time_base.num * (int64_t)AV_TIME_BASE, st->time_base.den);
1355
        }
1356
        av_free_packet(pkt);
1357
    }
1358

    
1359
    /* we compute the minimum start_time and use it as default */
1360
    start_time = MAXINT64;
1361
    for(i = 0; i < ic->nb_streams; i++) {
1362
        st = ic->streams[i];
1363
        if (st->start_time != AV_NOPTS_VALUE &&
1364
            st->start_time < start_time)
1365
            start_time = st->start_time;
1366
    }
1367
    if (start_time != MAXINT64)
1368
        ic->start_time = start_time;
1369
    
1370
    /* estimate the end time (duration) */
1371
    /* XXX: may need to support wrapping */
1372
    filesize = ic->file_size;
1373
    offset = filesize - DURATION_MAX_READ_SIZE;
1374
    if (offset < 0)
1375
        offset = 0;
1376

    
1377
    url_fseek(&ic->pb, offset, SEEK_SET);
1378
    read_size = 0;
1379
    for(;;) {
1380
        if (read_size >= DURATION_MAX_READ_SIZE)
1381
            break;
1382
        /* if all info is available, we can stop */
1383
        for(i = 0;i < ic->nb_streams; i++) {
1384
            st = ic->streams[i];
1385
            if (st->duration == AV_NOPTS_VALUE)
1386
                break;
1387
        }
1388
        if (i == ic->nb_streams)
1389
            break;
1390
        
1391
        ret = av_read_packet(ic, pkt);
1392
        if (ret != 0)
1393
            break;
1394
        read_size += pkt->size;
1395
        st = ic->streams[pkt->stream_index];
1396
        if (pkt->pts != AV_NOPTS_VALUE) {
1397
            end_time = av_rescale(pkt->pts, st->time_base.num * (int64_t)AV_TIME_BASE, st->time_base.den);
1398
            duration = end_time - st->start_time;
1399
            if (duration > 0) {
1400
                if (st->duration == AV_NOPTS_VALUE ||
1401
                    st->duration < duration)
1402
                    st->duration = duration;
1403
            }
1404
        }
1405
        av_free_packet(pkt);
1406
    }
1407
    
1408
    /* estimate total duration */
1409
    end_time = MININT64;
1410
    for(i = 0;i < ic->nb_streams; i++) {
1411
        st = ic->streams[i];
1412
        if (st->duration != AV_NOPTS_VALUE) {
1413
            end_time1 = st->start_time + st->duration;
1414
            if (end_time1 > end_time)
1415
                end_time = end_time1;
1416
        }
1417
    }
1418
    
1419
    /* update start_time (new stream may have been created, so we do
1420
       it at the end */
1421
    if (ic->start_time != AV_NOPTS_VALUE) {
1422
        for(i = 0; i < ic->nb_streams; i++) {
1423
            st = ic->streams[i];
1424
            if (st->start_time == AV_NOPTS_VALUE)
1425
                st->start_time = ic->start_time;
1426
        }
1427
    }
1428

    
1429
    if (end_time != MININT64) {
1430
        /* put dummy values for duration if needed */
1431
        for(i = 0;i < ic->nb_streams; i++) {
1432
            st = ic->streams[i];
1433
            if (st->duration == AV_NOPTS_VALUE && 
1434
                st->start_time != AV_NOPTS_VALUE)
1435
                st->duration = end_time - st->start_time;
1436
        }
1437
        ic->duration = end_time - ic->start_time;
1438
    }
1439

    
1440
    url_fseek(&ic->pb, 0, SEEK_SET);
1441
}
1442

    
1443
static void av_estimate_timings(AVFormatContext *ic)
1444
{
1445
    URLContext *h;
1446
    int64_t file_size;
1447

    
1448
    /* get the file size, if possible */
1449
    if (ic->iformat->flags & AVFMT_NOFILE) {
1450
        file_size = 0;
1451
    } else {
1452
        h = url_fileno(&ic->pb);
1453
        file_size = url_filesize(h);
1454
        if (file_size < 0)
1455
            file_size = 0;
1456
    }
1457
    ic->file_size = file_size;
1458

    
1459
    if (ic->iformat == &mpegps_demux) {
1460
        /* get accurate estimate from the PTSes */
1461
        av_estimate_timings_from_pts(ic);
1462
    } else if (av_has_timings(ic)) {
1463
        /* at least one components has timings - we use them for all
1464
           the components */
1465
        fill_all_stream_timings(ic);
1466
    } else {
1467
        /* less precise: use bit rate info */
1468
        av_estimate_timings_from_bit_rate(ic);
1469
    }
1470
    av_update_stream_timings(ic);
1471

    
1472
#if 0
1473
    {
1474
        int i;
1475
        AVStream *st;
1476
        for(i = 0;i < ic->nb_streams; i++) {
1477
            st = ic->streams[i];
1478
        printf("%d: start_time: %0.3f duration: %0.3f\n", 
1479
               i, (double)st->start_time / AV_TIME_BASE, 
1480
               (double)st->duration / AV_TIME_BASE);
1481
        }
1482
        printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n", 
1483
               (double)ic->start_time / AV_TIME_BASE, 
1484
               (double)ic->duration / AV_TIME_BASE,
1485
               ic->bit_rate / 1000);
1486
    }
1487
#endif
1488
}
1489

    
1490
static int has_codec_parameters(AVCodecContext *enc)
1491
{
1492
    int val;
1493
    switch(enc->codec_type) {
1494
    case CODEC_TYPE_AUDIO:
1495
        val = enc->sample_rate;
1496
        break;
1497
    case CODEC_TYPE_VIDEO:
1498
        val = enc->width;
1499
        break;
1500
    default:
1501
        val = 1;
1502
        break;
1503
    }
1504
    return (val != 0);
1505
}
1506

    
1507
static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1508
{
1509
    int16_t *samples;
1510
    AVCodec *codec;
1511
    int got_picture, ret;
1512
    AVFrame picture;
1513
    
1514
    codec = avcodec_find_decoder(st->codec.codec_id);
1515
    if (!codec)
1516
        return -1;
1517
    ret = avcodec_open(&st->codec, codec);
1518
    if (ret < 0)
1519
        return ret;
1520
    switch(st->codec.codec_type) {
1521
    case CODEC_TYPE_VIDEO:
1522
        ret = avcodec_decode_video(&st->codec, &picture, 
1523
                                   &got_picture, (uint8_t *)data, size);
1524
        break;
1525
    case CODEC_TYPE_AUDIO:
1526
        samples = av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
1527
        if (!samples)
1528
            goto fail;
1529
        ret = avcodec_decode_audio(&st->codec, samples, 
1530
                                   &got_picture, (uint8_t *)data, size);
1531
        av_free(samples);
1532
        break;
1533
    default:
1534
        break;
1535
    }
1536
 fail:
1537
    avcodec_close(&st->codec);
1538
    return ret;
1539
}
1540

    
1541
/* absolute maximum size we read until we abort */
1542
#define MAX_READ_SIZE        5000000
1543

    
1544
/* maximum duration until we stop analysing the stream */
1545
#define MAX_STREAM_DURATION  ((int)(AV_TIME_BASE * 1.0))
1546

    
1547
/**
1548
 * Read the beginning of a media file to get stream information. This
1549
 * is useful for file formats with no headers such as MPEG. This
1550
 * function also compute the real frame rate in case of mpeg2 repeat
1551
 * frame mode.
1552
 *
1553
 * @param ic media file handle
1554
 * @return >=0 if OK. AVERROR_xxx if error.  
1555
 */
1556
int av_find_stream_info(AVFormatContext *ic)
1557
{
1558
    int i, count, ret, read_size;
1559
    AVStream *st;
1560
    AVPacket pkt1, *pkt;
1561
    AVPacketList *pktl=NULL, **ppktl;
1562

    
1563
    count = 0;
1564
    read_size = 0;
1565
    ppktl = &ic->packet_buffer;
1566
    for(;;) {
1567
        /* check if one codec still needs to be handled */
1568
        for(i=0;i<ic->nb_streams;i++) {
1569
            st = ic->streams[i];
1570
            if (!has_codec_parameters(&st->codec))
1571
                break;
1572
        }
1573
        if (i == ic->nb_streams) {
1574
            /* NOTE: if the format has no header, then we need to read
1575
               some packets to get most of the streams, so we cannot
1576
               stop here */
1577
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
1578
                /* if we found the info for all the codecs, we can stop */
1579
                ret = count;
1580
                break;
1581
            }
1582
        } else {
1583
            /* we did not get all the codec info, but we read too much data */
1584
            if (read_size >= MAX_READ_SIZE) {
1585
                ret = count;
1586
                break;
1587
            }
1588
        }
1589

    
1590
        /* NOTE: a new stream can be added there if no header in file
1591
           (AVFMTCTX_NOHEADER) */
1592
        ret = av_read_frame_internal(ic, &pkt1);
1593
        if (ret < 0) {
1594
            /* EOF or error */
1595
            ret = -1; /* we could not have all the codec parameters before EOF */
1596
            if ((ic->ctx_flags & AVFMTCTX_NOHEADER) &&
1597
                i == ic->nb_streams)
1598
                ret = 0;
1599
            break;
1600
        }
1601

    
1602
        pktl = av_mallocz(sizeof(AVPacketList));
1603
        if (!pktl) {
1604
            ret = AVERROR_NOMEM;
1605
            break;
1606
        }
1607

    
1608
        /* add the packet in the buffered packet list */
1609
        *ppktl = pktl;
1610
        ppktl = &pktl->next;
1611

    
1612
        pkt = &pktl->pkt;
1613
        *pkt = pkt1;
1614
        
1615
        /* duplicate the packet */
1616
        if (av_dup_packet(pkt) < 0) {
1617
                ret = AVERROR_NOMEM;
1618
                break;
1619
        }
1620

    
1621
        read_size += pkt->size;
1622

    
1623
        st = ic->streams[pkt->stream_index];
1624
        st->codec_info_duration += pkt->duration;
1625
        if (pkt->duration != 0)
1626
            st->codec_info_nb_frames++;
1627

    
1628
        /* if still no information, we try to open the codec and to
1629
           decompress the frame. We try to avoid that in most cases as
1630
           it takes longer and uses more memory. For MPEG4, we need to
1631
           decompress for Quicktime. */
1632
        if (!has_codec_parameters(&st->codec) &&
1633
            (st->codec.codec_id == CODEC_ID_FLV1 ||
1634
             st->codec.codec_id == CODEC_ID_H264 ||
1635
             st->codec.codec_id == CODEC_ID_H263 ||
1636
             st->codec.codec_id == CODEC_ID_VORBIS ||
1637
             (st->codec.codec_id == CODEC_ID_MPEG4 && !st->need_parsing)))
1638
            try_decode_frame(st, pkt->data, pkt->size);
1639
        
1640
        if (st->codec_info_duration >= MAX_STREAM_DURATION) {
1641
            break;
1642
        }
1643
        count++;
1644
    }
1645

    
1646
    /* set real frame rate info */
1647
    for(i=0;i<ic->nb_streams;i++) {
1648
        st = ic->streams[i];
1649
        if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
1650
            /* compute the real frame rate for telecine */
1651
            if ((st->codec.codec_id == CODEC_ID_MPEG1VIDEO ||
1652
                 st->codec.codec_id == CODEC_ID_MPEG2VIDEO) &&
1653
                st->codec.sub_id == 2) {
1654
                if (st->codec_info_nb_frames >= 20) {
1655
                    float coded_frame_rate, est_frame_rate;
1656
                    est_frame_rate = ((double)st->codec_info_nb_frames * AV_TIME_BASE) / 
1657
                        (double)st->codec_info_duration ;
1658
                    coded_frame_rate = (double)st->codec.frame_rate /
1659
                        (double)st->codec.frame_rate_base;
1660
#if 0
1661
                    printf("telecine: coded_frame_rate=%0.3f est_frame_rate=%0.3f\n", 
1662
                           coded_frame_rate, est_frame_rate);
1663
#endif
1664
                    /* if we detect that it could be a telecine, we
1665
                       signal it. It would be better to do it at a
1666
                       higher level as it can change in a film */
1667
                    if (coded_frame_rate >= 24.97 && 
1668
                        (est_frame_rate >= 23.5 && est_frame_rate < 24.5)) {
1669
                        st->r_frame_rate = 24024;
1670
                        st->r_frame_rate_base = 1001;
1671
                    }
1672
                }
1673
            }
1674
            /* if no real frame rate, use the codec one */
1675
            if (!st->r_frame_rate){
1676
                st->r_frame_rate      = st->codec.frame_rate;
1677
                st->r_frame_rate_base = st->codec.frame_rate_base;
1678
            }
1679
        }
1680
    }
1681

    
1682
    av_estimate_timings(ic);
1683
#if 0
1684
    /* correct DTS for b frame streams with no timestamps */
1685
    for(i=0;i<ic->nb_streams;i++) {
1686
        st = ic->streams[i];
1687
        if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
1688
            if(b-frames){
1689
                ppktl = &ic->packet_buffer;
1690
                while(ppkt1){
1691
                    if(ppkt1->stream_index != i)
1692
                        continue;
1693
                    if(ppkt1->pkt->dts < 0)
1694
                        break;
1695
                    if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
1696
                        break;
1697
                    ppkt1->pkt->dts -= delta;
1698
                    ppkt1= ppkt1->next;
1699
                }
1700
                if(ppkt1)
1701
                    continue;
1702
                st->cur_dts -= delta;
1703
            }
1704
        }
1705
    }
1706
#endif
1707
    return ret;
1708
}
1709

    
1710
/*******************************************************/
1711

    
1712
/**
1713
 * start playing a network based stream (e.g. RTSP stream) at the
1714
 * current position 
1715
 */
1716
int av_read_play(AVFormatContext *s)
1717
{
1718
    if (!s->iformat->read_play)
1719
        return AVERROR_NOTSUPP;
1720
    return s->iformat->read_play(s);
1721
}
1722

    
1723
/**
1724
 * pause a network based stream (e.g. RTSP stream). Use av_read_play()
1725
 * to resume it.
1726
 */
1727
int av_read_pause(AVFormatContext *s)
1728
{
1729
    if (!s->iformat->read_pause)
1730
        return AVERROR_NOTSUPP;
1731
    return s->iformat->read_pause(s);
1732
}
1733

    
1734
/**
1735
 * Close a media file (but not its codecs)
1736
 *
1737
 * @param s media file handle
1738
 */
1739
void av_close_input_file(AVFormatContext *s)
1740
{
1741
    int i, must_open_file;
1742
    AVStream *st;
1743

    
1744
    /* free previous packet */
1745
    if (s->cur_st && s->cur_st->parser)
1746
        av_free_packet(&s->cur_pkt); 
1747

    
1748
    if (s->iformat->read_close)
1749
        s->iformat->read_close(s);
1750
    for(i=0;i<s->nb_streams;i++) {
1751
        /* free all data in a stream component */
1752
        st = s->streams[i];
1753
        if (st->parser) {
1754
            av_parser_close(st->parser);
1755
        }
1756
        av_free(st->index_entries);
1757
        av_free(st);
1758
    }
1759
    flush_packet_queue(s);
1760
    must_open_file = 1;
1761
    if (s->iformat->flags & AVFMT_NOFILE) {
1762
        must_open_file = 0;
1763
    }
1764
    if (must_open_file) {
1765
        url_fclose(&s->pb);
1766
    }
1767
    av_freep(&s->priv_data);
1768
    av_free(s);
1769
}
1770

    
1771
/**
1772
 * Add a new stream to a media file. Can only be called in the
1773
 * read_header function. If the flag AVFMTCTX_NOHEADER is in the
1774
 * format context, then new streams can be added in read_packet too.
1775
 *
1776
 *
1777
 * @param s media file handle
1778
 * @param id file format dependent stream id 
1779
 */
1780
AVStream *av_new_stream(AVFormatContext *s, int id)
1781
{
1782
    AVStream *st;
1783

    
1784
    if (s->nb_streams >= MAX_STREAMS)
1785
        return NULL;
1786

    
1787
    st = av_mallocz(sizeof(AVStream));
1788
    if (!st)
1789
        return NULL;
1790
    avcodec_get_context_defaults(&st->codec);
1791
    if (s->iformat) {
1792
        /* no default bitrate if decoding */
1793
        st->codec.bit_rate = 0;
1794
    }
1795
    st->index = s->nb_streams;
1796
    st->id = id;
1797
    st->start_time = AV_NOPTS_VALUE;
1798
    st->duration = AV_NOPTS_VALUE;
1799
    st->cur_dts = AV_NOPTS_VALUE;
1800

    
1801
    /* default pts settings is MPEG like */
1802
    av_set_pts_info(st, 33, 1, 90000);
1803
    st->last_IP_pts = AV_NOPTS_VALUE;
1804

    
1805
    s->streams[s->nb_streams++] = st;
1806
    return st;
1807
}
1808

    
1809
/************************************************************/
1810
/* output media file */
1811

    
1812
int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
1813
{
1814
    int ret;
1815
    
1816
    if (s->oformat->priv_data_size > 0) {
1817
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
1818
        if (!s->priv_data)
1819
            return AVERROR_NOMEM;
1820
    } else
1821
        s->priv_data = NULL;
1822
        
1823
    if (s->oformat->set_parameters) {
1824
        ret = s->oformat->set_parameters(s, ap);
1825
        if (ret < 0)
1826
            return ret;
1827
    }
1828
    return 0;
1829
}
1830

    
1831
/**
1832
 * allocate the stream private data and write the stream header to an
1833
 * output media file
1834
 *
1835
 * @param s media file handle
1836
 * @return 0 if OK. AVERROR_xxx if error.  
1837
 */
1838
int av_write_header(AVFormatContext *s)
1839
{
1840
    int ret, i;
1841
    AVStream *st;
1842

    
1843
    ret = s->oformat->write_header(s);
1844
    if (ret < 0)
1845
        return ret;
1846

    
1847
    /* init PTS generation */
1848
    for(i=0;i<s->nb_streams;i++) {
1849
        st = s->streams[i];
1850

    
1851
        switch (st->codec.codec_type) {
1852
        case CODEC_TYPE_AUDIO:
1853
            av_frac_init(&st->pts, 0, 0, 
1854
                         (int64_t)st->time_base.num * st->codec.sample_rate);
1855
            break;
1856
        case CODEC_TYPE_VIDEO:
1857
            av_frac_init(&st->pts, 0, 0, 
1858
                         (int64_t)st->time_base.num * st->codec.frame_rate);
1859
            break;
1860
        default:
1861
            break;
1862
        }
1863
    }
1864
    return 0;
1865
}
1866

    
1867
//FIXME merge with compute_pkt_fields
1868
static void compute_pkt_fields2(AVStream *st, AVPacket *pkt){
1869
    int b_frames = FFMAX(st->codec.has_b_frames, st->codec.max_b_frames);
1870
    int num, den, frame_size;
1871

    
1872
//    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);
1873
    
1874
/*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
1875
        return -1;*/
1876
            
1877
    if(pkt->pts != AV_NOPTS_VALUE)
1878
        pkt->pts = av_rescale(pkt->pts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1879
    if(pkt->dts != AV_NOPTS_VALUE)
1880
        pkt->dts = av_rescale(pkt->dts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1881

    
1882
    /* duration field */
1883
    pkt->duration = av_rescale(pkt->duration, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1884
    if (pkt->duration == 0) {
1885
        compute_frame_duration(&num, &den, st, NULL, pkt);
1886
        if (den && num) {
1887
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
1888
        }
1889
    }
1890

    
1891
    //XXX/FIXME this is a temporary hack until all encoders output pts
1892
    if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !b_frames){
1893
        pkt->dts=
1894
//        pkt->pts= st->cur_dts;
1895
        pkt->pts= st->pts.val;
1896
    }
1897

    
1898
    //calculate dts from pts    
1899
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
1900
        if(b_frames){
1901
            if(st->last_IP_pts == AV_NOPTS_VALUE){
1902
                st->last_IP_pts= -pkt->duration;
1903
            }
1904
            if(st->last_IP_pts < pkt->pts){
1905
                pkt->dts= st->last_IP_pts;
1906
                st->last_IP_pts= pkt->pts;
1907
            }else
1908
                pkt->dts= pkt->pts;
1909
        }else
1910
            pkt->dts= pkt->pts;
1911
    }
1912
    
1913
//    av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%lld dts2:%lld\n", pkt->pts, pkt->dts);
1914
    st->cur_dts= pkt->dts;
1915
    st->pts.val= pkt->dts;
1916

    
1917
    /* update pts */
1918
    switch (st->codec.codec_type) {
1919
    case CODEC_TYPE_AUDIO:
1920
        frame_size = get_audio_frame_size(&st->codec, pkt->size);
1921

    
1922
        /* HACK/FIXME, we skip the initial 0-size packets as they are most likely equal to the encoder delay,
1923
           but it would be better if we had the real timestamps from the encoder */
1924
        if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
1925
            av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
1926
        }
1927
        break;
1928
    case CODEC_TYPE_VIDEO:
1929
        av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec.frame_rate_base);
1930
        break;
1931
    default:
1932
        break;
1933
    }
1934
}
1935

    
1936
static void truncate_ts(AVStream *st, AVPacket *pkt){
1937
    int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
1938
    
1939
    if(pkt->dts < 0)
1940
        pkt->dts= 0;  //this happens for low_delay=0 and b frames, FIXME, needs further invstigation about what we should do here
1941
    
1942
    pkt->pts &= pts_mask;
1943
    pkt->dts &= pts_mask;
1944
}
1945

    
1946
/**
1947
 * Write a packet to an output media file. The packet shall contain
1948
 * one audio or video frame.
1949
 *
1950
 * @param s media file handle
1951
 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
1952
 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
1953
 */
1954
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
1955
{
1956
    compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
1957
    
1958
    truncate_ts(s->streams[pkt->stream_index], pkt);
1959

    
1960
    return s->oformat->write_packet(s, pkt);
1961
}
1962

    
1963
/**
1964
 * Writes a packet to an output media file ensuring correct interleaving. 
1965
 * The packet shall contain one audio or video frame.
1966
 * If the packets are already correctly interleaved the application should
1967
 * call av_write_frame() instead as its slightly faster, its also important
1968
 * to keep in mind that non interlaved input will need huge amounts
1969
 * of memory to interleave with this, so its prefereable to interleave at the
1970
 * demuxer level
1971
 *
1972
 * @param s media file handle
1973
 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
1974
 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
1975
 */
1976
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
1977
    AVPacketList *pktl, **next_point, *this_pktl;
1978
    int stream_count=0;
1979
    int streams[MAX_STREAMS];
1980
    AVStream *st= s->streams[ pkt->stream_index];
1981

    
1982
    compute_pkt_fields2(st, pkt);
1983

    
1984
    if(pkt->dts == AV_NOPTS_VALUE)
1985
        return -1;
1986
        
1987
    assert(pkt->destruct != av_destruct_packet); //FIXME
1988

    
1989
    this_pktl = av_mallocz(sizeof(AVPacketList));
1990
    this_pktl->pkt= *pkt;
1991
    av_dup_packet(&this_pktl->pkt);
1992

    
1993
    next_point = &s->packet_buffer;
1994
    while(*next_point){
1995
        AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
1996
        int64_t left=  st2->time_base.num * (int64_t)st ->time_base.den;
1997
        int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
1998
        if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
1999
            break;
2000
        next_point= &(*next_point)->next;
2001
    }
2002
    this_pktl->next= *next_point;
2003
    *next_point= this_pktl;
2004
    
2005
    memset(streams, 0, sizeof(streams));
2006
    pktl= s->packet_buffer;
2007
    while(pktl){
2008
//av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
2009
        if(streams[ pktl->pkt.stream_index ] == 0)
2010
            stream_count++;
2011
        streams[ pktl->pkt.stream_index ]++;
2012
        pktl= pktl->next;
2013
    }
2014

    
2015
    while(s->nb_streams == stream_count){
2016
        int ret;
2017

    
2018
        pktl= s->packet_buffer;
2019
//av_log(s, AV_LOG_DEBUG, "write st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
2020
        truncate_ts(s->streams[pktl->pkt.stream_index], &pktl->pkt);
2021
        ret= s->oformat->write_packet(s, &pktl->pkt);
2022
        
2023
        s->packet_buffer= pktl->next;        
2024
        if((--streams[ pktl->pkt.stream_index ]) == 0)
2025
            stream_count--;
2026

    
2027
        av_free_packet(&pktl->pkt);
2028
        av_freep(&pktl);
2029
        
2030
        if(ret<0)
2031
            return ret;
2032
    }
2033
    return 0;
2034
}
2035

    
2036
/**
2037
 * write the stream trailer to an output media file and and free the
2038
 * file private data.
2039
 *
2040
 * @param s media file handle
2041
 * @return 0 if OK. AVERROR_xxx if error.  */
2042
int av_write_trailer(AVFormatContext *s)
2043
{
2044
    int ret;
2045
    
2046
    while(s->packet_buffer){
2047
        int ret;
2048
        AVPacketList *pktl= s->packet_buffer;
2049

    
2050
//av_log(s, AV_LOG_DEBUG, "write_trailer st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
2051
        truncate_ts(s->streams[pktl->pkt.stream_index], &pktl->pkt);
2052
        ret= s->oformat->write_packet(s, &pktl->pkt);
2053
        
2054
        s->packet_buffer= pktl->next;        
2055

    
2056
        av_free_packet(&pktl->pkt);
2057
        av_freep(&pktl);
2058
        
2059
        if(ret<0)
2060
            return ret;
2061
    }
2062

    
2063
    ret = s->oformat->write_trailer(s);
2064
    av_freep(&s->priv_data);
2065
    return ret;
2066
}
2067

    
2068
/* "user interface" functions */
2069

    
2070
void dump_format(AVFormatContext *ic,
2071
                 int index, 
2072
                 const char *url,
2073
                 int is_output)
2074
{
2075
    int i, flags;
2076
    char buf[256];
2077

    
2078
    av_log(NULL, AV_LOG_DEBUG, "%s #%d, %s, %s '%s':\n", 
2079
            is_output ? "Output" : "Input",
2080
            index, 
2081
            is_output ? ic->oformat->name : ic->iformat->name, 
2082
            is_output ? "to" : "from", url);
2083
    if (!is_output) {
2084
        av_log(NULL, AV_LOG_DEBUG, "  Duration: ");
2085
        if (ic->duration != AV_NOPTS_VALUE) {
2086
            int hours, mins, secs, us;
2087
            secs = ic->duration / AV_TIME_BASE;
2088
            us = ic->duration % AV_TIME_BASE;
2089
            mins = secs / 60;
2090
            secs %= 60;
2091
            hours = mins / 60;
2092
            mins %= 60;
2093
            av_log(NULL, AV_LOG_DEBUG, "%02d:%02d:%02d.%01d", hours, mins, secs, 
2094
                   (10 * us) / AV_TIME_BASE);
2095
        } else {
2096
            av_log(NULL, AV_LOG_DEBUG, "N/A");
2097
        }
2098
        av_log(NULL, AV_LOG_DEBUG, ", bitrate: ");
2099
        if (ic->bit_rate) {
2100
            av_log(NULL, AV_LOG_DEBUG,"%d kb/s", ic->bit_rate / 1000);
2101
        } else {
2102
            av_log(NULL, AV_LOG_DEBUG, "N/A");
2103
        }
2104
        av_log(NULL, AV_LOG_DEBUG, "\n");
2105
    }
2106
    for(i=0;i<ic->nb_streams;i++) {
2107
        AVStream *st = ic->streams[i];
2108
        avcodec_string(buf, sizeof(buf), &st->codec, is_output);
2109
        av_log(NULL, AV_LOG_DEBUG, "  Stream #%d.%d", index, i);
2110
        /* the pid is an important information, so we display it */
2111
        /* XXX: add a generic system */
2112
        if (is_output)
2113
            flags = ic->oformat->flags;
2114
        else
2115
            flags = ic->iformat->flags;
2116
        if (flags & AVFMT_SHOW_IDS) {
2117
            av_log(NULL, AV_LOG_DEBUG, "[0x%x]", st->id);
2118
        }
2119
        av_log(NULL, AV_LOG_DEBUG, ": %s\n", buf);
2120
    }
2121
}
2122

    
2123
typedef struct {
2124
    const char *abv;
2125
    int width, height;
2126
    int frame_rate, frame_rate_base;
2127
} AbvEntry;
2128

    
2129
static AbvEntry frame_abvs[] = {
2130
    { "ntsc",      720, 480, 30000, 1001 },
2131
    { "pal",       720, 576,    25,    1 },
2132
    { "qntsc",     352, 240, 30000, 1001 }, /* VCD compliant ntsc */
2133
    { "qpal",      352, 288,    25,    1 }, /* VCD compliant pal */
2134
    { "sntsc",     640, 480, 30000, 1001 }, /* square pixel ntsc */
2135
    { "spal",      768, 576,    25,    1 }, /* square pixel pal */
2136
    { "film",      352, 240,    24,    1 },
2137
    { "ntsc-film", 352, 240, 24000, 1001 },
2138
    { "sqcif",     128,  96,     0,    0 },
2139
    { "qcif",      176, 144,     0,    0 },
2140
    { "cif",       352, 288,     0,    0 },
2141
    { "4cif",      704, 576,     0,    0 },
2142
};
2143

    
2144
int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2145
{
2146
    int i;
2147
    int n = sizeof(frame_abvs) / sizeof(AbvEntry);
2148
    const char *p;
2149
    int frame_width = 0, frame_height = 0;
2150

    
2151
    for(i=0;i<n;i++) {
2152
        if (!strcmp(frame_abvs[i].abv, str)) {
2153
            frame_width = frame_abvs[i].width;
2154
            frame_height = frame_abvs[i].height;
2155
            break;
2156
        }
2157
    }
2158
    if (i == n) {
2159
        p = str;
2160
        frame_width = strtol(p, (char **)&p, 10);
2161
        if (*p)
2162
            p++;
2163
        frame_height = strtol(p, (char **)&p, 10);
2164
    }
2165
    if (frame_width <= 0 || frame_height <= 0)
2166
        return -1;
2167
    *width_ptr = frame_width;
2168
    *height_ptr = frame_height;
2169
    return 0;
2170
}
2171

    
2172
int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
2173
{
2174
    int i;
2175
    char* cp;
2176
   
2177
    /* First, we check our abbreviation table */
2178
    for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
2179
         if (!strcmp(frame_abvs[i].abv, arg)) {
2180
             *frame_rate = frame_abvs[i].frame_rate;
2181
             *frame_rate_base = frame_abvs[i].frame_rate_base;
2182
             return 0;
2183
         }
2184

    
2185
    /* Then, we try to parse it as fraction */
2186
    cp = strchr(arg, '/');
2187
    if (cp) {
2188
        char* cpp;
2189
        *frame_rate = strtol(arg, &cpp, 10);
2190
        if (cpp != arg || cpp == cp) 
2191
            *frame_rate_base = strtol(cp+1, &cpp, 10);
2192
        else
2193
           *frame_rate = 0;
2194
    } 
2195
    else {
2196
        /* Finally we give up and parse it as double */
2197
        *frame_rate_base = DEFAULT_FRAME_RATE_BASE; //FIXME use av_d2q()
2198
        *frame_rate = (int)(strtod(arg, 0) * (*frame_rate_base) + 0.5);
2199
    }
2200
    if (!*frame_rate || !*frame_rate_base)
2201
        return -1;
2202
    else
2203
        return 0;
2204
}
2205

    
2206
/* Syntax:
2207
 * - If not a duration:
2208
 *  [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
2209
 * Time is localtime unless Z is suffixed to the end. In this case GMT
2210
 * Return the date in micro seconds since 1970 
2211
 * - If duration:
2212
 *  HH[:MM[:SS[.m...]]]
2213
 *  S+[.m...]
2214
 */
2215
int64_t parse_date(const char *datestr, int duration)
2216
{
2217
    const char *p;
2218
    int64_t t;
2219
    struct tm dt;
2220
    int i;
2221
    static const char *date_fmt[] = {
2222
        "%Y-%m-%d",
2223
        "%Y%m%d",
2224
    };
2225
    static const char *time_fmt[] = {
2226
        "%H:%M:%S",
2227
        "%H%M%S",
2228
    };
2229
    const char *q;
2230
    int is_utc, len;
2231
    char lastch;
2232
    int negative = 0;
2233

    
2234
#undef time
2235
    time_t now = time(0);
2236

    
2237
    len = strlen(datestr);
2238
    if (len > 0)
2239
        lastch = datestr[len - 1];
2240
    else
2241
        lastch = '\0';
2242
    is_utc = (lastch == 'z' || lastch == 'Z');
2243

    
2244
    memset(&dt, 0, sizeof(dt));
2245

    
2246
    p = datestr;
2247
    q = NULL;
2248
    if (!duration) {
2249
        for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
2250
            q = small_strptime(p, date_fmt[i], &dt);
2251
            if (q) {
2252
                break;
2253
            }
2254
        }
2255

    
2256
        if (!q) {
2257
            if (is_utc) {
2258
                dt = *gmtime(&now);
2259
            } else {
2260
                dt = *localtime(&now);
2261
            }
2262
            dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
2263
        } else {
2264
            p = q;
2265
        }
2266

    
2267
        if (*p == 'T' || *p == 't' || *p == ' ')
2268
            p++;
2269

    
2270
        for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
2271
            q = small_strptime(p, time_fmt[i], &dt);
2272
            if (q) {
2273
                break;
2274
            }
2275
        }
2276
    } else {
2277
        if (p[0] == '-') {
2278
            negative = 1;
2279
            ++p;
2280
        }
2281
        q = small_strptime(p, time_fmt[0], &dt);
2282
        if (!q) {
2283
            dt.tm_sec = strtol(p, (char **)&q, 10);
2284
            dt.tm_min = 0;
2285
            dt.tm_hour = 0;
2286
        }
2287
    }
2288

    
2289
    /* Now we have all the fields that we can get */
2290
    if (!q) {
2291
        if (duration)
2292
            return 0;
2293
        else
2294
            return now * int64_t_C(1000000);
2295
    }
2296

    
2297
    if (duration) {
2298
        t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2299
    } else {
2300
        dt.tm_isdst = -1;       /* unknown */
2301
        if (is_utc) {
2302
            t = mktimegm(&dt);
2303
        } else {
2304
            t = mktime(&dt);
2305
        }
2306
    }
2307

    
2308
    t *= 1000000;
2309

    
2310
    if (*q == '.') {
2311
        int val, n;
2312
        q++;
2313
        for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
2314
            if (!isdigit(*q)) 
2315
                break;
2316
            val += n * (*q - '0');
2317
        }
2318
        t += val;
2319
    }
2320
    return negative ? -t : t;
2321
}
2322

    
2323
/* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
2324
   1 if found */
2325
int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2326
{
2327
    const char *p;
2328
    char tag[128], *q;
2329

    
2330
    p = info;
2331
    if (*p == '?')
2332
        p++;
2333
    for(;;) {
2334
        q = tag;
2335
        while (*p != '\0' && *p != '=' && *p != '&') {
2336
            if ((q - tag) < sizeof(tag) - 1)
2337
                *q++ = *p;
2338
            p++;
2339
        }
2340
        *q = '\0';
2341
        q = arg;
2342
        if (*p == '=') {
2343
            p++;
2344
            while (*p != '&' && *p != '\0') {
2345
                if ((q - arg) < arg_size - 1) {
2346
                    if (*p == '+')
2347
                        *q++ = ' ';
2348
                    else
2349
                        *q++ = *p;
2350
                }
2351
                p++;
2352
            }
2353
            *q = '\0';
2354
        }
2355
        if (!strcmp(tag, tag1)) 
2356
            return 1;
2357
        if (*p != '&')
2358
            break;
2359
        p++;
2360
    }
2361
    return 0;
2362
}
2363

    
2364
/* Return in 'buf' the path with '%d' replaced by number. Also handles
2365
   the '%0nd' format where 'n' is the total number of digits and
2366
   '%%'. Return 0 if OK, and -1 if format error */
2367
int get_frame_filename(char *buf, int buf_size,
2368
                       const char *path, int number)
2369
{
2370
    const char *p;
2371
    char *q, buf1[20], c;
2372
    int nd, len, percentd_found;
2373

    
2374
    q = buf;
2375
    p = path;
2376
    percentd_found = 0;
2377
    for(;;) {
2378
        c = *p++;
2379
        if (c == '\0')
2380
            break;
2381
        if (c == '%') {
2382
            do {
2383
                nd = 0;
2384
                while (isdigit(*p)) {
2385
                    nd = nd * 10 + *p++ - '0';
2386
                }
2387
                c = *p++;
2388
            } while (isdigit(c));
2389

    
2390
            switch(c) {
2391
            case '%':
2392
                goto addchar;
2393
            case 'd':
2394
                if (percentd_found)
2395
                    goto fail;
2396
                percentd_found = 1;
2397
                snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2398
                len = strlen(buf1);
2399
                if ((q - buf + len) > buf_size - 1)
2400
                    goto fail;
2401
                memcpy(q, buf1, len);
2402
                q += len;
2403
                break;
2404
            default:
2405
                goto fail;
2406
            }
2407
        } else {
2408
        addchar:
2409
            if ((q - buf) < buf_size - 1)
2410
                *q++ = c;
2411
        }
2412
    }
2413
    if (!percentd_found)
2414
        goto fail;
2415
    *q = '\0';
2416
    return 0;
2417
 fail:
2418
    *q = '\0';
2419
    return -1;
2420
}
2421

    
2422
/**
2423
 * Print  nice hexa dump of a buffer
2424
 * @param f stream for output
2425
 * @param buf buffer
2426
 * @param size buffer size
2427
 */
2428
void av_hex_dump(FILE *f, uint8_t *buf, int size)
2429
{
2430
    int len, i, j, c;
2431

    
2432
    for(i=0;i<size;i+=16) {
2433
        len = size - i;
2434
        if (len > 16)
2435
            len = 16;
2436
        fprintf(f, "%08x ", i);
2437
        for(j=0;j<16;j++) {
2438
            if (j < len)
2439
                fprintf(f, " %02x", buf[i+j]);
2440
            else
2441
                fprintf(f, "   ");
2442
        }
2443
        fprintf(f, " ");
2444
        for(j=0;j<len;j++) {
2445
            c = buf[i+j];
2446
            if (c < ' ' || c > '~')
2447
                c = '.';
2448
            fprintf(f, "%c", c);
2449
        }
2450
        fprintf(f, "\n");
2451
    }
2452
}
2453

    
2454
/**
2455
 * Print on 'f' a nice dump of a packet
2456
 * @param f stream for output
2457
 * @param pkt packet to dump
2458
 * @param dump_payload true if the payload must be displayed too
2459
 */
2460
void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
2461
{
2462
    fprintf(f, "stream #%d:\n", pkt->stream_index);
2463
    fprintf(f, "  keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
2464
    fprintf(f, "  duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
2465
    /* DTS is _always_ valid after av_read_frame() */
2466
    fprintf(f, "  dts=");
2467
    if (pkt->dts == AV_NOPTS_VALUE)
2468
        fprintf(f, "N/A");
2469
    else
2470
        fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
2471
    /* PTS may be not known if B frames are present */
2472
    fprintf(f, "  pts=");
2473
    if (pkt->pts == AV_NOPTS_VALUE)
2474
        fprintf(f, "N/A");
2475
    else
2476
        fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
2477
    fprintf(f, "\n");
2478
    fprintf(f, "  size=%d\n", pkt->size);
2479
    if (dump_payload)
2480
        av_hex_dump(f, pkt->data, pkt->size);
2481
}
2482

    
2483
void url_split(char *proto, int proto_size,
2484
               char *hostname, int hostname_size,
2485
               int *port_ptr,
2486
               char *path, int path_size,
2487
               const char *url)
2488
{
2489
    const char *p;
2490
    char *q;
2491
    int port;
2492

    
2493
    port = -1;
2494

    
2495
    p = url;
2496
    q = proto;
2497
    while (*p != ':' && *p != '\0') {
2498
        if ((q - proto) < proto_size - 1)
2499
            *q++ = *p;
2500
        p++;
2501
    }
2502
    if (proto_size > 0)
2503
        *q = '\0';
2504
    if (*p == '\0') {
2505
        if (proto_size > 0)
2506
            proto[0] = '\0';
2507
        if (hostname_size > 0)
2508
            hostname[0] = '\0';
2509
        p = url;
2510
    } else {
2511
        p++;
2512
        if (*p == '/')
2513
            p++;
2514
        if (*p == '/')
2515
            p++;
2516
        q = hostname;
2517
        while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
2518
            if ((q - hostname) < hostname_size - 1)
2519
                *q++ = *p;
2520
            p++;
2521
        }
2522
        if (hostname_size > 0)
2523
            *q = '\0';
2524
        if (*p == ':') {
2525
            p++;
2526
            port = strtoul(p, (char **)&p, 10);
2527
        }
2528
    }
2529
    if (port_ptr)
2530
        *port_ptr = port;
2531
    pstrcpy(path, path_size, p);
2532
}
2533

    
2534
/**
2535
 * Set the pts for a given stream
2536
 * @param s stream 
2537
 * @param pts_wrap_bits number of bits effectively used by the pts
2538
 *        (used for wrap control, 33 is the value for MPEG) 
2539
 * @param pts_num numerator to convert to seconds (MPEG: 1) 
2540
 * @param pts_den denominator to convert to seconds (MPEG: 90000)
2541
 */
2542
void av_set_pts_info(AVStream *s, int pts_wrap_bits,
2543
                     int pts_num, int pts_den)
2544
{
2545
    s->pts_wrap_bits = pts_wrap_bits;
2546
    s->time_base.num = pts_num;
2547
    s->time_base.den = pts_den;
2548
}
2549

    
2550
/* fraction handling */
2551

    
2552
/**
2553
 * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
2554
 * as 0 <= num < den.
2555
 *
2556
 * @param f fractional number
2557
 * @param val integer value
2558
 * @param num must be >= 0
2559
 * @param den must be >= 1 
2560
 */
2561
void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
2562
{
2563
    num += (den >> 1);
2564
    if (num >= den) {
2565
        val += num / den;
2566
        num = num % den;
2567
    }
2568
    f->val = val;
2569
    f->num = num;
2570
    f->den = den;
2571
}
2572

    
2573
/* set f to (val + 0.5) */
2574
void av_frac_set(AVFrac *f, int64_t val)
2575
{
2576
    f->val = val;
2577
    f->num = f->den >> 1;
2578
}
2579

    
2580
/**
2581
 * Fractionnal addition to f: f = f + (incr / f->den)
2582
 *
2583
 * @param f fractional number
2584
 * @param incr increment, can be positive or negative
2585
 */
2586
void av_frac_add(AVFrac *f, int64_t incr)
2587
{
2588
    int64_t num, den;
2589

    
2590
    num = f->num + incr;
2591
    den = f->den;
2592
    if (num < 0) {
2593
        f->val += num / den;
2594
        num = num % den;
2595
        if (num < 0) {
2596
            num += den;
2597
            f->val--;
2598
        }
2599
    } else if (num >= den) {
2600
        f->val += num / den;
2601
        num = num % den;
2602
    }
2603
    f->num = num;
2604
}
2605

    
2606
/**
2607
 * register a new image format
2608
 * @param img_fmt Image format descriptor
2609
 */
2610
void av_register_image_format(AVImageFormat *img_fmt)
2611
{
2612
    AVImageFormat **p;
2613

    
2614
    p = &first_image_format;
2615
    while (*p != NULL) p = &(*p)->next;
2616
    *p = img_fmt;
2617
    img_fmt->next = NULL;
2618
}
2619

    
2620
/* guess image format */
2621
AVImageFormat *av_probe_image_format(AVProbeData *pd)
2622
{
2623
    AVImageFormat *fmt1, *fmt;
2624
    int score, score_max;
2625

    
2626
    fmt = NULL;
2627
    score_max = 0;
2628
    for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
2629
        if (fmt1->img_probe) {
2630
            score = fmt1->img_probe(pd);
2631
            if (score > score_max) {
2632
                score_max = score;
2633
                fmt = fmt1;
2634
            }
2635
        }
2636
    }
2637
    return fmt;
2638
}
2639

    
2640
AVImageFormat *guess_image_format(const char *filename)
2641
{
2642
    AVImageFormat *fmt1;
2643

    
2644
    for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
2645
        if (fmt1->extensions && match_ext(filename, fmt1->extensions))
2646
            return fmt1;
2647
    }
2648
    return NULL;
2649
}
2650

    
2651
/**
2652
 * Read an image from a stream. 
2653
 * @param gb byte stream containing the image
2654
 * @param fmt image format, NULL if probing is required
2655
 */
2656
int av_read_image(ByteIOContext *pb, const char *filename,
2657
                  AVImageFormat *fmt,
2658
                  int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
2659
{
2660
    char buf[PROBE_BUF_SIZE];
2661
    AVProbeData probe_data, *pd = &probe_data;
2662
    offset_t pos;
2663
    int ret;
2664

    
2665
    if (!fmt) {
2666
        pd->filename = filename;
2667
        pd->buf = buf;
2668
        pos = url_ftell(pb);
2669
        pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
2670
        url_fseek(pb, pos, SEEK_SET);
2671
        fmt = av_probe_image_format(pd);
2672
    }
2673
    if (!fmt)
2674
        return AVERROR_NOFMT;
2675
    ret = fmt->img_read(pb, alloc_cb, opaque);
2676
    return ret;
2677
}
2678

    
2679
/**
2680
 * Write an image to a stream.
2681
 * @param pb byte stream for the image output
2682
 * @param fmt image format
2683
 * @param img image data and informations
2684
 */
2685
int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
2686
{
2687
    return fmt->img_write(pb, img);
2688
}
2689