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