]> git.sesse.net Git - ffmpeg/blob - libavformat/ffmdec.c
avformat/ffmdec: Check pix_fmt
[ffmpeg] / libavformat / ffmdec.c
1 /*
2  * FFM (ffserver live feed) demuxer
3  * Copyright (c) 2001 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include <stdint.h>
23
24 #include "libavutil/internal.h"
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/intfloat.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/avassert.h"
29 #include "libavutil/avstring.h"
30 #include "libavutil/pixdesc.h"
31 #include "avformat.h"
32 #include "internal.h"
33 #include "ffm.h"
34 #include "avio_internal.h"
35
36 static int ffm_is_avail_data(AVFormatContext *s, int size)
37 {
38     FFMContext *ffm = s->priv_data;
39     int64_t pos, avail_size;
40     ptrdiff_t len;
41
42     len = ffm->packet_end - ffm->packet_ptr;
43     if (size <= len)
44         return 1;
45     pos = avio_tell(s->pb);
46     if (!ffm->write_index) {
47         if (pos == ffm->file_size)
48             return AVERROR_EOF;
49         avail_size = ffm->file_size - pos;
50     } else {
51     if (pos == ffm->write_index) {
52         /* exactly at the end of stream */
53         if (ffm->server_attached)
54             return AVERROR(EAGAIN);
55         else
56             return AVERROR_INVALIDDATA;
57     } else if (pos < ffm->write_index) {
58         avail_size = ffm->write_index - pos;
59     } else {
60         avail_size = (ffm->file_size - pos) + (ffm->write_index - FFM_PACKET_SIZE);
61     }
62     }
63     avail_size = (avail_size / ffm->packet_size) * (ffm->packet_size - FFM_HEADER_SIZE) + len;
64     if (size <= avail_size)
65         return 1;
66     else if (ffm->server_attached)
67         return AVERROR(EAGAIN);
68     else
69         return AVERROR_INVALIDDATA;
70 }
71
72 static int ffm_resync(AVFormatContext *s, uint32_t state)
73 {
74     av_log(s, AV_LOG_ERROR, "resyncing\n");
75     while (state != PACKET_ID) {
76         if (avio_feof(s->pb)) {
77             av_log(s, AV_LOG_ERROR, "cannot find FFM syncword\n");
78             return -1;
79         }
80         state = (state << 8) | avio_r8(s->pb);
81     }
82     return 0;
83 }
84
85 /* first is true if we read the frame header */
86 static int ffm_read_data(AVFormatContext *s,
87                          uint8_t *buf, int size, int header)
88 {
89     FFMContext *ffm = s->priv_data;
90     AVIOContext *pb = s->pb;
91     int fill_size, size1, frame_offset;
92     uint32_t id;
93     ptrdiff_t len;
94     int64_t last_pos = -1;
95
96     size1 = size;
97     while (size > 0) {
98     redo:
99         len = ffm->packet_end - ffm->packet_ptr;
100         if (len < 0)
101             return -1;
102         if (len > size)
103             len = size;
104         if (len == 0) {
105             if (avio_tell(pb) == ffm->file_size) {
106                 if (ffm->server_attached) {
107                     avio_seek(pb, ffm->packet_size, SEEK_SET);
108                 } else
109                     return AVERROR_EOF;
110             }
111     retry_read:
112             if (pb->buffer_size != ffm->packet_size) {
113                 int64_t tell = avio_tell(pb);
114                 int ret = ffio_set_buf_size(pb, ffm->packet_size);
115                 if (ret < 0)
116                     return ret;
117                 avio_seek(pb, tell, SEEK_SET);
118             }
119             id = avio_rb16(pb); /* PACKET_ID */
120             if (id != PACKET_ID) {
121                 if (ffm_resync(s, id) < 0)
122                     return -1;
123                 last_pos = avio_tell(pb);
124             }
125             fill_size = avio_rb16(pb);
126             ffm->dts = avio_rb64(pb);
127             frame_offset = avio_rb16(pb);
128             avio_read(pb, ffm->packet, ffm->packet_size - FFM_HEADER_SIZE);
129             if (ffm->packet_size < FFM_HEADER_SIZE + fill_size || frame_offset < 0) {
130                 return -1;
131             }
132             ffm->packet_end = ffm->packet + (ffm->packet_size - FFM_HEADER_SIZE - fill_size);
133             /* if first packet or resynchronization packet, we must
134                handle it specifically */
135             if (ffm->first_packet || (frame_offset & 0x8000)) {
136                 if (!frame_offset) {
137                     /* This packet has no frame headers in it */
138                     if (avio_tell(pb) >= ffm->packet_size * 3LL) {
139                         int64_t seekback = FFMIN(ffm->packet_size * 2LL, avio_tell(pb) - last_pos);
140                         seekback = FFMAX(seekback, 0);
141                         avio_seek(pb, -seekback, SEEK_CUR);
142                         goto retry_read;
143                     }
144                     /* This is bad, we cannot find a valid frame header */
145                     return 0;
146                 }
147                 ffm->first_packet = 0;
148                 if ((frame_offset & 0x7fff) < FFM_HEADER_SIZE) {
149                     ffm->packet_end = ffm->packet_ptr;
150                     return -1;
151                 }
152                 ffm->packet_ptr = ffm->packet + (frame_offset & 0x7fff) - FFM_HEADER_SIZE;
153                 if (!header)
154                     break;
155             } else {
156                 ffm->packet_ptr = ffm->packet;
157             }
158             goto redo;
159         }
160         memcpy(buf, ffm->packet_ptr, len);
161         buf += len;
162         ffm->packet_ptr += len;
163         size -= len;
164         header = 0;
165     }
166     return size1 - size;
167 }
168
169 /* ensure that actual seeking happens between FFM_PACKET_SIZE
170    and file_size - FFM_PACKET_SIZE */
171 static int64_t ffm_seek1(AVFormatContext *s, int64_t pos1)
172 {
173     FFMContext *ffm = s->priv_data;
174     AVIOContext *pb = s->pb;
175     int64_t pos;
176
177     pos = FFMIN(pos1, ffm->file_size - FFM_PACKET_SIZE);
178     pos = FFMAX(pos, FFM_PACKET_SIZE);
179     ff_dlog(s, "seek to %"PRIx64" -> %"PRIx64"\n", pos1, pos);
180     return avio_seek(pb, pos, SEEK_SET);
181 }
182
183 static int64_t get_dts(AVFormatContext *s, int64_t pos)
184 {
185     AVIOContext *pb = s->pb;
186     int64_t dts;
187
188     ffm_seek1(s, pos);
189     avio_skip(pb, 4);
190     dts = avio_rb64(pb);
191     ff_dlog(s, "dts=%0.6f\n", dts / 1000000.0);
192     return dts;
193 }
194
195 static void adjust_write_index(AVFormatContext *s)
196 {
197     FFMContext *ffm = s->priv_data;
198     AVIOContext *pb = s->pb;
199     int64_t pts;
200     //int64_t orig_write_index = ffm->write_index;
201     int64_t pos_min, pos_max;
202     int64_t pts_start;
203     int64_t ptr = avio_tell(pb);
204
205
206     pos_min = 0;
207     pos_max = ffm->file_size - 2 * FFM_PACKET_SIZE;
208
209     pts_start = get_dts(s, pos_min);
210
211     pts = get_dts(s, pos_max);
212
213     if (pts - 100000 > pts_start)
214         goto end;
215
216     ffm->write_index = FFM_PACKET_SIZE;
217
218     pts_start = get_dts(s, pos_min);
219
220     pts = get_dts(s, pos_max);
221
222     if (pts - 100000 <= pts_start) {
223         while (1) {
224             int64_t newpos;
225             int64_t newpts;
226
227             newpos = ((pos_max + pos_min) / (2 * FFM_PACKET_SIZE)) * FFM_PACKET_SIZE;
228
229             if (newpos == pos_min)
230                 break;
231
232             newpts = get_dts(s, newpos);
233
234             if (newpts - 100000 <= pts) {
235                 pos_max = newpos;
236                 pts = newpts;
237             } else {
238                 pos_min = newpos;
239             }
240         }
241         ffm->write_index += pos_max;
242     }
243
244  end:
245     avio_seek(pb, ptr, SEEK_SET);
246 }
247
248
249 static int ffm_close(AVFormatContext *s)
250 {
251     int i;
252
253     for (i = 0; i < s->nb_streams; i++)
254         av_freep(&s->streams[i]->codec->rc_eq);
255
256     return 0;
257 }
258
259 static int ffm_append_recommended_configuration(AVStream *st, char **conf)
260 {
261     int ret;
262     size_t newsize;
263     av_assert0(conf && st);
264     if (!*conf)
265         return 0;
266     if (!st->recommended_encoder_configuration) {
267         st->recommended_encoder_configuration = *conf;
268         *conf = 0;
269         return 0;
270     }
271     newsize = strlen(*conf) + strlen(st->recommended_encoder_configuration) + 2;
272     if ((ret = av_reallocp(&st->recommended_encoder_configuration, newsize)) < 0)
273         return ret;
274     av_strlcat(st->recommended_encoder_configuration, ",", newsize);
275     av_strlcat(st->recommended_encoder_configuration, *conf, newsize);
276     av_freep(conf);
277     return 0;
278 }
279
280 static int ffm2_read_header(AVFormatContext *s)
281 {
282     FFMContext *ffm = s->priv_data;
283     AVStream *st;
284     AVIOContext *pb = s->pb;
285     AVCodecContext *codec;
286     const AVCodecDescriptor *codec_desc;
287     int ret, i;
288     int f_main = 0, f_cprv = -1, f_stvi = -1, f_stau = -1;
289     AVCodec *enc;
290     char *buffer;
291
292     ffm->packet_size = avio_rb32(pb);
293     if (ffm->packet_size != FFM_PACKET_SIZE) {
294         av_log(s, AV_LOG_ERROR, "Invalid packet size %d, expected size was %d\n",
295                ffm->packet_size, FFM_PACKET_SIZE);
296         ret = AVERROR_INVALIDDATA;
297         goto fail;
298     }
299
300     ffm->write_index = avio_rb64(pb);
301     /* get also filesize */
302     if (pb->seekable) {
303         ffm->file_size = avio_size(pb);
304         if (ffm->write_index && 0)
305             adjust_write_index(s);
306     } else {
307         ffm->file_size = (UINT64_C(1) << 63) - 1;
308     }
309
310     while(!avio_feof(pb)) {
311         unsigned id = avio_rb32(pb);
312         unsigned size = avio_rb32(pb);
313         int64_t next = avio_tell(pb) + size;
314         char rc_eq_buf[128];
315
316         if(!id)
317             break;
318
319         switch(id) {
320         case MKBETAG('M', 'A', 'I', 'N'):
321             if (f_main++) {
322                 ret = AVERROR(EINVAL);
323                 goto fail;
324             }
325             avio_rb32(pb); /* nb_streams */
326             avio_rb32(pb); /* total bitrate */
327             break;
328         case MKBETAG('C', 'O', 'M', 'M'):
329             f_cprv = f_stvi = f_stau = 0;
330             st = avformat_new_stream(s, NULL);
331             if (!st) {
332                 ret = AVERROR(ENOMEM);
333                 goto fail;
334             }
335
336             avpriv_set_pts_info(st, 64, 1, 1000000);
337
338             codec = st->codec;
339             /* generic info */
340             codec->codec_id = avio_rb32(pb);
341             codec_desc = avcodec_descriptor_get(codec->codec_id);
342             if (!codec_desc) {
343                 av_log(s, AV_LOG_ERROR, "Invalid codec id: %d\n", codec->codec_id);
344                 codec->codec_id = AV_CODEC_ID_NONE;
345                 goto fail;
346             }
347             codec->codec_type = avio_r8(pb);
348             if (codec->codec_type != codec_desc->type) {
349                 av_log(s, AV_LOG_ERROR, "Codec type mismatch: expected %d, found %d\n",
350                        codec_desc->type, codec->codec_type);
351                 codec->codec_id = AV_CODEC_ID_NONE;
352                 codec->codec_type = AVMEDIA_TYPE_UNKNOWN;
353                 goto fail;
354             }
355             codec->bit_rate = avio_rb32(pb);
356             codec->flags = avio_rb32(pb);
357             codec->flags2 = avio_rb32(pb);
358             codec->debug = avio_rb32(pb);
359             if (codec->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
360                 int size = avio_rb32(pb);
361                 codec->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
362                 if (!codec->extradata)
363                     return AVERROR(ENOMEM);
364                 codec->extradata_size = size;
365                 avio_read(pb, codec->extradata, size);
366             }
367             break;
368         case MKBETAG('S', 'T', 'V', 'I'):
369             if (f_stvi++) {
370                 ret = AVERROR(EINVAL);
371                 goto fail;
372             }
373             codec->time_base.num = avio_rb32(pb);
374             codec->time_base.den = avio_rb32(pb);
375             if (codec->time_base.num <= 0 || codec->time_base.den <= 0) {
376                 av_log(s, AV_LOG_ERROR, "Invalid time base %d/%d\n",
377                        codec->time_base.num, codec->time_base.den);
378                 ret = AVERROR_INVALIDDATA;
379                 goto fail;
380             }
381             codec->width = avio_rb16(pb);
382             codec->height = avio_rb16(pb);
383             codec->gop_size = avio_rb16(pb);
384             codec->pix_fmt = avio_rb32(pb);
385             if (!av_pix_fmt_desc_get(codec->pix_fmt)) {
386                 av_log(s, AV_LOG_ERROR, "Invalid pix fmt id: %d\n", codec->pix_fmt);
387                 codec->pix_fmt = AV_PIX_FMT_NONE;
388                 goto fail;
389             }
390             codec->qmin = avio_r8(pb);
391             codec->qmax = avio_r8(pb);
392             codec->max_qdiff = avio_r8(pb);
393             codec->qcompress = avio_rb16(pb) / 10000.0;
394             codec->qblur = avio_rb16(pb) / 10000.0;
395             codec->bit_rate_tolerance = avio_rb32(pb);
396             avio_get_str(pb, INT_MAX, rc_eq_buf, sizeof(rc_eq_buf));
397             codec->rc_eq = av_strdup(rc_eq_buf);
398             codec->rc_max_rate = avio_rb32(pb);
399             codec->rc_min_rate = avio_rb32(pb);
400             codec->rc_buffer_size = avio_rb32(pb);
401             codec->i_quant_factor = av_int2double(avio_rb64(pb));
402             codec->b_quant_factor = av_int2double(avio_rb64(pb));
403             codec->i_quant_offset = av_int2double(avio_rb64(pb));
404             codec->b_quant_offset = av_int2double(avio_rb64(pb));
405             codec->dct_algo = avio_rb32(pb);
406             codec->strict_std_compliance = avio_rb32(pb);
407             codec->max_b_frames = avio_rb32(pb);
408             codec->mpeg_quant = avio_rb32(pb);
409             codec->intra_dc_precision = avio_rb32(pb);
410             codec->me_method = avio_rb32(pb);
411             codec->mb_decision = avio_rb32(pb);
412             codec->nsse_weight = avio_rb32(pb);
413             codec->frame_skip_cmp = avio_rb32(pb);
414             codec->rc_buffer_aggressivity = av_int2double(avio_rb64(pb));
415             codec->codec_tag = avio_rb32(pb);
416             codec->thread_count = avio_r8(pb);
417             codec->coder_type = avio_rb32(pb);
418             codec->me_cmp = avio_rb32(pb);
419             codec->me_subpel_quality = avio_rb32(pb);
420             codec->me_range = avio_rb32(pb);
421             codec->keyint_min = avio_rb32(pb);
422             codec->scenechange_threshold = avio_rb32(pb);
423             codec->b_frame_strategy = avio_rb32(pb);
424             codec->qcompress = av_int2double(avio_rb64(pb));
425             codec->qblur = av_int2double(avio_rb64(pb));
426             codec->max_qdiff = avio_rb32(pb);
427             codec->refs = avio_rb32(pb);
428             break;
429         case MKBETAG('S', 'T', 'A', 'U'):
430             if (f_stau++) {
431                 ret = AVERROR(EINVAL);
432                 goto fail;
433             }
434             codec->sample_rate = avio_rb32(pb);
435             codec->channels = avio_rl16(pb);
436             codec->frame_size = avio_rl16(pb);
437             break;
438         case MKBETAG('C', 'P', 'R', 'V'):
439             if (f_cprv++) {
440                 ret = AVERROR(EINVAL);
441                 goto fail;
442             }
443             enc = avcodec_find_encoder(codec->codec_id);
444             if (enc && enc->priv_data_size && enc->priv_class) {
445                 buffer = av_malloc(size + 1);
446                 if (!buffer) {
447                     ret = AVERROR(ENOMEM);
448                     goto fail;
449                 }
450                 avio_get_str(pb, size, buffer, size + 1);
451                 if ((ret = ffm_append_recommended_configuration(st, &buffer)) < 0)
452                     goto fail;
453             }
454             break;
455         case MKBETAG('S', '2', 'V', 'I'):
456             if (f_stvi++ || !size) {
457                 ret = AVERROR(EINVAL);
458                 goto fail;
459             }
460             buffer = av_malloc(size);
461             if (!buffer) {
462                 ret = AVERROR(ENOMEM);
463                 goto fail;
464             }
465             avio_get_str(pb, INT_MAX, buffer, size);
466             av_set_options_string(codec, buffer, "=", ",");
467             if ((ret = ffm_append_recommended_configuration(st, &buffer)) < 0)
468                 goto fail;
469             break;
470         case MKBETAG('S', '2', 'A', 'U'):
471             if (f_stau++ || !size) {
472                 ret = AVERROR(EINVAL);
473                 goto fail;
474             }
475             buffer = av_malloc(size);
476             if (!buffer) {
477                 ret = AVERROR(ENOMEM);
478                 goto fail;
479             }
480             avio_get_str(pb, INT_MAX, buffer, size);
481             av_set_options_string(codec, buffer, "=", ",");
482             if ((ret = ffm_append_recommended_configuration(st, &buffer)) < 0)
483                 goto fail;
484             break;
485         }
486         avio_seek(pb, next, SEEK_SET);
487     }
488
489     for (i = 0; i < s->nb_streams; i++)
490         avcodec_parameters_from_context(s->streams[i]->codecpar, s->streams[i]->codec);
491
492     /* get until end of block reached */
493     while ((avio_tell(pb) % ffm->packet_size) != 0 && !pb->eof_reached)
494         avio_r8(pb);
495
496     /* init packet demux */
497     ffm->packet_ptr = ffm->packet;
498     ffm->packet_end = ffm->packet;
499     ffm->frame_offset = 0;
500     ffm->dts = 0;
501     ffm->read_state = READ_HEADER;
502     ffm->first_packet = 1;
503     return 0;
504  fail:
505     ffm_close(s);
506     return ret;
507 }
508
509 static int ffm_read_header(AVFormatContext *s)
510 {
511     FFMContext *ffm = s->priv_data;
512     AVStream *st;
513     AVIOContext *pb = s->pb;
514     AVCodecContext *codec;
515     const AVCodecDescriptor *codec_desc;
516     int i, nb_streams;
517     uint32_t tag;
518
519     /* header */
520     tag = avio_rl32(pb);
521     if (tag == MKTAG('F', 'F', 'M', '2'))
522         return ffm2_read_header(s);
523     if (tag != MKTAG('F', 'F', 'M', '1'))
524         goto fail;
525     ffm->packet_size = avio_rb32(pb);
526     if (ffm->packet_size != FFM_PACKET_SIZE)
527         goto fail;
528     ffm->write_index = avio_rb64(pb);
529     /* get also filesize */
530     if (pb->seekable) {
531         ffm->file_size = avio_size(pb);
532         if (ffm->write_index && 0)
533             adjust_write_index(s);
534     } else {
535         ffm->file_size = (UINT64_C(1) << 63) - 1;
536     }
537
538     nb_streams = avio_rb32(pb);
539     avio_rb32(pb); /* total bitrate */
540     /* read each stream */
541     for(i=0;i<nb_streams;i++) {
542         char rc_eq_buf[128];
543
544         st = avformat_new_stream(s, NULL);
545         if (!st)
546             goto fail;
547
548         avpriv_set_pts_info(st, 64, 1, 1000000);
549
550         codec = st->codec;
551         /* generic info */
552         codec->codec_id = avio_rb32(pb);
553         codec_desc = avcodec_descriptor_get(codec->codec_id);
554         if (!codec_desc) {
555             av_log(s, AV_LOG_ERROR, "Invalid codec id: %d\n", codec->codec_id);
556             codec->codec_id = AV_CODEC_ID_NONE;
557             goto fail;
558         }
559         codec->codec_type = avio_r8(pb); /* codec_type */
560         if (codec->codec_type != codec_desc->type) {
561             av_log(s, AV_LOG_ERROR, "Codec type mismatch: expected %d, found %d\n",
562                    codec_desc->type, codec->codec_type);
563             codec->codec_id = AV_CODEC_ID_NONE;
564             codec->codec_type = AVMEDIA_TYPE_UNKNOWN;
565             goto fail;
566         }
567         codec->bit_rate = avio_rb32(pb);
568         codec->flags = avio_rb32(pb);
569         codec->flags2 = avio_rb32(pb);
570         codec->debug = avio_rb32(pb);
571         /* specific info */
572         switch(codec->codec_type) {
573         case AVMEDIA_TYPE_VIDEO:
574             codec->time_base.num = avio_rb32(pb);
575             codec->time_base.den = avio_rb32(pb);
576             if (codec->time_base.num <= 0 || codec->time_base.den <= 0) {
577                 av_log(s, AV_LOG_ERROR, "Invalid time base %d/%d\n",
578                        codec->time_base.num, codec->time_base.den);
579                 goto fail;
580             }
581             codec->width = avio_rb16(pb);
582             codec->height = avio_rb16(pb);
583             codec->gop_size = avio_rb16(pb);
584             codec->pix_fmt = avio_rb32(pb);
585             if (!av_pix_fmt_desc_get(codec->pix_fmt)) {
586                 av_log(s, AV_LOG_ERROR, "Invalid pix fmt id: %d\n", codec->pix_fmt);
587                 codec->pix_fmt = AV_PIX_FMT_NONE;
588                 goto fail;
589             }
590             codec->qmin = avio_r8(pb);
591             codec->qmax = avio_r8(pb);
592             codec->max_qdiff = avio_r8(pb);
593             codec->qcompress = avio_rb16(pb) / 10000.0;
594             codec->qblur = avio_rb16(pb) / 10000.0;
595             codec->bit_rate_tolerance = avio_rb32(pb);
596             avio_get_str(pb, INT_MAX, rc_eq_buf, sizeof(rc_eq_buf));
597             codec->rc_eq = av_strdup(rc_eq_buf);
598             codec->rc_max_rate = avio_rb32(pb);
599             codec->rc_min_rate = avio_rb32(pb);
600             codec->rc_buffer_size = avio_rb32(pb);
601             codec->i_quant_factor = av_int2double(avio_rb64(pb));
602             codec->b_quant_factor = av_int2double(avio_rb64(pb));
603             codec->i_quant_offset = av_int2double(avio_rb64(pb));
604             codec->b_quant_offset = av_int2double(avio_rb64(pb));
605             codec->dct_algo = avio_rb32(pb);
606             codec->strict_std_compliance = avio_rb32(pb);
607             codec->max_b_frames = avio_rb32(pb);
608             codec->mpeg_quant = avio_rb32(pb);
609             codec->intra_dc_precision = avio_rb32(pb);
610             codec->me_method = avio_rb32(pb);
611             codec->mb_decision = avio_rb32(pb);
612             codec->nsse_weight = avio_rb32(pb);
613             codec->frame_skip_cmp = avio_rb32(pb);
614             codec->rc_buffer_aggressivity = av_int2double(avio_rb64(pb));
615             codec->codec_tag = avio_rb32(pb);
616             codec->thread_count = avio_r8(pb);
617             codec->coder_type = avio_rb32(pb);
618             codec->me_cmp = avio_rb32(pb);
619             codec->me_subpel_quality = avio_rb32(pb);
620             codec->me_range = avio_rb32(pb);
621             codec->keyint_min = avio_rb32(pb);
622             codec->scenechange_threshold = avio_rb32(pb);
623             codec->b_frame_strategy = avio_rb32(pb);
624             codec->qcompress = av_int2double(avio_rb64(pb));
625             codec->qblur = av_int2double(avio_rb64(pb));
626             codec->max_qdiff = avio_rb32(pb);
627             codec->refs = avio_rb32(pb);
628             break;
629         case AVMEDIA_TYPE_AUDIO:
630             codec->sample_rate = avio_rb32(pb);
631             codec->channels = avio_rl16(pb);
632             codec->frame_size = avio_rl16(pb);
633             break;
634         default:
635             goto fail;
636         }
637         if (codec->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
638             int size = avio_rb32(pb);
639             codec->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
640             if (!codec->extradata)
641                 return AVERROR(ENOMEM);
642             codec->extradata_size = size;
643             avio_read(pb, codec->extradata, size);
644         }
645
646         avcodec_parameters_from_context(st->codecpar, codec);
647     }
648
649     /* get until end of block reached */
650     while ((avio_tell(pb) % ffm->packet_size) != 0 && !pb->eof_reached)
651         avio_r8(pb);
652
653     /* init packet demux */
654     ffm->packet_ptr = ffm->packet;
655     ffm->packet_end = ffm->packet;
656     ffm->frame_offset = 0;
657     ffm->dts = 0;
658     ffm->read_state = READ_HEADER;
659     ffm->first_packet = 1;
660     return 0;
661  fail:
662     ffm_close(s);
663     return -1;
664 }
665
666 /* return < 0 if eof */
667 static int ffm_read_packet(AVFormatContext *s, AVPacket *pkt)
668 {
669     int size;
670     FFMContext *ffm = s->priv_data;
671     int duration, ret;
672
673     switch(ffm->read_state) {
674     case READ_HEADER:
675         if ((ret = ffm_is_avail_data(s, FRAME_HEADER_SIZE+4)) < 0)
676             return ret;
677
678         ff_dlog(s, "pos=%08"PRIx64" spos=%"PRIx64", write_index=%"PRIx64" size=%"PRIx64"\n",
679                avio_tell(s->pb), s->pb->pos, ffm->write_index, ffm->file_size);
680         if (ffm_read_data(s, ffm->header, FRAME_HEADER_SIZE, 1) !=
681             FRAME_HEADER_SIZE)
682             return -1;
683         if (ffm->header[1] & FLAG_DTS)
684             if (ffm_read_data(s, ffm->header+16, 4, 1) != 4)
685                 return -1;
686         ffm->read_state = READ_DATA;
687         /* fall through */
688     case READ_DATA:
689         size = AV_RB24(ffm->header + 2);
690         if ((ret = ffm_is_avail_data(s, size)) < 0)
691             return ret;
692
693         duration = AV_RB24(ffm->header + 5);
694
695         if (av_new_packet(pkt, size) < 0) {
696             return AVERROR(ENOMEM);
697         }
698         pkt->stream_index = ffm->header[0];
699         if ((unsigned)pkt->stream_index >= s->nb_streams) {
700             av_log(s, AV_LOG_ERROR, "invalid stream index %d\n", pkt->stream_index);
701             av_packet_unref(pkt);
702             ffm->read_state = READ_HEADER;
703             return -1;
704         }
705         pkt->pos = avio_tell(s->pb);
706         if (ffm->header[1] & FLAG_KEY_FRAME)
707             pkt->flags |= AV_PKT_FLAG_KEY;
708
709         ffm->read_state = READ_HEADER;
710         if (ffm_read_data(s, pkt->data, size, 0) != size) {
711             /* bad case: desynchronized packet. we cancel all the packet loading */
712             av_packet_unref(pkt);
713             return -1;
714         }
715         pkt->pts = AV_RB64(ffm->header+8);
716         if (ffm->header[1] & FLAG_DTS)
717             pkt->dts = pkt->pts - AV_RB32(ffm->header+16);
718         else
719             pkt->dts = pkt->pts;
720         pkt->duration = duration;
721         break;
722     }
723     return 0;
724 }
725
726 /* seek to a given time in the file. The file read pointer is
727    positioned at or before pts. XXX: the following code is quite
728    approximative */
729 static int ffm_seek(AVFormatContext *s, int stream_index, int64_t wanted_pts, int flags)
730 {
731     FFMContext *ffm = s->priv_data;
732     int64_t pos_min, pos_max, pos;
733     int64_t pts_min, pts_max, pts;
734     double pos1;
735
736     ff_dlog(s, "wanted_pts=%0.6f\n", wanted_pts / 1000000.0);
737     /* find the position using linear interpolation (better than
738        dichotomy in typical cases) */
739     if (ffm->write_index && ffm->write_index < ffm->file_size) {
740         if (get_dts(s, FFM_PACKET_SIZE) < wanted_pts) {
741             pos_min = FFM_PACKET_SIZE;
742             pos_max = ffm->write_index - FFM_PACKET_SIZE;
743         } else {
744             pos_min = ffm->write_index;
745             pos_max = ffm->file_size - FFM_PACKET_SIZE;
746         }
747     } else {
748         pos_min = FFM_PACKET_SIZE;
749         pos_max = ffm->file_size - FFM_PACKET_SIZE;
750     }
751     while (pos_min <= pos_max) {
752         pts_min = get_dts(s, pos_min);
753         pts_max = get_dts(s, pos_max);
754         if (pts_min > wanted_pts || pts_max <= wanted_pts) {
755             pos = pts_min > wanted_pts ? pos_min : pos_max;
756             goto found;
757         }
758         /* linear interpolation */
759         pos1 = (double)(pos_max - pos_min) * (double)(wanted_pts - pts_min) /
760             (double)(pts_max - pts_min);
761         pos = (((int64_t)pos1) / FFM_PACKET_SIZE) * FFM_PACKET_SIZE;
762         if (pos <= pos_min)
763             pos = pos_min;
764         else if (pos >= pos_max)
765             pos = pos_max;
766         pts = get_dts(s, pos);
767         /* check if we are lucky */
768         if (pts == wanted_pts) {
769             goto found;
770         } else if (pts > wanted_pts) {
771             pos_max = pos - FFM_PACKET_SIZE;
772         } else {
773             pos_min = pos + FFM_PACKET_SIZE;
774         }
775     }
776     pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
777
778  found:
779     if (ffm_seek1(s, pos) < 0)
780         return -1;
781
782     /* reset read state */
783     ffm->read_state = READ_HEADER;
784     ffm->packet_ptr = ffm->packet;
785     ffm->packet_end = ffm->packet;
786     ffm->first_packet = 1;
787
788     return 0;
789 }
790
791 static int ffm_probe(AVProbeData *p)
792 {
793     if (
794         p->buf[0] == 'F' && p->buf[1] == 'F' && p->buf[2] == 'M' &&
795         (p->buf[3] == '1' || p->buf[3] == '2'))
796         return AVPROBE_SCORE_MAX + 1;
797     return 0;
798 }
799
800 static const AVOption options[] = {
801     {"server_attached", NULL, offsetof(FFMContext, server_attached), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_EXPORT },
802     {"ffm_write_index", NULL, offsetof(FFMContext, write_index), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, AV_OPT_FLAG_EXPORT },
803     {"ffm_file_size", NULL, offsetof(FFMContext, file_size), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, AV_OPT_FLAG_EXPORT },
804     { NULL },
805 };
806
807 static const AVClass ffm_class = {
808     .class_name = "ffm demuxer",
809     .item_name  = av_default_item_name,
810     .option     = options,
811     .version    = LIBAVUTIL_VERSION_INT,
812 };
813 AVInputFormat ff_ffm_demuxer = {
814     .name           = "ffm",
815     .long_name      = NULL_IF_CONFIG_SMALL("FFM (FFserver live feed)"),
816     .priv_data_size = sizeof(FFMContext),
817     .read_probe     = ffm_probe,
818     .read_header    = ffm_read_header,
819     .read_packet    = ffm_read_packet,
820     .read_close     = ffm_close,
821     .read_seek      = ffm_seek,
822     .priv_class     = &ffm_class,
823 };