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