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