]> git.sesse.net Git - ffmpeg/blob - libavformat/wavdec.c
flvenc: Don't pretend to support muxing "plain" VP6
[ffmpeg] / libavformat / wavdec.c
1 /*
2  * WAV demuxer
3  * Copyright (c) 2001, 2002 Fabrice Bellard
4  *
5  * Sony Wave64 demuxer
6  * RF64 demuxer
7  * Copyright (c) 2009 Daniel Verkamp
8  *
9  * This file is part of Libav.
10  *
11  * Libav is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * Libav is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with Libav; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24  */
25
26 #include "libavutil/avassert.h"
27 #include "libavutil/dict.h"
28 #include "libavutil/log.h"
29 #include "libavutil/mathematics.h"
30 #include "libavutil/opt.h"
31 #include "avformat.h"
32 #include "avio.h"
33 #include "avio_internal.h"
34 #include "internal.h"
35 #include "metadata.h"
36 #include "pcm.h"
37 #include "riff.h"
38
39 typedef struct WAVDemuxContext {
40     int64_t data_end;
41     int w64;
42 } WAVDemuxContext;
43
44 #if CONFIG_WAV_DEMUXER
45
46 static int64_t next_tag(AVIOContext *pb, uint32_t *tag)
47 {
48     *tag = avio_rl32(pb);
49     return avio_rl32(pb);
50 }
51
52 /* RIFF chunks are always on a even offset. */
53 static int64_t wav_seek_tag(AVIOContext *s, int64_t offset, int whence)
54 {
55     return avio_seek(s, offset + (offset & 1), whence);
56 }
57
58 /* return the size of the found tag */
59 static int64_t find_tag(AVIOContext *pb, uint32_t tag1)
60 {
61     unsigned int tag;
62     int64_t size;
63
64     for (;;) {
65         if (pb->eof_reached)
66             return -1;
67         size = next_tag(pb, &tag);
68         if (tag == tag1)
69             break;
70         wav_seek_tag(pb, size, SEEK_CUR);
71     }
72     return size;
73 }
74
75 static int wav_probe(AVProbeData *p)
76 {
77     /* check file header */
78     if (p->buf_size <= 32)
79         return 0;
80     if (!memcmp(p->buf + 8, "WAVE", 4)) {
81         if (!memcmp(p->buf, "RIFF", 4))
82             /* Since the ACT demuxer has a standard WAV header at the top of
83              * its own, the returned score is decreased to avoid a probe
84              * conflict between ACT and WAV. */
85             return AVPROBE_SCORE_MAX - 1;
86         else if (!memcmp(p->buf,      "RF64", 4) &&
87                  !memcmp(p->buf + 12, "ds64", 4))
88             return AVPROBE_SCORE_MAX;
89     }
90     return 0;
91 }
92
93 static int wav_parse_fmt_tag(AVFormatContext *s, int64_t size, AVStream **st)
94 {
95     AVIOContext *pb = s->pb;
96     int ret;
97
98     /* parse fmt header */
99     *st = avformat_new_stream(s, NULL);
100     if (!*st)
101         return AVERROR(ENOMEM);
102
103     ret = ff_get_wav_header(pb, (*st)->codec, size);
104     if (ret < 0)
105         return ret;
106     (*st)->need_parsing = AVSTREAM_PARSE_FULL;
107
108     avpriv_set_pts_info(*st, 64, 1, (*st)->codec->sample_rate);
109
110     return 0;
111 }
112
113 static inline int wav_parse_bext_string(AVFormatContext *s, const char *key,
114                                         int length)
115 {
116     char temp[257];
117     int ret;
118
119     av_assert0(length <= sizeof(temp));
120     if ((ret = avio_read(s->pb, temp, length)) < 0)
121         return ret;
122
123     temp[length] = 0;
124
125     if (strlen(temp))
126         return av_dict_set(&s->metadata, key, temp, 0);
127
128     return 0;
129 }
130
131 static int wav_parse_bext_tag(AVFormatContext *s, int64_t size)
132 {
133     char temp[131], *coding_history;
134     int ret, x;
135     uint64_t time_reference;
136     int64_t umid_parts[8], umid_mask = 0;
137
138     if ((ret = wav_parse_bext_string(s, "description", 256)) < 0 ||
139         (ret = wav_parse_bext_string(s, "originator", 32)) < 0 ||
140         (ret = wav_parse_bext_string(s, "originator_reference", 32)) < 0 ||
141         (ret = wav_parse_bext_string(s, "origination_date", 10)) < 0 ||
142         (ret = wav_parse_bext_string(s, "origination_time", 8)) < 0)
143         return ret;
144
145     time_reference = avio_rl64(s->pb);
146     snprintf(temp, sizeof(temp), "%"PRIu64, time_reference);
147     if ((ret = av_dict_set(&s->metadata, "time_reference", temp, 0)) < 0)
148         return ret;
149
150     /* check if version is >= 1, in which case an UMID may be present */
151     if (avio_rl16(s->pb) >= 1) {
152         for (x = 0; x < 8; x++)
153             umid_mask |= umid_parts[x] = avio_rb64(s->pb);
154
155         if (umid_mask) {
156             /* the string formatting below is per SMPTE 330M-2004 Annex C */
157             if (umid_parts[4] == 0 && umid_parts[5] == 0 &&
158                 umid_parts[6] == 0 && umid_parts[7] == 0) {
159                 /* basic UMID */
160                 snprintf(temp, sizeof(temp),
161                          "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
162                          umid_parts[0], umid_parts[1],
163                          umid_parts[2], umid_parts[3]);
164             } else {
165                 /* extended UMID */
166                 snprintf(temp, sizeof(temp),
167                          "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64
168                          "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
169                          umid_parts[0], umid_parts[1],
170                          umid_parts[2], umid_parts[3],
171                          umid_parts[4], umid_parts[5],
172                          umid_parts[6], umid_parts[7]);
173             }
174
175             if ((ret = av_dict_set(&s->metadata, "umid", temp, 0)) < 0)
176                 return ret;
177         }
178
179         avio_skip(s->pb, 190);
180     } else
181         avio_skip(s->pb, 254);
182
183     if (size > 602) {
184         /* CodingHistory present */
185         size -= 602;
186
187         if (!(coding_history = av_malloc(size + 1)))
188             return AVERROR(ENOMEM);
189
190         if ((ret = avio_read(s->pb, coding_history, size)) < 0)
191             return ret;
192
193         coding_history[size] = 0;
194         if ((ret = av_dict_set(&s->metadata, "coding_history", coding_history,
195                                AV_DICT_DONT_STRDUP_VAL)) < 0)
196             return ret;
197     }
198
199     return 0;
200 }
201
202 static const AVMetadataConv wav_metadata_conv[] = {
203     { "description",      "comment"       },
204     { "originator",       "encoded_by"    },
205     { "origination_date", "date"          },
206     { "origination_time", "creation_time" },
207     { 0 },
208 };
209
210 /* wav input */
211 static int wav_read_header(AVFormatContext *s)
212 {
213     int64_t size, av_uninit(data_size);
214     int64_t sample_count = 0;
215     int rf64;
216     uint32_t tag;
217     AVIOContext *pb      = s->pb;
218     AVStream *st         = NULL;
219     WAVDemuxContext *wav = s->priv_data;
220     int ret, got_fmt = 0;
221     int64_t next_tag_ofs, data_ofs = -1;
222
223     /* check RIFF header */
224     tag = avio_rl32(pb);
225
226     rf64 = tag == MKTAG('R', 'F', '6', '4');
227     if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))
228         return AVERROR_INVALIDDATA;
229     avio_rl32(pb); /* file size */
230     tag = avio_rl32(pb);
231     if (tag != MKTAG('W', 'A', 'V', 'E'))
232         return AVERROR_INVALIDDATA;
233
234     if (rf64) {
235         if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
236             return AVERROR_INVALIDDATA;
237         size = avio_rl32(pb);
238         if (size < 16)
239             return AVERROR_INVALIDDATA;
240         avio_rl64(pb); /* RIFF size */
241
242         data_size    = avio_rl64(pb);
243         sample_count = avio_rl64(pb);
244
245         if (data_size < 0 || sample_count < 0) {
246             av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "
247                    "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",
248                    data_size, sample_count);
249             return AVERROR_INVALIDDATA;
250         }
251         avio_skip(pb, size - 16); /* skip rest of ds64 chunk */
252     }
253
254     for (;;) {
255         size         = next_tag(pb, &tag);
256         next_tag_ofs = avio_tell(pb) + size;
257
258         if (pb->eof_reached)
259             break;
260
261         switch (tag) {
262         case MKTAG('f', 'm', 't', ' '):
263             /* only parse the first 'fmt ' tag found */
264             if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st) < 0)) {
265                 return ret;
266             } else if (got_fmt)
267                 av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");
268
269             got_fmt = 1;
270             break;
271         case MKTAG('d', 'a', 't', 'a'):
272             if (!got_fmt) {
273                 av_log(s, AV_LOG_ERROR,
274                        "found no 'fmt ' tag before the 'data' tag\n");
275                 return AVERROR_INVALIDDATA;
276             }
277
278             if (rf64) {
279                 next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;
280             } else {
281                 data_size    = size;
282                 next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;
283             }
284
285             data_ofs = avio_tell(pb);
286
287             /* don't look for footer metadata if we can't seek or if we don't
288              * know where the data tag ends
289              */
290             if (!pb->seekable || (!rf64 && !size))
291                 goto break_loop;
292             break;
293         case MKTAG('f', 'a', 'c', 't'):
294             if (!sample_count)
295                 sample_count = avio_rl32(pb);
296             break;
297         case MKTAG('b', 'e', 'x', 't'):
298             if ((ret = wav_parse_bext_tag(s, size)) < 0)
299                 return ret;
300             break;
301         case MKTAG('L', 'I', 'S', 'T'):
302             if (size < 4) {
303                 av_log(s, AV_LOG_ERROR, "too short LIST");
304                 return AVERROR_INVALIDDATA;
305             }
306             switch (avio_rl32(pb)) {
307             case MKTAG('I', 'N', 'F', 'O'):
308                 if ((ret = ff_read_riff_info(s, size - 4)) < 0)
309                     return ret;
310             }
311             break;
312         }
313
314         /* seek to next tag unless we know that we'll run into EOF */
315         if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||
316             wav_seek_tag(pb, next_tag_ofs, SEEK_SET) < 0) {
317             break;
318         }
319     }
320
321 break_loop:
322     if (data_ofs < 0) {
323         av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");
324         return AVERROR_INVALIDDATA;
325     }
326
327     avio_seek(pb, data_ofs, SEEK_SET);
328
329     if (!sample_count && st->codec->channels &&
330         av_get_bits_per_sample(st->codec->codec_id))
331         sample_count = (data_size << 3) /
332                        (st->codec->channels *
333                         (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
334     if (sample_count)
335         st->duration = sample_count;
336
337     ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
338     ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
339
340     return 0;
341 }
342
343 /**
344  * Find chunk with w64 GUID by skipping over other chunks.
345  * @return the size of the found chunk
346  */
347 static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
348 {
349     uint8_t guid[16];
350     int64_t size;
351
352     while (!pb->eof_reached) {
353         avio_read(pb, guid, 16);
354         size = avio_rl64(pb);
355         if (size <= 24)
356             return -1;
357         if (!memcmp(guid, guid1, 16))
358             return size;
359         avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
360     }
361     return -1;
362 }
363
364 static const uint8_t guid_data[16] = {
365     'd',  'a',  't',  'a',
366     0xF3, 0xAC, 0xD3, 0x11,0x8C,  0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A
367 };
368
369 #define MAX_SIZE 4096
370
371 static int wav_read_packet(AVFormatContext *s, AVPacket *pkt)
372 {
373     int ret, size;
374     int64_t left;
375     AVStream *st;
376     WAVDemuxContext *wav = s->priv_data;
377
378     st = s->streams[0];
379
380     left = wav->data_end - avio_tell(s->pb);
381     if (left <= 0) {
382         if (CONFIG_W64_DEMUXER && wav->w64)
383             left = find_guid(s->pb, guid_data) - 24;
384         else
385             left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a'));
386         if (left < 0)
387             return AVERROR_EOF;
388         wav->data_end = avio_tell(s->pb) + left;
389     }
390
391     size = MAX_SIZE;
392     if (st->codec->block_align > 1) {
393         if (size < st->codec->block_align)
394             size = st->codec->block_align;
395         size = (size / st->codec->block_align) * st->codec->block_align;
396     }
397     size = FFMIN(size, left);
398     ret  = av_get_packet(s->pb, pkt, size);
399     if (ret < 0)
400         return ret;
401     pkt->stream_index = 0;
402
403     return ret;
404 }
405
406 static int wav_read_seek(AVFormatContext *s,
407                          int stream_index, int64_t timestamp, int flags)
408 {
409     AVStream *st;
410
411     st = s->streams[0];
412     switch (st->codec->codec_id) {
413     case AV_CODEC_ID_MP2:
414     case AV_CODEC_ID_MP3:
415     case AV_CODEC_ID_AC3:
416     case AV_CODEC_ID_DTS:
417         /* use generic seeking with dynamically generated indexes */
418         return -1;
419     default:
420         break;
421     }
422     return ff_pcm_read_seek(s, stream_index, timestamp, flags);
423 }
424
425 AVInputFormat ff_wav_demuxer = {
426     .name           = "wav",
427     .long_name      = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
428     .priv_data_size = sizeof(WAVDemuxContext),
429     .read_probe     = wav_probe,
430     .read_header    = wav_read_header,
431     .read_packet    = wav_read_packet,
432     .read_seek      = wav_read_seek,
433     .flags          = AVFMT_GENERIC_INDEX,
434     .codec_tag      = (const AVCodecTag * const []) { ff_codec_wav_tags,  0 },
435 };
436 #endif /* CONFIG_WAV_DEMUXER */
437
438 #if CONFIG_W64_DEMUXER
439 static const uint8_t guid_riff[16] = {
440     'r',  'i',  'f',  'f',
441     0x2E, 0x91, 0xCF, 0x11,0xA5,  0xD6, 0x28, 0xDB, 0x04, 0xC1, 0x00, 0x00
442 };
443
444 static const uint8_t guid_wave[16] = {
445     'w',  'a',  'v',  'e',
446     0xF3, 0xAC, 0xD3, 0x11,0x8C,  0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A
447 };
448
449 static const uint8_t guid_fmt[16] = {
450     'f',  'm',  't',  ' ',
451     0xF3, 0xAC, 0xD3, 0x11,0x8C,  0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A
452 };
453
454 static int w64_probe(AVProbeData *p)
455 {
456     if (p->buf_size <= 40)
457         return 0;
458     if (!memcmp(p->buf,      guid_riff, 16) &&
459         !memcmp(p->buf + 24, guid_wave, 16))
460         return AVPROBE_SCORE_MAX;
461     else
462         return 0;
463 }
464
465 static int w64_read_header(AVFormatContext *s)
466 {
467     int64_t size;
468     AVIOContext *pb      = s->pb;
469     WAVDemuxContext *wav = s->priv_data;
470     AVStream *st;
471     uint8_t guid[16];
472     int ret;
473
474     avio_read(pb, guid, 16);
475     if (memcmp(guid, guid_riff, 16))
476         return AVERROR_INVALIDDATA;
477
478     /* riff + wave + fmt + sizes */
479     if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8)
480         return AVERROR_INVALIDDATA;
481
482     avio_read(pb, guid, 16);
483     if (memcmp(guid, guid_wave, 16)) {
484         av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
485         return AVERROR_INVALIDDATA;
486     }
487
488     size = find_guid(pb, guid_fmt);
489     if (size < 0) {
490         av_log(s, AV_LOG_ERROR, "could not find fmt guid\n");
491         return AVERROR_INVALIDDATA;
492     }
493
494     st = avformat_new_stream(s, NULL);
495     if (!st)
496         return AVERROR(ENOMEM);
497
498     /* subtract chunk header size - normal wav file doesn't count it */
499     ret = ff_get_wav_header(pb, st->codec, size - 24);
500     if (ret < 0)
501         return ret;
502     avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
503
504     st->need_parsing = AVSTREAM_PARSE_FULL;
505
506     avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
507
508     size = find_guid(pb, guid_data);
509     if (size < 0) {
510         av_log(s, AV_LOG_ERROR, "could not find data guid\n");
511         return AVERROR_INVALIDDATA;
512     }
513     wav->data_end = avio_tell(pb) + size - 24;
514     wav->w64      = 1;
515
516     return 0;
517 }
518
519 AVInputFormat ff_w64_demuxer = {
520     .name           = "w64",
521     .long_name      = NULL_IF_CONFIG_SMALL("Sony Wave64"),
522     .priv_data_size = sizeof(WAVDemuxContext),
523     .read_probe     = w64_probe,
524     .read_header    = w64_read_header,
525     .read_packet    = wav_read_packet,
526     .read_seek      = wav_read_seek,
527     .flags          = AVFMT_GENERIC_INDEX,
528     .codec_tag      = (const AVCodecTag * const []) { ff_codec_wav_tags, 0 },
529 };
530 #endif /* CONFIG_W64_DEMUXER */