]> git.sesse.net Git - ffmpeg/blob - libavformat/swfdec.c
avformat/mxfdec: optimize probing
[ffmpeg] / libavformat / swfdec.c
1 /*
2  * Flash Compatible Streaming Format demuxer
3  * Copyright (c) 2000 Fabrice Bellard
4  * Copyright (c) 2003 Tinic Uro
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "libavutil/avassert.h"
24 #include "libavutil/channel_layout.h"
25 #include "libavutil/imgutils.h"
26 #include "libavutil/intreadwrite.h"
27 #include "swf.h"
28
29 static const AVCodecTag swf_audio_codec_tags[] = {
30     { AV_CODEC_ID_PCM_S16LE,  0x00 },
31     { AV_CODEC_ID_ADPCM_SWF,  0x01 },
32     { AV_CODEC_ID_MP3,        0x02 },
33     { AV_CODEC_ID_PCM_S16LE,  0x03 },
34 //  { AV_CODEC_ID_NELLYMOSER, 0x06 },
35     { AV_CODEC_ID_NONE,          0 },
36 };
37
38 static int get_swf_tag(AVIOContext *pb, int *len_ptr)
39 {
40     int tag, len;
41
42     if (url_feof(pb))
43         return AVERROR_EOF;
44
45     tag = avio_rl16(pb);
46     len = tag & 0x3f;
47     tag = tag >> 6;
48     if (len == 0x3f) {
49         len = avio_rl32(pb);
50     }
51     *len_ptr = len;
52     return tag;
53 }
54
55
56 static int swf_probe(AVProbeData *p)
57 {
58     if(p->buf_size < 15)
59         return 0;
60
61     /* check file header */
62     if ((p->buf[0] == 'F' || p->buf[0] == 'C') && p->buf[1] == 'W' &&
63         p->buf[2] == 'S' && p->buf[3] < 20)
64         return AVPROBE_SCORE_MAX;
65     else
66         return 0;
67 }
68
69 #if CONFIG_ZLIB
70 static int zlib_refill(void *opaque, uint8_t *buf, int buf_size)
71 {
72     AVFormatContext *s = opaque;
73     SWFContext *swf = s->priv_data;
74     z_stream *z = &swf->zstream;
75     int ret;
76
77 retry:
78     if (!z->avail_in) {
79         int n = avio_read(s->pb, swf->zbuf_in, ZBUF_SIZE);
80         if (n < 0)
81             return n;
82         z->next_in  = swf->zbuf_in;
83         z->avail_in = n;
84     }
85
86     z->next_out  = buf;
87     z->avail_out = buf_size;
88
89     ret = inflate(z, Z_NO_FLUSH);
90     if (ret < 0)
91         return AVERROR(EINVAL);
92     if (ret == Z_STREAM_END)
93         return AVERROR_EOF;
94
95     if (buf_size - z->avail_out == 0)
96         goto retry;
97
98     return buf_size - z->avail_out;
99 }
100 #endif
101
102 static int swf_read_header(AVFormatContext *s)
103 {
104     SWFContext *swf = s->priv_data;
105     AVIOContext *pb = s->pb;
106     int nbits, len, tag;
107
108     tag = avio_rb32(pb) & 0xffffff00;
109     avio_rl32(pb);
110
111     if (tag == MKBETAG('C', 'W', 'S', 0)) {
112         av_log(s, AV_LOG_INFO, "SWF compressed file detected\n");
113 #if CONFIG_ZLIB
114         swf->zbuf_in  = av_malloc(ZBUF_SIZE);
115         swf->zbuf_out = av_malloc(ZBUF_SIZE);
116         swf->zpb = avio_alloc_context(swf->zbuf_out, ZBUF_SIZE, 0, s,
117                                       zlib_refill, NULL, NULL);
118         if (!swf->zbuf_in || !swf->zbuf_out || !swf->zpb)
119             return AVERROR(ENOMEM);
120         swf->zpb->seekable = 0;
121         if (inflateInit(&swf->zstream) != Z_OK) {
122             av_log(s, AV_LOG_ERROR, "Unable to init zlib context\n");
123             return AVERROR(EINVAL);
124         }
125         pb = swf->zpb;
126 #else
127         av_log(s, AV_LOG_ERROR, "zlib support is required to read SWF compressed files\n");
128         return AVERROR(EIO);
129 #endif
130     } else if (tag != MKBETAG('F', 'W', 'S', 0))
131         return AVERROR(EIO);
132     /* skip rectangle size */
133     nbits = avio_r8(pb) >> 3;
134     len = (4 * nbits - 3 + 7) / 8;
135     avio_skip(pb, len);
136     swf->frame_rate = avio_rl16(pb); /* 8.8 fixed */
137     avio_rl16(pb); /* frame count */
138
139     swf->samples_per_frame = 0;
140     s->ctx_flags |= AVFMTCTX_NOHEADER;
141     return 0;
142 }
143
144 static AVStream *create_new_audio_stream(AVFormatContext *s, int id, int info)
145 {
146     int sample_rate_code, sample_size_code;
147     AVStream *ast = avformat_new_stream(s, NULL);
148     if (!ast)
149         return NULL;
150     ast->id = id;
151     if (info & 1) {
152         ast->codec->channels       = 2;
153         ast->codec->channel_layout = AV_CH_LAYOUT_STEREO;
154     } else {
155         ast->codec->channels       = 1;
156         ast->codec->channel_layout = AV_CH_LAYOUT_MONO;
157     }
158     ast->codec->codec_type = AVMEDIA_TYPE_AUDIO;
159     ast->codec->codec_id   = ff_codec_get_id(swf_audio_codec_tags, info>>4 & 15);
160     ast->need_parsing = AVSTREAM_PARSE_FULL;
161     sample_rate_code = info>>2 & 3;
162     sample_size_code = info>>1 & 1;
163     if (!sample_size_code && ast->codec->codec_id == AV_CODEC_ID_PCM_S16LE)
164         ast->codec->codec_id = AV_CODEC_ID_PCM_U8;
165     ast->codec->sample_rate = 44100 >> (3 - sample_rate_code);
166     avpriv_set_pts_info(ast, 64, 1, ast->codec->sample_rate);
167     return ast;
168 }
169
170 static int swf_read_packet(AVFormatContext *s, AVPacket *pkt)
171 {
172     SWFContext *swf = s->priv_data;
173     AVIOContext *pb = s->pb;
174     AVStream *vst = NULL, *ast = NULL, *st = 0;
175     int tag, len, i, frame, v, res;
176
177 #if CONFIG_ZLIB
178     if (swf->zpb)
179         pb = swf->zpb;
180 #endif
181
182     for(;;) {
183         uint64_t pos = avio_tell(pb);
184         tag = get_swf_tag(pb, &len);
185         if (tag < 0)
186             return tag;
187         if (len < 0) {
188             av_log(s, AV_LOG_ERROR, "invalid tag length: %d\n", len);
189             return AVERROR_INVALIDDATA;
190         }
191         if (tag == TAG_VIDEOSTREAM) {
192             int ch_id = avio_rl16(pb);
193             len -= 2;
194
195             for (i=0; i<s->nb_streams; i++) {
196                 st = s->streams[i];
197                 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->id == ch_id)
198                     goto skip;
199             }
200
201             avio_rl16(pb);
202             avio_rl16(pb);
203             avio_rl16(pb);
204             avio_r8(pb);
205             /* Check for FLV1 */
206             vst = avformat_new_stream(s, NULL);
207             if (!vst)
208                 return AVERROR(ENOMEM);
209             vst->id = ch_id;
210             vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
211             vst->codec->codec_id = ff_codec_get_id(ff_swf_codec_tags, avio_r8(pb));
212             avpriv_set_pts_info(vst, 16, 256, swf->frame_rate);
213             len -= 8;
214         } else if (tag == TAG_STREAMHEAD || tag == TAG_STREAMHEAD2) {
215             /* streaming found */
216
217             for (i=0; i<s->nb_streams; i++) {
218                 st = s->streams[i];
219                 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->id == -1)
220                     goto skip;
221             }
222
223             avio_r8(pb);
224             v = avio_r8(pb);
225             swf->samples_per_frame = avio_rl16(pb);
226             ast = create_new_audio_stream(s, -1, v); /* -1 to avoid clash with video stream ch_id */
227             if (!ast)
228                 return AVERROR(ENOMEM);
229             len -= 4;
230         } else if (tag == TAG_DEFINESOUND) {
231             /* audio stream */
232             int ch_id = avio_rl16(pb);
233
234             for (i=0; i<s->nb_streams; i++) {
235                 st = s->streams[i];
236                 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->id == ch_id)
237                     goto skip;
238             }
239
240             // FIXME: The entire audio stream is stored in a single chunk/tag. Normally,
241             // these are smaller audio streams in DEFINESOUND tags, but it's technically
242             // possible they could be huge. Break it up into multiple packets if it's big.
243             v = avio_r8(pb);
244             ast = create_new_audio_stream(s, ch_id, v);
245             if (!ast)
246                 return AVERROR(ENOMEM);
247             ast->duration = avio_rl32(pb); // number of samples
248             if (((v>>4) & 15) == 2) { // MP3 sound data record
249                 ast->skip_samples = avio_rl16(pb);
250                 len -= 2;
251             }
252             len -= 7;
253             if ((res = av_get_packet(pb, pkt, len)) < 0)
254                 return res;
255             pkt->pos = pos;
256             pkt->stream_index = ast->index;
257             return pkt->size;
258         } else if (tag == TAG_VIDEOFRAME) {
259             int ch_id = avio_rl16(pb);
260             len -= 2;
261             for(i=0; i<s->nb_streams; i++) {
262                 st = s->streams[i];
263                 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->id == ch_id) {
264                     frame = avio_rl16(pb);
265                     len -= 2;
266                     if (len <= 0)
267                         goto skip;
268                     if ((res = av_get_packet(pb, pkt, len)) < 0)
269                         return res;
270                     pkt->pos = pos;
271                     pkt->pts = frame;
272                     pkt->stream_index = st->index;
273                     return pkt->size;
274                 }
275             }
276         } else if (tag == TAG_DEFINEBITSLOSSLESS || tag == TAG_DEFINEBITSLOSSLESS2) {
277 #if CONFIG_ZLIB
278             long out_len;
279             uint8_t *buf = NULL, *zbuf = NULL, *pal;
280             uint32_t colormap[AVPALETTE_COUNT] = {0};
281             const int alpha_bmp = tag == TAG_DEFINEBITSLOSSLESS2;
282             const int colormapbpp = 3 + alpha_bmp;
283             int linesize, colormapsize = 0;
284
285             const int ch_id   = avio_rl16(pb);
286             const int bmp_fmt = avio_r8(pb);
287             const int width   = avio_rl16(pb);
288             const int height  = avio_rl16(pb);
289
290             len -= 2+1+2+2;
291
292             switch (bmp_fmt) {
293             case 3: // PAL-8
294                 linesize = width;
295                 colormapsize = avio_r8(pb) + 1;
296                 len--;
297                 break;
298             case 4: // RGB15
299                 linesize = width * 2;
300                 break;
301             case 5: // RGB24 (0RGB)
302                 linesize = width * 4;
303                 break;
304             default:
305                 av_log(s, AV_LOG_ERROR, "invalid bitmap format %d, skipped\n", bmp_fmt);
306                 goto bitmap_end_skip;
307             }
308
309             linesize = FFALIGN(linesize, 4);
310
311             if (av_image_check_size(width, height, 0, s) < 0 ||
312                 linesize >= INT_MAX / height ||
313                 linesize * height >= INT_MAX - colormapsize * colormapbpp) {
314                 av_log(s, AV_LOG_ERROR, "invalid frame size %dx%d\n", width, height);
315                 goto bitmap_end_skip;
316             }
317
318             out_len = colormapsize * colormapbpp + linesize * height;
319
320             av_dlog(s, "bitmap: ch=%d fmt=%d %dx%d (linesize=%d) len=%d->%ld pal=%d\n",
321                     ch_id, bmp_fmt, width, height, linesize, len, out_len, colormapsize);
322
323             zbuf = av_malloc(len);
324             buf  = av_malloc(out_len);
325             if (!zbuf || !buf) {
326                 res = AVERROR(ENOMEM);
327                 goto bitmap_end;
328             }
329
330             len = avio_read(pb, zbuf, len);
331             if (len < 0 || (res = uncompress(buf, &out_len, zbuf, len)) != Z_OK) {
332                 av_log(s, AV_LOG_WARNING, "Failed to uncompress one bitmap\n");
333                 goto bitmap_end_skip;
334             }
335
336             for (i = 0; i < s->nb_streams; i++) {
337                 st = s->streams[i];
338                 if (st->codec->codec_id == AV_CODEC_ID_RAWVIDEO && st->id == -3)
339                     break;
340             }
341             if (i == s->nb_streams) {
342                 vst = avformat_new_stream(s, NULL);
343                 if (!vst) {
344                     res = AVERROR(ENOMEM);
345                     goto bitmap_end;
346                 }
347                 vst->id = -3; /* -3 to avoid clash with video stream and audio stream */
348                 vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
349                 vst->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
350                 avpriv_set_pts_info(vst, 64, 256, swf->frame_rate);
351                 st = vst;
352             }
353             st->codec->width  = width;
354             st->codec->height = height;
355
356             if ((res = av_new_packet(pkt, out_len - colormapsize * colormapbpp)) < 0)
357                 goto bitmap_end;
358             pkt->pos = pos;
359             pkt->stream_index = st->index;
360
361             switch (bmp_fmt) {
362             case 3:
363                 st->codec->pix_fmt = AV_PIX_FMT_PAL8;
364                 for (i = 0; i < colormapsize; i++)
365                     if (alpha_bmp)  colormap[i] = buf[3]<<24 | AV_RB24(buf + 4*i);
366                     else            colormap[i] = 0xffU <<24 | AV_RB24(buf + 3*i);
367                 pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
368                 if (!pal) {
369                     res = AVERROR(ENOMEM);
370                     goto bitmap_end;
371                 }
372                 memcpy(pal, colormap, AVPALETTE_SIZE);
373                 break;
374             case 4:
375                 st->codec->pix_fmt = AV_PIX_FMT_RGB555;
376                 break;
377             case 5:
378                 st->codec->pix_fmt = alpha_bmp ? AV_PIX_FMT_ARGB : AV_PIX_FMT_0RGB;
379                 break;
380             default:
381                 av_assert0(0);
382             }
383
384             if (linesize * height > pkt->size) {
385                 res = AVERROR_INVALIDDATA;
386                 goto bitmap_end;
387             }
388             memcpy(pkt->data, buf + colormapsize*colormapbpp, linesize * height);
389
390             res = pkt->size;
391
392 bitmap_end:
393             av_freep(&zbuf);
394             av_freep(&buf);
395             return res;
396 bitmap_end_skip:
397             av_freep(&zbuf);
398             av_freep(&buf);
399 #else
400             av_log(s, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
401 #endif
402         } else if (tag == TAG_STREAMBLOCK) {
403             for (i = 0; i < s->nb_streams; i++) {
404                 st = s->streams[i];
405                 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->id == -1) {
406                     if (st->codec->codec_id == AV_CODEC_ID_MP3) {
407                         avio_skip(pb, 4);
408                         len -= 4;
409                         if (len <= 0)
410                             goto skip;
411                         if ((res = av_get_packet(pb, pkt, len)) < 0)
412                             return res;
413                     } else { // ADPCM, PCM
414                         if (len <= 0)
415                             goto skip;
416                         if ((res = av_get_packet(pb, pkt, len)) < 0)
417                             return res;
418                     }
419                     pkt->pos          = pos;
420                     pkt->stream_index = st->index;
421                     return pkt->size;
422                 }
423             }
424         } else if (tag == TAG_JPEG2) {
425             for (i=0; i<s->nb_streams; i++) {
426                 st = s->streams[i];
427                 if (st->codec->codec_id == AV_CODEC_ID_MJPEG && st->id == -2)
428                     break;
429             }
430             if (i == s->nb_streams) {
431                 vst = avformat_new_stream(s, NULL);
432                 if (!vst)
433                     return AVERROR(ENOMEM);
434                 vst->id = -2; /* -2 to avoid clash with video stream and audio stream */
435                 vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
436                 vst->codec->codec_id = AV_CODEC_ID_MJPEG;
437                 avpriv_set_pts_info(vst, 64, 256, swf->frame_rate);
438                 st = vst;
439             }
440             avio_rl16(pb); /* BITMAP_ID */
441             len -= 2;
442             if (len < 4)
443                 goto skip;
444             if ((res = av_new_packet(pkt, len)) < 0)
445                 return res;
446             avio_read(pb, pkt->data, 4);
447             if (AV_RB32(pkt->data) == 0xffd8ffd9 ||
448                 AV_RB32(pkt->data) == 0xffd9ffd8) {
449                 /* old SWF files containing SOI/EOI as data start */
450                 /* files created by swink have reversed tag */
451                 pkt->size -= 4;
452                 avio_read(pb, pkt->data, pkt->size);
453             } else {
454                 avio_read(pb, pkt->data + 4, pkt->size - 4);
455             }
456             pkt->pos = pos;
457             pkt->stream_index = st->index;
458             return pkt->size;
459         } else {
460             av_log(s, AV_LOG_DEBUG, "Unknown tag: %d\n", tag);
461         }
462     skip:
463         if(len<0)
464             av_log(s, AV_LOG_WARNING, "Cliping len %d\n", len);
465         len = FFMAX(0, len);
466         avio_skip(pb, len);
467     }
468 }
469
470 #if CONFIG_ZLIB
471 static av_cold int swf_read_close(AVFormatContext *avctx)
472 {
473     SWFContext *s = avctx->priv_data;
474     inflateEnd(&s->zstream);
475     av_freep(&s->zbuf_in);
476     av_freep(&s->zbuf_out);
477     av_freep(&s->zpb);
478     return 0;
479 }
480 #endif
481
482 AVInputFormat ff_swf_demuxer = {
483     .name           = "swf",
484     .long_name      = NULL_IF_CONFIG_SMALL("SWF (ShockWave Flash)"),
485     .priv_data_size = sizeof(SWFContext),
486     .read_probe     = swf_probe,
487     .read_header    = swf_read_header,
488     .read_packet    = swf_read_packet,
489 #if CONFIG_ZLIB
490     .read_close     = swf_read_close,
491 #endif
492 };