]> git.sesse.net Git - ffmpeg/blob - libavformat/wavdec.c
Merge commit '3fb78e99a04d0ed8db834d813d933eb86c37142a'
[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 FFmpeg.
10  *
11  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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/intreadwrite.h"
29 #include "libavutil/log.h"
30 #include "libavutil/mathematics.h"
31 #include "libavutil/opt.h"
32 #include "avformat.h"
33 #include "avio.h"
34 #include "avio_internal.h"
35 #include "internal.h"
36 #include "metadata.h"
37 #include "pcm.h"
38 #include "riff.h"
39 #include "w64.h"
40 #include "spdif.h"
41
42 typedef struct WAVDemuxContext {
43     const AVClass *class;
44     int64_t data_end;
45     int w64;
46     int64_t smv_data_ofs;
47     int smv_block_size;
48     int smv_frames_per_jpeg;
49     int smv_block;
50     int smv_last_stream;
51     int smv_eof;
52     int audio_eof;
53     int ignore_length;
54     int spdif;
55     int smv_cur_pt;
56     int smv_given_first;
57     int unaligned; // e.g. if an odd number of bytes ID3 tag was prepended
58 } WAVDemuxContext;
59
60 #if CONFIG_WAV_DEMUXER
61
62 static int64_t next_tag(AVIOContext *pb, uint32_t *tag)
63 {
64     *tag = avio_rl32(pb);
65     return avio_rl32(pb);
66 }
67
68 /* RIFF chunks are always at even offsets relative to where they start. */
69 static int64_t wav_seek_tag(WAVDemuxContext * wav, AVIOContext *s, int64_t offset, int whence)
70 {
71     offset += offset < INT64_MAX && offset + wav->unaligned & 1;
72
73     return avio_seek(s, offset, whence);
74 }
75
76 /* return the size of the found tag */
77 static int64_t find_tag(WAVDemuxContext * wav, AVIOContext *pb, uint32_t tag1)
78 {
79     unsigned int tag;
80     int64_t size;
81
82     for (;;) {
83         if (url_feof(pb))
84             return AVERROR_EOF;
85         size = next_tag(pb, &tag);
86         if (tag == tag1)
87             break;
88         wav_seek_tag(wav, pb, size, SEEK_CUR);
89     }
90     return size;
91 }
92
93 static int wav_probe(AVProbeData *p)
94 {
95     /* check file header */
96     if (p->buf_size <= 32)
97         return 0;
98     if (!memcmp(p->buf + 8, "WAVE", 4)) {
99         if (!memcmp(p->buf, "RIFF", 4))
100             /* Since the ACT demuxer has a standard WAV header at the top of
101              * its own, the returned score is decreased to avoid a probe
102              * conflict between ACT and WAV. */
103             return AVPROBE_SCORE_MAX - 1;
104         else if (!memcmp(p->buf,      "RF64", 4) &&
105                  !memcmp(p->buf + 12, "ds64", 4))
106             return AVPROBE_SCORE_MAX;
107     }
108     return 0;
109 }
110
111 static void handle_stream_probing(AVStream *st)
112 {
113     if (st->codec->codec_id == AV_CODEC_ID_PCM_S16LE) {
114         st->request_probe = AVPROBE_SCORE_EXTENSION;
115         st->probe_packets = FFMIN(st->probe_packets, 4);
116     }
117 }
118
119 static int wav_parse_fmt_tag(AVFormatContext *s, int64_t size, AVStream **st)
120 {
121     AVIOContext *pb = s->pb;
122     int ret;
123
124     /* parse fmt header */
125     *st = avformat_new_stream(s, NULL);
126     if (!*st)
127         return AVERROR(ENOMEM);
128
129     ret = ff_get_wav_header(pb, (*st)->codec, size);
130     if (ret < 0)
131         return ret;
132     handle_stream_probing(*st);
133
134     (*st)->need_parsing = AVSTREAM_PARSE_FULL_RAW;
135
136     avpriv_set_pts_info(*st, 64, 1, (*st)->codec->sample_rate);
137
138     return 0;
139 }
140
141 static inline int wav_parse_bext_string(AVFormatContext *s, const char *key,
142                                         int length)
143 {
144     char temp[257];
145     int ret;
146
147     av_assert0(length <= sizeof(temp));
148     if ((ret = avio_read(s->pb, temp, length)) < 0)
149         return ret;
150
151     temp[length] = 0;
152
153     if (strlen(temp))
154         return av_dict_set(&s->metadata, key, temp, 0);
155
156     return 0;
157 }
158
159 static int wav_parse_bext_tag(AVFormatContext *s, int64_t size)
160 {
161     char temp[131], *coding_history;
162     int ret, x;
163     uint64_t time_reference;
164     int64_t umid_parts[8], umid_mask = 0;
165
166     if ((ret = wav_parse_bext_string(s, "description", 256)) < 0 ||
167         (ret = wav_parse_bext_string(s, "originator", 32)) < 0 ||
168         (ret = wav_parse_bext_string(s, "originator_reference", 32)) < 0 ||
169         (ret = wav_parse_bext_string(s, "origination_date", 10)) < 0 ||
170         (ret = wav_parse_bext_string(s, "origination_time", 8)) < 0)
171         return ret;
172
173     time_reference = avio_rl64(s->pb);
174     snprintf(temp, sizeof(temp), "%"PRIu64, time_reference);
175     if ((ret = av_dict_set(&s->metadata, "time_reference", temp, 0)) < 0)
176         return ret;
177
178     /* check if version is >= 1, in which case an UMID may be present */
179     if (avio_rl16(s->pb) >= 1) {
180         for (x = 0; x < 8; x++)
181             umid_mask |= umid_parts[x] = avio_rb64(s->pb);
182
183         if (umid_mask) {
184             /* the string formatting below is per SMPTE 330M-2004 Annex C */
185             if (umid_parts[4] == 0 && umid_parts[5] == 0 &&
186                 umid_parts[6] == 0 && umid_parts[7] == 0) {
187                 /* basic UMID */
188                 snprintf(temp, sizeof(temp),
189                          "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
190                          umid_parts[0], umid_parts[1],
191                          umid_parts[2], umid_parts[3]);
192             } else {
193                 /* extended UMID */
194                 snprintf(temp, sizeof(temp),
195                          "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64
196                          "%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
197                          umid_parts[0], umid_parts[1],
198                          umid_parts[2], umid_parts[3],
199                          umid_parts[4], umid_parts[5],
200                          umid_parts[6], umid_parts[7]);
201             }
202
203             if ((ret = av_dict_set(&s->metadata, "umid", temp, 0)) < 0)
204                 return ret;
205         }
206
207         avio_skip(s->pb, 190);
208     } else
209         avio_skip(s->pb, 254);
210
211     if (size > 602) {
212         /* CodingHistory present */
213         size -= 602;
214
215         if (!(coding_history = av_malloc(size + 1)))
216             return AVERROR(ENOMEM);
217
218         if ((ret = avio_read(s->pb, coding_history, size)) < 0)
219             return ret;
220
221         coding_history[size] = 0;
222         if ((ret = av_dict_set(&s->metadata, "coding_history", coding_history,
223                                AV_DICT_DONT_STRDUP_VAL)) < 0)
224             return ret;
225     }
226
227     return 0;
228 }
229
230 static const AVMetadataConv wav_metadata_conv[] = {
231     { "description",      "comment"       },
232     { "originator",       "encoded_by"    },
233     { "origination_date", "date"          },
234     { "origination_time", "creation_time" },
235     { 0 },
236 };
237
238 /* wav input */
239 static int wav_read_header(AVFormatContext *s)
240 {
241     int64_t size, av_uninit(data_size);
242     int64_t sample_count = 0;
243     int rf64;
244     uint32_t tag;
245     AVIOContext *pb      = s->pb;
246     AVStream *st         = NULL;
247     WAVDemuxContext *wav = s->priv_data;
248     int ret, got_fmt = 0;
249     int64_t next_tag_ofs, data_ofs = -1;
250
251     wav->unaligned = avio_tell(s->pb) & 1;
252
253     wav->smv_data_ofs = -1;
254
255     /* check RIFF header */
256     tag = avio_rl32(pb);
257
258     rf64 = tag == MKTAG('R', 'F', '6', '4');
259     if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))
260         return AVERROR_INVALIDDATA;
261     avio_rl32(pb); /* file size */
262     tag = avio_rl32(pb);
263     if (tag != MKTAG('W', 'A', 'V', 'E'))
264         return AVERROR_INVALIDDATA;
265
266     if (rf64) {
267         if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
268             return AVERROR_INVALIDDATA;
269         size = avio_rl32(pb);
270         if (size < 24)
271             return AVERROR_INVALIDDATA;
272         avio_rl64(pb); /* RIFF size */
273
274         data_size    = avio_rl64(pb);
275         sample_count = avio_rl64(pb);
276
277         if (data_size < 0 || sample_count < 0) {
278             av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "
279                    "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",
280                    data_size, sample_count);
281             return AVERROR_INVALIDDATA;
282         }
283         avio_skip(pb, size - 24); /* skip rest of ds64 chunk */
284
285     }
286
287     for (;;) {
288         AVStream *vst;
289         size         = next_tag(pb, &tag);
290         next_tag_ofs = avio_tell(pb) + size;
291
292         if (url_feof(pb))
293             break;
294
295         switch (tag) {
296         case MKTAG('f', 'm', 't', ' '):
297             /* only parse the first 'fmt ' tag found */
298             if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st)) < 0) {
299                 return ret;
300             } else if (got_fmt)
301                 av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");
302
303             got_fmt = 1;
304             break;
305         case MKTAG('d', 'a', 't', 'a'):
306             if (!got_fmt) {
307                 av_log(s, AV_LOG_ERROR,
308                        "found no 'fmt ' tag before the 'data' tag\n");
309                 return AVERROR_INVALIDDATA;
310             }
311
312             if (rf64) {
313                 next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;
314             } else {
315                 data_size    = size;
316                 next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;
317             }
318
319             data_ofs = avio_tell(pb);
320
321             /* don't look for footer metadata if we can't seek or if we don't
322              * know where the data tag ends
323              */
324             if (!pb->seekable || (!rf64 && !size))
325                 goto break_loop;
326             break;
327         case MKTAG('f', 'a', 'c', 't'):
328             if (!sample_count)
329                 sample_count = avio_rl32(pb);
330             break;
331         case MKTAG('b', 'e', 'x', 't'):
332             if ((ret = wav_parse_bext_tag(s, size)) < 0)
333                 return ret;
334             break;
335         case MKTAG('S','M','V','0'):
336             if (!got_fmt) {
337                 av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'SMV0' tag\n");
338                 return AVERROR_INVALIDDATA;
339             }
340             // SMV file, a wav file with video appended.
341             if (size != MKTAG('0','2','0','0')) {
342                 av_log(s, AV_LOG_ERROR, "Unknown SMV version found\n");
343                 goto break_loop;
344             }
345             av_log(s, AV_LOG_DEBUG, "Found SMV data\n");
346             wav->smv_given_first = 0;
347             vst = avformat_new_stream(s, NULL);
348             if (!vst)
349                 return AVERROR(ENOMEM);
350             avio_r8(pb);
351             vst->id = 1;
352             vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
353             vst->codec->codec_id = AV_CODEC_ID_SMVJPEG;
354             vst->codec->width  = avio_rl24(pb);
355             vst->codec->height = avio_rl24(pb);
356             vst->codec->extradata_size = 4;
357             vst->codec->extradata = av_malloc(vst->codec->extradata_size +
358                                               FF_INPUT_BUFFER_PADDING_SIZE);
359             if (!vst->codec->extradata) {
360                 av_log(s, AV_LOG_ERROR, "Could not allocate extradata.\n");
361                 return AVERROR(ENOMEM);
362             }
363             size = avio_rl24(pb);
364             wav->smv_data_ofs = avio_tell(pb) + (size - 5) * 3;
365             avio_rl24(pb);
366             wav->smv_block_size = avio_rl24(pb);
367             avpriv_set_pts_info(vst, 32, 1, avio_rl24(pb));
368             vst->duration = avio_rl24(pb);
369             avio_rl24(pb);
370             avio_rl24(pb);
371             wav->smv_frames_per_jpeg = avio_rl24(pb);
372             if (wav->smv_frames_per_jpeg > 65536) {
373                 av_log(s, AV_LOG_ERROR, "too many frames per jpeg\n");
374                 return AVERROR_INVALIDDATA;
375             }
376             AV_WL32(vst->codec->extradata, wav->smv_frames_per_jpeg);
377             wav->smv_cur_pt = 0;
378             goto break_loop;
379         case MKTAG('L', 'I', 'S', 'T'):
380             if (size < 4) {
381                 av_log(s, AV_LOG_ERROR, "too short LIST tag\n");
382                 return AVERROR_INVALIDDATA;
383             }
384             switch (avio_rl32(pb)) {
385             case MKTAG('I', 'N', 'F', 'O'):
386                 ff_read_riff_info(s, size - 4);
387             }
388             break;
389         }
390
391         /* seek to next tag unless we know that we'll run into EOF */
392         if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||
393             wav_seek_tag(wav, pb, next_tag_ofs, SEEK_SET) < 0) {
394             break;
395         }
396     }
397
398 break_loop:
399     if (data_ofs < 0) {
400         av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");
401         return AVERROR_INVALIDDATA;
402     }
403
404     avio_seek(pb, data_ofs, SEEK_SET);
405
406     if (!sample_count && st->codec->channels &&
407         av_get_bits_per_sample(st->codec->codec_id) && wav->data_end <= avio_size(pb))
408         sample_count = (data_size << 3) /
409                        (st->codec->channels *
410                         (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
411     if (sample_count)
412         st->duration = sample_count;
413
414     ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
415     ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
416
417     return 0;
418 }
419
420 /**
421  * Find chunk with w64 GUID by skipping over other chunks.
422  * @return the size of the found chunk
423  */
424 static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
425 {
426     uint8_t guid[16];
427     int64_t size;
428
429     while (!url_feof(pb)) {
430         avio_read(pb, guid, 16);
431         size = avio_rl64(pb);
432         if (size <= 24)
433             return AVERROR_INVALIDDATA;
434         if (!memcmp(guid, guid1, 16))
435             return size;
436         avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
437     }
438     return AVERROR_EOF;
439 }
440
441 #define MAX_SIZE 4096
442
443 static int wav_read_packet(AVFormatContext *s, AVPacket *pkt)
444 {
445     int ret, size;
446     int64_t left;
447     AVStream *st;
448     WAVDemuxContext *wav = s->priv_data;
449
450     if (CONFIG_SPDIF_DEMUXER && wav->spdif == 0 &&
451         s->streams[0]->codec->codec_tag == 1) {
452         enum AVCodecID codec;
453         ret = ff_spdif_probe(s->pb->buffer, s->pb->buf_end - s->pb->buffer,
454                              &codec);
455         if (ret > AVPROBE_SCORE_EXTENSION) {
456             s->streams[0]->codec->codec_id = codec;
457             wav->spdif = 1;
458         } else {
459             wav->spdif = -1;
460         }
461     }
462     if (CONFIG_SPDIF_DEMUXER && wav->spdif == 1)
463         return ff_spdif_read_packet(s, pkt);
464
465     if (wav->smv_data_ofs > 0) {
466         int64_t audio_dts, video_dts;
467 smv_retry:
468         audio_dts = s->streams[0]->cur_dts;
469         video_dts = s->streams[1]->cur_dts;
470
471         if (audio_dts != AV_NOPTS_VALUE && video_dts != AV_NOPTS_VALUE) {
472             /*We always return a video frame first to get the pixel format first*/
473             wav->smv_last_stream = wav->smv_given_first ?
474                 av_compare_ts(video_dts, s->streams[1]->time_base,
475                               audio_dts, s->streams[0]->time_base) > 0 : 0;
476             wav->smv_given_first = 1;
477         }
478         wav->smv_last_stream = !wav->smv_last_stream;
479         wav->smv_last_stream |= wav->audio_eof;
480         wav->smv_last_stream &= !wav->smv_eof;
481         if (wav->smv_last_stream) {
482             uint64_t old_pos = avio_tell(s->pb);
483             uint64_t new_pos = wav->smv_data_ofs +
484                 wav->smv_block * wav->smv_block_size;
485             if (avio_seek(s->pb, new_pos, SEEK_SET) < 0) {
486                 ret = AVERROR_EOF;
487                 goto smv_out;
488             }
489             size = avio_rl24(s->pb);
490             ret  = av_get_packet(s->pb, pkt, size);
491             if (ret < 0)
492                 goto smv_out;
493             pkt->pos -= 3;
494             pkt->pts = wav->smv_block * wav->smv_frames_per_jpeg + wav->smv_cur_pt;
495             wav->smv_cur_pt++;
496             if (wav->smv_frames_per_jpeg > 0)
497                 wav->smv_cur_pt %= wav->smv_frames_per_jpeg;
498             if (!wav->smv_cur_pt)
499                 wav->smv_block++;
500
501             pkt->stream_index = 1;
502 smv_out:
503             avio_seek(s->pb, old_pos, SEEK_SET);
504             if (ret == AVERROR_EOF) {
505                 wav->smv_eof = 1;
506                 goto smv_retry;
507             }
508             return ret;
509         }
510     }
511
512     st = s->streams[0];
513
514     left = wav->data_end - avio_tell(s->pb);
515     if (wav->ignore_length)
516         left = INT_MAX;
517     if (left <= 0) {
518         if (CONFIG_W64_DEMUXER && wav->w64)
519             left = find_guid(s->pb, ff_w64_guid_data) - 24;
520         else
521             left = find_tag(wav, s->pb, MKTAG('d', 'a', 't', 'a'));
522         if (left < 0) {
523             wav->audio_eof = 1;
524             if (wav->smv_data_ofs > 0 && !wav->smv_eof)
525                 goto smv_retry;
526             return AVERROR_EOF;
527         }
528         wav->data_end = avio_tell(s->pb) + left;
529     }
530
531     size = MAX_SIZE;
532     if (st->codec->block_align > 1) {
533         if (size < st->codec->block_align)
534             size = st->codec->block_align;
535         size = (size / st->codec->block_align) * st->codec->block_align;
536     }
537     size = FFMIN(size, left);
538     ret  = av_get_packet(s->pb, pkt, size);
539     if (ret < 0)
540         return ret;
541     pkt->stream_index = 0;
542
543     return ret;
544 }
545
546 static int wav_read_seek(AVFormatContext *s,
547                          int stream_index, int64_t timestamp, int flags)
548 {
549     WAVDemuxContext *wav = s->priv_data;
550     AVStream *st;
551     wav->smv_eof = 0;
552     wav->audio_eof = 0;
553     if (wav->smv_data_ofs > 0) {
554         int64_t smv_timestamp = timestamp;
555         if (stream_index == 0)
556             smv_timestamp = av_rescale_q(timestamp, s->streams[0]->time_base, s->streams[1]->time_base);
557         else
558             timestamp = av_rescale_q(smv_timestamp, s->streams[1]->time_base, s->streams[0]->time_base);
559         if (wav->smv_frames_per_jpeg > 0) {
560             wav->smv_block = smv_timestamp / wav->smv_frames_per_jpeg;
561             wav->smv_cur_pt = smv_timestamp % wav->smv_frames_per_jpeg;
562         }
563     }
564
565     st = s->streams[0];
566     switch (st->codec->codec_id) {
567     case AV_CODEC_ID_MP2:
568     case AV_CODEC_ID_MP3:
569     case AV_CODEC_ID_AC3:
570     case AV_CODEC_ID_DTS:
571         /* use generic seeking with dynamically generated indexes */
572         return -1;
573     default:
574         break;
575     }
576     return ff_pcm_read_seek(s, stream_index, timestamp, flags);
577 }
578
579 #define OFFSET(x) offsetof(WAVDemuxContext, x)
580 #define DEC AV_OPT_FLAG_DECODING_PARAM
581 static const AVOption demux_options[] = {
582     { "ignore_length", "Ignore length", OFFSET(ignore_length), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, DEC },
583     { NULL },
584 };
585
586 static const AVClass wav_demuxer_class = {
587     .class_name = "WAV demuxer",
588     .item_name  = av_default_item_name,
589     .option     = demux_options,
590     .version    = LIBAVUTIL_VERSION_INT,
591 };
592 AVInputFormat ff_wav_demuxer = {
593     .name           = "wav",
594     .long_name      = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
595     .priv_data_size = sizeof(WAVDemuxContext),
596     .read_probe     = wav_probe,
597     .read_header    = wav_read_header,
598     .read_packet    = wav_read_packet,
599     .read_seek      = wav_read_seek,
600     .flags          = AVFMT_GENERIC_INDEX,
601     .codec_tag      = (const AVCodecTag * const []) { ff_codec_wav_tags,  0 },
602     .priv_class     = &wav_demuxer_class,
603 };
604 #endif /* CONFIG_WAV_DEMUXER */
605
606 #if CONFIG_W64_DEMUXER
607 static int w64_probe(AVProbeData *p)
608 {
609     if (p->buf_size <= 40)
610         return 0;
611     if (!memcmp(p->buf,      ff_w64_guid_riff, 16) &&
612         !memcmp(p->buf + 24, ff_w64_guid_wave, 16))
613         return AVPROBE_SCORE_MAX;
614     else
615         return 0;
616 }
617
618 static int w64_read_header(AVFormatContext *s)
619 {
620     int64_t size, data_ofs = 0;
621     AVIOContext *pb      = s->pb;
622     WAVDemuxContext *wav = s->priv_data;
623     AVStream *st;
624     uint8_t guid[16];
625     int ret;
626
627     avio_read(pb, guid, 16);
628     if (memcmp(guid, ff_w64_guid_riff, 16))
629         return AVERROR_INVALIDDATA;
630
631     /* riff + wave + fmt + sizes */
632     if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8)
633         return AVERROR_INVALIDDATA;
634
635     avio_read(pb, guid, 16);
636     if (memcmp(guid, ff_w64_guid_wave, 16)) {
637         av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
638         return AVERROR_INVALIDDATA;
639     }
640
641     wav->w64 = 1;
642
643     st = avformat_new_stream(s, NULL);
644     if (!st)
645         return AVERROR(ENOMEM);
646
647     while (!url_feof(pb)) {
648         if (avio_read(pb, guid, 16) != 16)
649             break;
650         size = avio_rl64(pb);
651         if (size <= 24 || INT64_MAX - size < avio_tell(pb))
652             return AVERROR_INVALIDDATA;
653
654         if (!memcmp(guid, ff_w64_guid_fmt, 16)) {
655             /* subtract chunk header size - normal wav file doesn't count it */
656             ret = ff_get_wav_header(pb, st->codec, size - 24);
657             if (ret < 0)
658                 return ret;
659             avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
660
661             avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
662         } else if (!memcmp(guid, ff_w64_guid_fact, 16)) {
663             int64_t samples;
664
665             samples = avio_rl64(pb);
666             if (samples > 0)
667                 st->duration = samples;
668         } else if (!memcmp(guid, ff_w64_guid_data, 16)) {
669             wav->data_end = avio_tell(pb) + size - 24;
670
671             data_ofs = avio_tell(pb);
672             if (!pb->seekable)
673                 break;
674
675             avio_skip(pb, size - 24);
676         } else if (!memcmp(guid, ff_w64_guid_summarylist, 16)) {
677             int64_t start, end, cur;
678             uint32_t count, chunk_size, i;
679
680             start = avio_tell(pb);
681             end = start + FFALIGN(size, INT64_C(8)) - 24;
682             count = avio_rl32(pb);
683
684             for (i = 0; i < count; i++) {
685                 char chunk_key[5], *value;
686
687                 if (url_feof(pb) || (cur = avio_tell(pb)) < 0 || cur > end - 8 /* = tag + size */)
688                     break;
689
690                 chunk_key[4] = 0;
691                 avio_read(pb, chunk_key, 4);
692                 chunk_size = avio_rl32(pb);
693
694                 value = av_mallocz(chunk_size + 1);
695                 if (!value)
696                     return AVERROR(ENOMEM);
697
698                 ret = avio_get_str16le(pb, chunk_size, value, chunk_size);
699                 avio_skip(pb, chunk_size - ret);
700
701                 av_dict_set(&s->metadata, chunk_key, value, AV_DICT_DONT_STRDUP_VAL);
702             }
703
704             avio_skip(pb, end - avio_tell(pb));
705         } else {
706             av_log(s, AV_LOG_DEBUG, "unknown guid: "FF_PRI_GUID"\n", FF_ARG_GUID(guid));
707             avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
708         }
709     }
710
711     if (!data_ofs)
712         return AVERROR_EOF;
713
714     ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
715     ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
716
717     handle_stream_probing(st);
718     st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
719
720     avio_seek(pb, data_ofs, SEEK_SET);
721
722     return 0;
723 }
724
725 AVInputFormat ff_w64_demuxer = {
726     .name           = "w64",
727     .long_name      = NULL_IF_CONFIG_SMALL("Sony Wave64"),
728     .priv_data_size = sizeof(WAVDemuxContext),
729     .read_probe     = w64_probe,
730     .read_header    = w64_read_header,
731     .read_packet    = wav_read_packet,
732     .read_seek      = wav_read_seek,
733     .flags          = AVFMT_GENERIC_INDEX,
734     .codec_tag      = (const AVCodecTag * const []) { ff_codec_wav_tags, 0 },
735 };
736 #endif /* CONFIG_W64_DEMUXER */