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