]> git.sesse.net Git - ffmpeg/blob - libavformat/iff.c
avformat: Constify all muxer/demuxers
[ffmpeg] / libavformat / iff.c
1 /*
2  * Copyright (c) 2008 Jaikrishnan Menon <realityman@gmx.net>
3  * Copyright (c) 2010 Peter Ross <pross@xvid.org>
4  * Copyright (c) 2010 Sebastian Vater <cdgs.basty@googlemail.com>
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 /**
24  * @file
25  * IFF file demuxer
26  * by Jaikrishnan Menon
27  * for more information on the .iff file format, visit:
28  * http://wiki.multimedia.cx/index.php?title=IFF
29  */
30
31 #include <inttypes.h>
32
33 #include "libavutil/avassert.h"
34 #include "libavutil/channel_layout.h"
35 #include "libavutil/intreadwrite.h"
36 #include "libavutil/dict.h"
37 #include "libavcodec/bytestream.h"
38 #include "avformat.h"
39 #include "id3v2.h"
40 #include "internal.h"
41
42 #define ID_8SVX       MKTAG('8','S','V','X')
43 #define ID_16SV       MKTAG('1','6','S','V')
44 #define ID_MAUD       MKTAG('M','A','U','D')
45 #define ID_MHDR       MKTAG('M','H','D','R')
46 #define ID_MDAT       MKTAG('M','D','A','T')
47 #define ID_VHDR       MKTAG('V','H','D','R')
48 #define ID_ATAK       MKTAG('A','T','A','K')
49 #define ID_RLSE       MKTAG('R','L','S','E')
50 #define ID_CHAN       MKTAG('C','H','A','N')
51 #define ID_PBM        MKTAG('P','B','M',' ')
52 #define ID_ILBM       MKTAG('I','L','B','M')
53 #define ID_BMHD       MKTAG('B','M','H','D')
54 #define ID_DGBL       MKTAG('D','G','B','L')
55 #define ID_CAMG       MKTAG('C','A','M','G')
56 #define ID_CMAP       MKTAG('C','M','A','P')
57 #define ID_ACBM       MKTAG('A','C','B','M')
58 #define ID_DEEP       MKTAG('D','E','E','P')
59 #define ID_RGB8       MKTAG('R','G','B','8')
60 #define ID_RGBN       MKTAG('R','G','B','N')
61 #define ID_DSD        MKTAG('D','S','D',' ')
62 #define ID_DST        MKTAG('D','S','T',' ')
63 #define ID_DSTC       MKTAG('D','S','T','C')
64 #define ID_DSTF       MKTAG('D','S','T','F')
65 #define ID_FRTE       MKTAG('F','R','T','E')
66 #define ID_ANIM       MKTAG('A','N','I','M')
67 #define ID_ANHD       MKTAG('A','N','H','D')
68 #define ID_DLTA       MKTAG('D','L','T','A')
69 #define ID_DPAN       MKTAG('D','P','A','N')
70
71 #define ID_FORM       MKTAG('F','O','R','M')
72 #define ID_FRM8       MKTAG('F','R','M','8')
73 #define ID_ANNO       MKTAG('A','N','N','O')
74 #define ID_AUTH       MKTAG('A','U','T','H')
75 #define ID_CHRS       MKTAG('C','H','R','S')
76 #define ID_COPYRIGHT  MKTAG('(','c',')',' ')
77 #define ID_CSET       MKTAG('C','S','E','T')
78 #define ID_FVER       MKTAG('F','V','E','R')
79 #define ID_NAME       MKTAG('N','A','M','E')
80 #define ID_TEXT       MKTAG('T','E','X','T')
81 #define ID_ABIT       MKTAG('A','B','I','T')
82 #define ID_BODY       MKTAG('B','O','D','Y')
83 #define ID_DBOD       MKTAG('D','B','O','D')
84 #define ID_DPEL       MKTAG('D','P','E','L')
85 #define ID_DLOC       MKTAG('D','L','O','C')
86 #define ID_TVDC       MKTAG('T','V','D','C')
87
88 #define LEFT    2
89 #define RIGHT   4
90 #define STEREO  6
91
92 /**
93  * This number of bytes if added at the beginning of each AVPacket
94  * which contain additional information about video properties
95  * which has to be shared between demuxer and decoder.
96  * This number may change between frames, e.g. the demuxer might
97  * set it to smallest possible size of 2 to indicate that there's
98  * no extradata changing in this frame.
99  */
100 #define IFF_EXTRA_VIDEO_SIZE 41
101
102 typedef enum {
103     COMP_NONE,
104     COMP_FIB,
105     COMP_EXP
106 } svx8_compression_type;
107
108 typedef struct IffDemuxContext {
109     int      is_64bit;  ///< chunk size is 64-bit
110     int64_t  body_pos;
111     int64_t  body_end;
112     uint32_t  body_size;
113     svx8_compression_type   svx8_compression;
114     unsigned  maud_bits;
115     unsigned  maud_compression;
116     unsigned  bitmap_compression;  ///< delta compression method used
117     unsigned  bpp;          ///< bits per plane to decode (differs from bits_per_coded_sample if HAM)
118     unsigned  ham;          ///< 0 if non-HAM or number of hold bits (6 for bpp > 6, 4 otherwise)
119     unsigned  flags;        ///< 1 for EHB, 0 is no extra half darkening
120     unsigned  transparency; ///< transparency color index in palette
121     unsigned  masking;      ///< masking method used
122     uint8_t   tvdc[32];     ///< TVDC lookup table
123     int64_t   pts;
124 } IffDemuxContext;
125
126 /* Metadata string read */
127 static int get_metadata(AVFormatContext *s,
128                         const char *const tag,
129                         const unsigned data_size)
130 {
131     uint8_t *buf = ((data_size + 1) == 0) ? NULL : av_malloc(data_size + 1);
132
133     if (!buf)
134         return AVERROR(ENOMEM);
135
136     if (avio_read(s->pb, buf, data_size) != data_size) {
137         av_free(buf);
138         return AVERROR(EIO);
139     }
140     buf[data_size] = 0;
141     av_dict_set(&s->metadata, tag, buf, AV_DICT_DONT_STRDUP_VAL);
142     return 0;
143 }
144
145 static int iff_probe(const AVProbeData *p)
146 {
147     const uint8_t *d = p->buf;
148
149     if ( (AV_RL32(d)   == ID_FORM &&
150          (AV_RL32(d+8) == ID_8SVX ||
151           AV_RL32(d+8) == ID_16SV ||
152           AV_RL32(d+8) == ID_MAUD ||
153           AV_RL32(d+8) == ID_PBM  ||
154           AV_RL32(d+8) == ID_ACBM ||
155           AV_RL32(d+8) == ID_DEEP ||
156           AV_RL32(d+8) == ID_ILBM ||
157           AV_RL32(d+8) == ID_RGB8 ||
158           AV_RL32(d+8) == ID_ANIM ||
159           AV_RL32(d+8) == ID_RGBN)) ||
160          (AV_RL32(d) == ID_FRM8 && AV_RL32(d+12) == ID_DSD))
161         return AVPROBE_SCORE_MAX;
162     return 0;
163 }
164
165 static const AVCodecTag dsd_codec_tags[] = {
166     { AV_CODEC_ID_DSD_MSBF, ID_DSD },
167     { AV_CODEC_ID_DST,      ID_DST },
168     { AV_CODEC_ID_NONE, 0 },
169 };
170
171
172 #define DSD_SLFT MKTAG('S','L','F','T')
173 #define DSD_SRGT MKTAG('S','R','G','T')
174 #define DSD_MLFT MKTAG('M','L','F','T')
175 #define DSD_MRGT MKTAG('M','R','G','T')
176 #define DSD_C    MKTAG('C',' ',' ',' ')
177 #define DSD_LS   MKTAG('L','S',' ',' ')
178 #define DSD_RS   MKTAG('R','S',' ',' ')
179 #define DSD_LFE  MKTAG('L','F','E',' ')
180
181 static const uint32_t dsd_stereo[]  = { DSD_SLFT, DSD_SRGT };
182 static const uint32_t dsd_5point0[] = { DSD_MLFT, DSD_MRGT, DSD_C, DSD_LS, DSD_RS };
183 static const uint32_t dsd_5point1[] = { DSD_MLFT, DSD_MRGT, DSD_C, DSD_LFE, DSD_LS, DSD_RS };
184
185 typedef struct {
186     uint64_t layout;
187     const uint32_t * dsd_layout;
188 } DSDLayoutDesc;
189
190 static const DSDLayoutDesc dsd_channel_layout[] = {
191     { AV_CH_LAYOUT_STEREO,  dsd_stereo },
192     { AV_CH_LAYOUT_5POINT0, dsd_5point0 },
193     { AV_CH_LAYOUT_5POINT1, dsd_5point1 },
194 };
195
196 static const uint64_t dsd_loudspeaker_config[] = {
197     AV_CH_LAYOUT_STEREO,
198     0, 0,
199     AV_CH_LAYOUT_5POINT0, AV_CH_LAYOUT_5POINT1,
200 };
201
202 static const char * dsd_source_comment[] = {
203     "dsd_source_comment",
204     "analogue_source_comment",
205     "pcm_source_comment",
206 };
207
208 static const char * dsd_history_comment[] = {
209     "general_remark",
210     "operator_name",
211     "creating_machine",
212     "timezone",
213     "file_revision"
214 };
215
216 static int parse_dsd_diin(AVFormatContext *s, AVStream *st, uint64_t eof)
217 {
218     AVIOContext *pb = s->pb;
219
220     while (avio_tell(pb) + 12 <= eof && !avio_feof(pb)) {
221         uint32_t tag      = avio_rl32(pb);
222         uint64_t size     = avio_rb64(pb);
223         uint64_t orig_pos = avio_tell(pb);
224         const char * metadata_tag = NULL;
225
226         if (size >= INT64_MAX)
227             return AVERROR_INVALIDDATA;
228
229         switch(tag) {
230         case MKTAG('D','I','A','R'): metadata_tag = "artist"; break;
231         case MKTAG('D','I','T','I'): metadata_tag = "title";  break;
232         }
233
234         if (metadata_tag && size > 4) {
235             unsigned int tag_size = avio_rb32(pb);
236             int ret = get_metadata(s, metadata_tag, FFMIN(tag_size, size - 4));
237             if (ret < 0) {
238                 av_log(s, AV_LOG_ERROR, "cannot allocate metadata tag %s!\n", metadata_tag);
239                 return ret;
240             }
241         }
242
243         avio_skip(pb, size - (avio_tell(pb) - orig_pos) + (size & 1));
244     }
245
246     return 0;
247 }
248
249 static int parse_dsd_prop(AVFormatContext *s, AVStream *st, uint64_t eof)
250 {
251     AVIOContext *pb = s->pb;
252     char abss[24];
253     int hour, min, sec, i, ret, config;
254     int dsd_layout[6];
255     ID3v2ExtraMeta *id3v2_extra_meta;
256
257     while (avio_tell(pb) + 12 <= eof && !avio_feof(pb)) {
258         uint32_t tag      = avio_rl32(pb);
259         uint64_t size     = avio_rb64(pb);
260         uint64_t orig_pos = avio_tell(pb);
261
262         if (size >= INT64_MAX)
263             return AVERROR_INVALIDDATA;
264
265         switch(tag) {
266         case MKTAG('A','B','S','S'):
267             if (size < 8)
268                 return AVERROR_INVALIDDATA;
269             hour = avio_rb16(pb);
270             min  = avio_r8(pb);
271             sec  = avio_r8(pb);
272             snprintf(abss, sizeof(abss), "%02dh:%02dm:%02ds:%d", hour, min, sec, avio_rb32(pb));
273             av_dict_set(&st->metadata, "absolute_start_time", abss, 0);
274             break;
275
276         case MKTAG('C','H','N','L'):
277             if (size < 2)
278                 return AVERROR_INVALIDDATA;
279             st->codecpar->channels       = avio_rb16(pb);
280             if (size < 2 + st->codecpar->channels * 4)
281                 return AVERROR_INVALIDDATA;
282             st->codecpar->channel_layout = 0;
283             if (st->codecpar->channels > FF_ARRAY_ELEMS(dsd_layout)) {
284                 avpriv_request_sample(s, "channel layout");
285                 break;
286             }
287             for (i = 0; i < st->codecpar->channels; i++)
288                 dsd_layout[i] = avio_rl32(pb);
289             for (i = 0; i < FF_ARRAY_ELEMS(dsd_channel_layout); i++) {
290                 const DSDLayoutDesc * d = &dsd_channel_layout[i];
291                 if (av_get_channel_layout_nb_channels(d->layout) == st->codecpar->channels &&
292                     !memcmp(d->dsd_layout, dsd_layout, st->codecpar->channels * sizeof(uint32_t))) {
293                     st->codecpar->channel_layout = d->layout;
294                     break;
295                 }
296             }
297             break;
298
299         case MKTAG('C','M','P','R'):
300             if (size < 4)
301                 return AVERROR_INVALIDDATA;
302             st->codecpar->codec_tag = tag = avio_rl32(pb);
303             st->codecpar->codec_id = ff_codec_get_id(dsd_codec_tags, tag);
304             if (!st->codecpar->codec_id) {
305                 av_log(s, AV_LOG_ERROR, "'%s' compression is not supported\n",
306                        av_fourcc2str(tag));
307                 return AVERROR_PATCHWELCOME;
308             }
309             break;
310
311         case MKTAG('F','S',' ',' '):
312             if (size < 4)
313                 return AVERROR_INVALIDDATA;
314             st->codecpar->sample_rate = avio_rb32(pb) / 8;
315             break;
316
317         case MKTAG('I','D','3',' '):
318             ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta, size);
319             if (id3v2_extra_meta) {
320                 if ((ret = ff_id3v2_parse_apic(s, id3v2_extra_meta)) < 0 ||
321                     (ret = ff_id3v2_parse_chapters(s, id3v2_extra_meta)) < 0) {
322                     ff_id3v2_free_extra_meta(&id3v2_extra_meta);
323                     return ret;
324                 }
325                 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
326             }
327
328             if (size < avio_tell(pb) - orig_pos) {
329                 av_log(s, AV_LOG_ERROR, "id3 exceeds chunk size\n");
330                 return AVERROR_INVALIDDATA;
331             }
332             break;
333
334         case MKTAG('L','S','C','O'):
335             if (size < 2)
336                 return AVERROR_INVALIDDATA;
337             config = avio_rb16(pb);
338             if (config != 0xFFFF) {
339                 if (config < FF_ARRAY_ELEMS(dsd_loudspeaker_config))
340                     st->codecpar->channel_layout = dsd_loudspeaker_config[config];
341                 if (!st->codecpar->channel_layout)
342                     avpriv_request_sample(s, "loudspeaker configuration %d", config);
343             }
344             break;
345         }
346
347         avio_skip(pb, size - (avio_tell(pb) - orig_pos) + (size & 1));
348     }
349
350     return 0;
351 }
352
353 static int read_dst_frame(AVFormatContext *s, AVPacket *pkt)
354 {
355     IffDemuxContext *iff = s->priv_data;
356     AVIOContext *pb = s->pb;
357     uint32_t chunk_id;
358     uint64_t chunk_pos, data_pos, data_size;
359     int ret = AVERROR_EOF;
360
361     while (!avio_feof(pb)) {
362         chunk_pos = avio_tell(pb);
363         if (chunk_pos >= iff->body_end)
364             return AVERROR_EOF;
365
366         chunk_id = avio_rl32(pb);
367         data_size = iff->is_64bit ? avio_rb64(pb) : avio_rb32(pb);
368         data_pos = avio_tell(pb);
369
370         if (data_size < 1 || data_size >= INT64_MAX)
371             return AVERROR_INVALIDDATA;
372
373         switch (chunk_id) {
374         case ID_DSTF:
375             if (!pkt) {
376                 iff->body_pos  = avio_tell(pb) - (iff->is_64bit ? 12 : 8);
377                 iff->body_size = iff->body_end - iff->body_pos;
378                 return 0;
379             }
380             ret = av_get_packet(pb, pkt, data_size);
381             if (ret < 0)
382                 return ret;
383             if (data_size & 1)
384                 avio_skip(pb, 1);
385             pkt->flags |= AV_PKT_FLAG_KEY;
386             pkt->stream_index = 0;
387             pkt->duration = 588 * s->streams[0]->codecpar->sample_rate / 44100;
388             pkt->pos = chunk_pos;
389
390             chunk_pos = avio_tell(pb);
391             if (chunk_pos >= iff->body_end)
392                 return 0;
393
394             avio_seek(pb, chunk_pos, SEEK_SET);
395             return 0;
396
397         case ID_FRTE:
398             if (data_size < 4)
399                 return AVERROR_INVALIDDATA;
400             s->streams[0]->duration = avio_rb32(pb) * 588LL * s->streams[0]->codecpar->sample_rate / 44100;
401             break;
402         }
403
404         avio_skip(pb, data_size - (avio_tell(pb) - data_pos) + (data_size & 1));
405     }
406
407     return ret;
408 }
409
410 static const uint8_t deep_rgb24[] = {0, 0, 0, 3, 0, 1, 0, 8, 0, 2, 0, 8, 0, 3, 0, 8};
411 static const uint8_t deep_rgba[]  = {0, 0, 0, 4, 0, 1, 0, 8, 0, 2, 0, 8, 0, 3, 0, 8};
412 static const uint8_t deep_bgra[]  = {0, 0, 0, 4, 0, 3, 0, 8, 0, 2, 0, 8, 0, 1, 0, 8};
413 static const uint8_t deep_argb[]  = {0, 0, 0, 4, 0,17, 0, 8, 0, 1, 0, 8, 0, 2, 0, 8};
414 static const uint8_t deep_abgr[]  = {0, 0, 0, 4, 0,17, 0, 8, 0, 3, 0, 8, 0, 2, 0, 8};
415
416 static int iff_read_header(AVFormatContext *s)
417 {
418     IffDemuxContext *iff = s->priv_data;
419     AVIOContext *pb = s->pb;
420     AVStream *st;
421     uint8_t *buf;
422     uint32_t chunk_id;
423     uint64_t data_size;
424     uint32_t screenmode = 0, num, den;
425     unsigned transparency = 0;
426     unsigned masking = 0; // no mask
427     uint8_t fmt[16];
428     int fmt_size;
429
430     st = avformat_new_stream(s, NULL);
431     if (!st)
432         return AVERROR(ENOMEM);
433
434     st->codecpar->channels = 1;
435     st->codecpar->channel_layout = AV_CH_LAYOUT_MONO;
436     iff->is_64bit = avio_rl32(pb) == ID_FRM8;
437     avio_skip(pb, iff->is_64bit ? 8 : 4);
438     // codec_tag used by ByteRun1 decoder to distinguish progressive (PBM) and interlaced (ILBM) content
439     st->codecpar->codec_tag = avio_rl32(pb);
440     if (st->codecpar->codec_tag == ID_ANIM) {
441         avio_skip(pb, 12);
442     }
443     iff->bitmap_compression = -1;
444     iff->svx8_compression = -1;
445     iff->maud_bits = -1;
446     iff->maud_compression = -1;
447
448     while(!avio_feof(pb)) {
449         uint64_t orig_pos;
450         int res;
451         const char *metadata_tag = NULL;
452         int version, nb_comments, i;
453         chunk_id = avio_rl32(pb);
454         data_size = iff->is_64bit ? avio_rb64(pb) : avio_rb32(pb);
455         orig_pos = avio_tell(pb);
456
457         if (data_size >= INT64_MAX)
458             return AVERROR_INVALIDDATA;
459
460         switch(chunk_id) {
461         case ID_VHDR:
462             st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
463
464             if (data_size < 14)
465                 return AVERROR_INVALIDDATA;
466             avio_skip(pb, 12);
467             st->codecpar->sample_rate = avio_rb16(pb);
468             if (data_size >= 16) {
469                 avio_skip(pb, 1);
470                 iff->svx8_compression = avio_r8(pb);
471             }
472             break;
473
474         case ID_MHDR:
475             st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
476
477             if (data_size < 32)
478                 return AVERROR_INVALIDDATA;
479             avio_skip(pb, 4);
480             iff->maud_bits = avio_rb16(pb);
481             avio_skip(pb, 2);
482             num = avio_rb32(pb);
483             den = avio_rb16(pb);
484             if (!den)
485                 return AVERROR_INVALIDDATA;
486             avio_skip(pb, 2);
487             st->codecpar->sample_rate = num / den;
488             st->codecpar->channels = avio_rb16(pb);
489             iff->maud_compression = avio_rb16(pb);
490             if (st->codecpar->channels == 1)
491                 st->codecpar->channel_layout = AV_CH_LAYOUT_MONO;
492             else if (st->codecpar->channels == 2)
493                 st->codecpar->channel_layout = AV_CH_LAYOUT_STEREO;
494             break;
495
496         case ID_ABIT:
497         case ID_BODY:
498         case ID_DBOD:
499         case ID_DSD:
500         case ID_DST:
501         case ID_MDAT:
502             iff->body_pos = avio_tell(pb);
503             iff->body_end = iff->body_pos + data_size;
504             iff->body_size = data_size;
505             if (chunk_id == ID_DST) {
506                 int ret = read_dst_frame(s, NULL);
507                 if (ret < 0)
508                     return ret;
509             }
510             break;
511
512         case ID_CHAN:
513             if (data_size < 4)
514                 return AVERROR_INVALIDDATA;
515             if (avio_rb32(pb) < 6) {
516                 st->codecpar->channels       = 1;
517                 st->codecpar->channel_layout = AV_CH_LAYOUT_MONO;
518             } else {
519                 st->codecpar->channels       = 2;
520                 st->codecpar->channel_layout = AV_CH_LAYOUT_STEREO;
521             }
522             break;
523
524         case ID_CAMG:
525             if (data_size < 4)
526                 return AVERROR_INVALIDDATA;
527             screenmode                = avio_rb32(pb);
528             break;
529
530         case ID_CMAP:
531             if (data_size < 3 || data_size > 768 || data_size % 3) {
532                  av_log(s, AV_LOG_ERROR, "Invalid CMAP chunk size %"PRIu64"\n",
533                         data_size);
534                  return AVERROR_INVALIDDATA;
535             }
536             res = ff_alloc_extradata(st->codecpar,
537                                      data_size + IFF_EXTRA_VIDEO_SIZE);
538             if (res < 0)
539                 return res;
540             if (avio_read(pb, st->codecpar->extradata + IFF_EXTRA_VIDEO_SIZE, data_size) < 0) {
541                 av_freep(&st->codecpar->extradata);
542                 st->codecpar->extradata_size = 0;
543                 return AVERROR(EIO);
544             }
545             break;
546
547         case ID_BMHD:
548             st->codecpar->codec_type            = AVMEDIA_TYPE_VIDEO;
549             if (data_size <= 8)
550                 return AVERROR_INVALIDDATA;
551             st->codecpar->width                 = avio_rb16(pb);
552             st->codecpar->height                = avio_rb16(pb);
553             avio_skip(pb, 4); // x, y offset
554             st->codecpar->bits_per_coded_sample = avio_r8(pb);
555             if (data_size >= 10)
556                 masking                      = avio_r8(pb);
557             if (data_size >= 11)
558                 iff->bitmap_compression      = avio_r8(pb);
559             if (data_size >= 14) {
560                 avio_skip(pb, 1); // padding
561                 transparency                 = avio_rb16(pb);
562             }
563             if (data_size >= 16) {
564                 st->sample_aspect_ratio.num  = avio_r8(pb);
565                 st->sample_aspect_ratio.den  = avio_r8(pb);
566             }
567             break;
568
569         case ID_ANHD:
570             break;
571
572         case ID_DPAN:
573             avio_skip(pb, 2);
574             st->duration = avio_rb16(pb);
575             break;
576
577         case ID_DPEL:
578             if (data_size < 4 || (data_size & 3))
579                 return AVERROR_INVALIDDATA;
580             if ((fmt_size = avio_read(pb, fmt, sizeof(fmt))) < 0)
581                 return fmt_size;
582             if (fmt_size == sizeof(deep_rgb24) && !memcmp(fmt, deep_rgb24, sizeof(deep_rgb24)))
583                 st->codecpar->format = AV_PIX_FMT_RGB24;
584             else if (fmt_size == sizeof(deep_rgba) && !memcmp(fmt, deep_rgba, sizeof(deep_rgba)))
585                 st->codecpar->format = AV_PIX_FMT_RGBA;
586             else if (fmt_size == sizeof(deep_bgra) && !memcmp(fmt, deep_bgra, sizeof(deep_bgra)))
587                 st->codecpar->format = AV_PIX_FMT_BGRA;
588             else if (fmt_size == sizeof(deep_argb) && !memcmp(fmt, deep_argb, sizeof(deep_argb)))
589                 st->codecpar->format = AV_PIX_FMT_ARGB;
590             else if (fmt_size == sizeof(deep_abgr) && !memcmp(fmt, deep_abgr, sizeof(deep_abgr)))
591                 st->codecpar->format = AV_PIX_FMT_ABGR;
592             else {
593                 avpriv_request_sample(s, "color format %.16s", fmt);
594                 return AVERROR_PATCHWELCOME;
595             }
596             break;
597
598         case ID_DGBL:
599             st->codecpar->codec_type         = AVMEDIA_TYPE_VIDEO;
600             if (data_size < 8)
601                 return AVERROR_INVALIDDATA;
602             st->codecpar->width              = avio_rb16(pb);
603             st->codecpar->height             = avio_rb16(pb);
604             iff->bitmap_compression          = avio_rb16(pb);
605             st->sample_aspect_ratio.num      = avio_r8(pb);
606             st->sample_aspect_ratio.den      = avio_r8(pb);
607             st->codecpar->bits_per_coded_sample = 24;
608             break;
609
610         case ID_DLOC:
611             if (data_size < 4)
612                 return AVERROR_INVALIDDATA;
613             st->codecpar->width  = avio_rb16(pb);
614             st->codecpar->height = avio_rb16(pb);
615             break;
616
617         case ID_TVDC:
618             if (data_size < sizeof(iff->tvdc))
619                 return AVERROR_INVALIDDATA;
620             res = avio_read(pb, iff->tvdc, sizeof(iff->tvdc));
621             if (res < 0)
622                 return res;
623             break;
624
625         case ID_ANNO:
626         case ID_TEXT:      metadata_tag = "comment";   break;
627         case ID_AUTH:      metadata_tag = "artist";    break;
628         case ID_COPYRIGHT: metadata_tag = "copyright"; break;
629         case ID_NAME:      metadata_tag = "title";     break;
630
631         /* DSD tags */
632
633         case MKTAG('F','V','E','R'):
634             if (data_size < 4)
635                 return AVERROR_INVALIDDATA;
636             version = avio_rb32(pb);
637             av_log(s, AV_LOG_DEBUG, "DSIFF v%d.%d.%d.%d\n",version >> 24, (version >> 16) & 0xFF, (version >> 8) & 0xFF, version & 0xFF);
638             st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
639             break;
640
641         case MKTAG('D','I','I','N'):
642             res = parse_dsd_diin(s, st, orig_pos + data_size);
643             if (res < 0)
644                 return res;
645             break;
646
647         case MKTAG('P','R','O','P'):
648             if (data_size < 4)
649                 return AVERROR_INVALIDDATA;
650             if (avio_rl32(pb) != MKTAG('S','N','D',' ')) {
651                 avpriv_request_sample(s, "unknown property type");
652                 break;
653             }
654             res = parse_dsd_prop(s, st, orig_pos + data_size);
655             if (res < 0)
656                 return res;
657             break;
658
659         case MKTAG('C','O','M','T'):
660             if (data_size < 2)
661                 return AVERROR_INVALIDDATA;
662             nb_comments = avio_rb16(pb);
663             for (i = 0; i < nb_comments; i++) {
664                 int year, mon, day, hour, min, type, ref;
665                 char tmp[24];
666                 const char *tag;
667                 int metadata_size;
668
669                 year = avio_rb16(pb);
670                 mon  = avio_r8(pb);
671                 day  = avio_r8(pb);
672                 hour = avio_r8(pb);
673                 min  = avio_r8(pb);
674                 snprintf(tmp, sizeof(tmp), "%04d-%02d-%02d %02d:%02d", year, mon, day, hour, min);
675                 av_dict_set(&st->metadata, "comment_time", tmp, 0);
676
677                 type = avio_rb16(pb);
678                 ref  = avio_rb16(pb);
679                 switch (type) {
680                 case 1:
681                     if (!i)
682                         tag = "channel_comment";
683                     else {
684                         snprintf(tmp, sizeof(tmp), "channel%d_comment", ref);
685                         tag = tmp;
686                     }
687                     break;
688                 case 2:
689                     tag = ref < FF_ARRAY_ELEMS(dsd_source_comment) ? dsd_source_comment[ref] : "source_comment";
690                     break;
691                 case 3:
692                     tag = ref < FF_ARRAY_ELEMS(dsd_history_comment) ? dsd_history_comment[ref] : "file_history";
693                     break;
694                 default:
695                     tag = "comment";
696                 }
697
698                 metadata_size  = avio_rb32(pb);
699                 if ((res = get_metadata(s, tag, metadata_size)) < 0) {
700                     av_log(s, AV_LOG_ERROR, "cannot allocate metadata tag %s!\n", tag);
701                     return res;
702                 }
703
704                 if (metadata_size & 1)
705                     avio_skip(pb, 1);
706             }
707             break;
708         }
709
710         if (metadata_tag) {
711             if ((res = get_metadata(s, metadata_tag, data_size)) < 0) {
712                 av_log(s, AV_LOG_ERROR, "cannot allocate metadata tag %s!\n", metadata_tag);
713                 return res;
714             }
715         }
716         avio_skip(pb, data_size - (avio_tell(pb) - orig_pos) + (data_size & 1));
717     }
718
719     if (st->codecpar->codec_tag == ID_ANIM)
720         avio_seek(pb, 12, SEEK_SET);
721     else
722         avio_seek(pb, iff->body_pos, SEEK_SET);
723
724     switch(st->codecpar->codec_type) {
725     case AVMEDIA_TYPE_AUDIO:
726         avpriv_set_pts_info(st, 32, 1, st->codecpar->sample_rate);
727
728         if (st->codecpar->codec_tag == ID_16SV)
729             st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE_PLANAR;
730         else if (st->codecpar->codec_tag == ID_MAUD) {
731             if (iff->maud_bits == 8 && !iff->maud_compression) {
732                 st->codecpar->codec_id = AV_CODEC_ID_PCM_U8;
733             } else if (iff->maud_bits == 16 && !iff->maud_compression) {
734                 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
735             } else if (iff->maud_bits ==  8 && iff->maud_compression == 2) {
736                 st->codecpar->codec_id = AV_CODEC_ID_PCM_ALAW;
737             } else if (iff->maud_bits ==  8 && iff->maud_compression == 3) {
738                 st->codecpar->codec_id = AV_CODEC_ID_PCM_MULAW;
739             } else {
740                 avpriv_request_sample(s, "compression %d and bit depth %d", iff->maud_compression, iff->maud_bits);
741                 return AVERROR_PATCHWELCOME;
742             }
743         } else if (st->codecpar->codec_tag != ID_DSD &&
744                    st->codecpar->codec_tag != ID_DST) {
745             switch (iff->svx8_compression) {
746             case COMP_NONE:
747                 st->codecpar->codec_id = AV_CODEC_ID_PCM_S8_PLANAR;
748                 break;
749             case COMP_FIB:
750                 st->codecpar->codec_id = AV_CODEC_ID_8SVX_FIB;
751                 break;
752             case COMP_EXP:
753                 st->codecpar->codec_id = AV_CODEC_ID_8SVX_EXP;
754                 break;
755             default:
756                 av_log(s, AV_LOG_ERROR,
757                        "Unknown SVX8 compression method '%d'\n", iff->svx8_compression);
758                 return -1;
759             }
760         }
761
762         st->codecpar->bits_per_coded_sample = av_get_bits_per_sample(st->codecpar->codec_id);
763         st->codecpar->bit_rate = (int64_t)st->codecpar->channels * st->codecpar->sample_rate * st->codecpar->bits_per_coded_sample;
764         st->codecpar->block_align = st->codecpar->channels * st->codecpar->bits_per_coded_sample;
765         if ((st->codecpar->codec_tag == ID_DSD || st->codecpar->codec_tag == ID_MAUD) && st->codecpar->block_align <= 0)
766             return AVERROR_INVALIDDATA;
767         break;
768
769     case AVMEDIA_TYPE_VIDEO:
770         iff->bpp          = st->codecpar->bits_per_coded_sample;
771         if (st->codecpar->codec_tag == ID_ANIM)
772             avpriv_set_pts_info(st, 32, 1, 60);
773         if ((screenmode & 0x800 /* Hold And Modify */) && iff->bpp <= 8) {
774             iff->ham      = iff->bpp > 6 ? 6 : 4;
775             st->codecpar->bits_per_coded_sample = 24;
776         }
777         iff->flags        = (screenmode & 0x80 /* Extra HalfBrite */) && iff->bpp <= 8;
778         iff->masking      = masking;
779         iff->transparency = transparency;
780
781         if (!st->codecpar->extradata) {
782             int ret = ff_alloc_extradata(st->codecpar, IFF_EXTRA_VIDEO_SIZE);
783             if (ret < 0)
784                 return ret;
785         }
786         av_assert0(st->codecpar->extradata_size >= IFF_EXTRA_VIDEO_SIZE);
787         buf = st->codecpar->extradata;
788         bytestream_put_be16(&buf, IFF_EXTRA_VIDEO_SIZE);
789         bytestream_put_byte(&buf, iff->bitmap_compression);
790         bytestream_put_byte(&buf, iff->bpp);
791         bytestream_put_byte(&buf, iff->ham);
792         bytestream_put_byte(&buf, iff->flags);
793         bytestream_put_be16(&buf, iff->transparency);
794         bytestream_put_byte(&buf, iff->masking);
795         bytestream_put_buffer(&buf, iff->tvdc, sizeof(iff->tvdc));
796         st->codecpar->codec_id = AV_CODEC_ID_IFF_ILBM;
797         break;
798     default:
799         return -1;
800     }
801
802     return 0;
803 }
804
805 static unsigned get_anim_duration(uint8_t *buf, int size)
806 {
807     GetByteContext gb;
808
809     bytestream2_init(&gb, buf, size);
810     bytestream2_skip(&gb, 4);
811     while (bytestream2_get_bytes_left(&gb) > 8) {
812         unsigned chunk = bytestream2_get_le32(&gb);
813         unsigned size = bytestream2_get_be32(&gb);
814
815         if (chunk == ID_ANHD) {
816             if (size < 40)
817                 break;
818             bytestream2_skip(&gb, 14);
819             return bytestream2_get_be32(&gb);
820         } else {
821             bytestream2_skip(&gb, size + size & 1);
822         }
823     }
824     return 10;
825 }
826
827 static int iff_read_packet(AVFormatContext *s,
828                            AVPacket *pkt)
829 {
830     IffDemuxContext *iff = s->priv_data;
831     AVIOContext *pb = s->pb;
832     AVStream *st = s->streams[0];
833     int ret;
834     int64_t pos = avio_tell(pb);
835
836     if (avio_feof(pb))
837         return AVERROR_EOF;
838     if (st->codecpar->codec_tag != ID_ANIM && pos >= iff->body_end)
839         return AVERROR_EOF;
840
841     if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
842         if (st->codecpar->codec_tag == ID_DSD || st->codecpar->codec_tag == ID_MAUD) {
843             ret = av_get_packet(pb, pkt, FFMIN(iff->body_end - pos, 1024 * st->codecpar->block_align));
844         } else if (st->codecpar->codec_tag == ID_DST) {
845             return read_dst_frame(s, pkt);
846         } else {
847             if (iff->body_size > INT_MAX || !iff->body_size)
848                 return AVERROR_INVALIDDATA;
849             ret = av_get_packet(pb, pkt, iff->body_size);
850         }
851     } else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
852                st->codecpar->codec_tag  == ID_ANIM) {
853         uint64_t data_size, orig_pos;
854         uint32_t chunk_id, chunk_id2;
855
856         while (!avio_feof(pb)) {
857             if (avio_feof(pb))
858                 return AVERROR_EOF;
859
860             orig_pos  = avio_tell(pb);
861             chunk_id  = avio_rl32(pb);
862             data_size = avio_rb32(pb);
863             chunk_id2 = avio_rl32(pb);
864
865             if (chunk_id  == ID_FORM &&
866                 chunk_id2 == ID_ILBM) {
867                 avio_skip(pb, -4);
868                 break;
869             } else if (chunk_id == ID_FORM &&
870                        chunk_id2 == ID_ANIM) {
871                 continue;
872             } else {
873                 avio_skip(pb, data_size);
874             }
875         }
876         ret = av_get_packet(pb, pkt, data_size);
877         pkt->pos = orig_pos;
878         pkt->duration = get_anim_duration(pkt->data, pkt->size);
879         if (pos == 12)
880             pkt->flags |= AV_PKT_FLAG_KEY;
881     } else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
882                st->codecpar->codec_tag  != ID_ANIM) {
883         if (iff->body_size > INT_MAX || !iff->body_size)
884             return AVERROR_INVALIDDATA;
885         ret = av_get_packet(pb, pkt, iff->body_size);
886         pkt->pos = pos;
887         if (pos == iff->body_pos)
888             pkt->flags |= AV_PKT_FLAG_KEY;
889     } else {
890         av_assert0(0);
891     }
892
893     if (ret < 0)
894         return ret;
895     pkt->stream_index = 0;
896     return ret;
897 }
898
899 const AVInputFormat ff_iff_demuxer = {
900     .name           = "iff",
901     .long_name      = NULL_IF_CONFIG_SMALL("IFF (Interchange File Format)"),
902     .priv_data_size = sizeof(IffDemuxContext),
903     .read_probe     = iff_probe,
904     .read_header    = iff_read_header,
905     .read_packet    = iff_read_packet,
906     .flags          = AVFMT_GENERIC_INDEX | AVFMT_NO_BYTE_SEEK,
907 };