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