]> git.sesse.net Git - ffmpeg/blob - libavformat/wavdec.c
Merge remote-tracking branch 'qatar/master'
[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 || av_get_exact_bits_per_sample(st->codec->codec_id) > 0)
407         if (   st->codec->channels
408             && data_size
409             && av_get_bits_per_sample(st->codec->codec_id)
410             && wav->data_end <= avio_size(pb))
411             sample_count = (data_size << 3)
412                                   /
413                 (st->codec->channels * (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
414
415     if (sample_count)
416         st->duration = sample_count;
417
418     ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
419     ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
420
421     return 0;
422 }
423
424 /**
425  * Find chunk with w64 GUID by skipping over other chunks.
426  * @return the size of the found chunk
427  */
428 static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
429 {
430     uint8_t guid[16];
431     int64_t size;
432
433     while (!url_feof(pb)) {
434         avio_read(pb, guid, 16);
435         size = avio_rl64(pb);
436         if (size <= 24)
437             return AVERROR_INVALIDDATA;
438         if (!memcmp(guid, guid1, 16))
439             return size;
440         avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
441     }
442     return AVERROR_EOF;
443 }
444
445 #define MAX_SIZE 4096
446
447 static int wav_read_packet(AVFormatContext *s, AVPacket *pkt)
448 {
449     int ret, size;
450     int64_t left;
451     AVStream *st;
452     WAVDemuxContext *wav = s->priv_data;
453
454     if (CONFIG_SPDIF_DEMUXER && wav->spdif == 0 &&
455         s->streams[0]->codec->codec_tag == 1) {
456         enum AVCodecID codec;
457         ret = ff_spdif_probe(s->pb->buffer, s->pb->buf_end - s->pb->buffer,
458                              &codec);
459         if (ret > AVPROBE_SCORE_EXTENSION) {
460             s->streams[0]->codec->codec_id = codec;
461             wav->spdif = 1;
462         } else {
463             wav->spdif = -1;
464         }
465     }
466     if (CONFIG_SPDIF_DEMUXER && wav->spdif == 1)
467         return ff_spdif_read_packet(s, pkt);
468
469     if (wav->smv_data_ofs > 0) {
470         int64_t audio_dts, video_dts;
471 smv_retry:
472         audio_dts = s->streams[0]->cur_dts;
473         video_dts = s->streams[1]->cur_dts;
474
475         if (audio_dts != AV_NOPTS_VALUE && video_dts != AV_NOPTS_VALUE) {
476             /*We always return a video frame first to get the pixel format first*/
477             wav->smv_last_stream = wav->smv_given_first ?
478                 av_compare_ts(video_dts, s->streams[1]->time_base,
479                               audio_dts, s->streams[0]->time_base) > 0 : 0;
480             wav->smv_given_first = 1;
481         }
482         wav->smv_last_stream = !wav->smv_last_stream;
483         wav->smv_last_stream |= wav->audio_eof;
484         wav->smv_last_stream &= !wav->smv_eof;
485         if (wav->smv_last_stream) {
486             uint64_t old_pos = avio_tell(s->pb);
487             uint64_t new_pos = wav->smv_data_ofs +
488                 wav->smv_block * wav->smv_block_size;
489             if (avio_seek(s->pb, new_pos, SEEK_SET) < 0) {
490                 ret = AVERROR_EOF;
491                 goto smv_out;
492             }
493             size = avio_rl24(s->pb);
494             ret  = av_get_packet(s->pb, pkt, size);
495             if (ret < 0)
496                 goto smv_out;
497             pkt->pos -= 3;
498             pkt->pts = wav->smv_block * wav->smv_frames_per_jpeg + wav->smv_cur_pt;
499             wav->smv_cur_pt++;
500             if (wav->smv_frames_per_jpeg > 0)
501                 wav->smv_cur_pt %= wav->smv_frames_per_jpeg;
502             if (!wav->smv_cur_pt)
503                 wav->smv_block++;
504
505             pkt->stream_index = 1;
506 smv_out:
507             avio_seek(s->pb, old_pos, SEEK_SET);
508             if (ret == AVERROR_EOF) {
509                 wav->smv_eof = 1;
510                 goto smv_retry;
511             }
512             return ret;
513         }
514     }
515
516     st = s->streams[0];
517
518     left = wav->data_end - avio_tell(s->pb);
519     if (wav->ignore_length)
520         left = INT_MAX;
521     if (left <= 0) {
522         if (CONFIG_W64_DEMUXER && wav->w64)
523             left = find_guid(s->pb, ff_w64_guid_data) - 24;
524         else
525             left = find_tag(wav, s->pb, MKTAG('d', 'a', 't', 'a'));
526         if (left < 0) {
527             wav->audio_eof = 1;
528             if (wav->smv_data_ofs > 0 && !wav->smv_eof)
529                 goto smv_retry;
530             return AVERROR_EOF;
531         }
532         wav->data_end = avio_tell(s->pb) + left;
533     }
534
535     size = MAX_SIZE;
536     if (st->codec->block_align > 1) {
537         if (size < st->codec->block_align)
538             size = st->codec->block_align;
539         size = (size / st->codec->block_align) * st->codec->block_align;
540     }
541     size = FFMIN(size, left);
542     ret  = av_get_packet(s->pb, pkt, size);
543     if (ret < 0)
544         return ret;
545     pkt->stream_index = 0;
546
547     return ret;
548 }
549
550 static int wav_read_seek(AVFormatContext *s,
551                          int stream_index, int64_t timestamp, int flags)
552 {
553     WAVDemuxContext *wav = s->priv_data;
554     AVStream *st;
555     wav->smv_eof = 0;
556     wav->audio_eof = 0;
557     if (wav->smv_data_ofs > 0) {
558         int64_t smv_timestamp = timestamp;
559         if (stream_index == 0)
560             smv_timestamp = av_rescale_q(timestamp, s->streams[0]->time_base, s->streams[1]->time_base);
561         else
562             timestamp = av_rescale_q(smv_timestamp, s->streams[1]->time_base, s->streams[0]->time_base);
563         if (wav->smv_frames_per_jpeg > 0) {
564             wav->smv_block = smv_timestamp / wav->smv_frames_per_jpeg;
565             wav->smv_cur_pt = smv_timestamp % wav->smv_frames_per_jpeg;
566         }
567     }
568
569     st = s->streams[0];
570     switch (st->codec->codec_id) {
571     case AV_CODEC_ID_MP2:
572     case AV_CODEC_ID_MP3:
573     case AV_CODEC_ID_AC3:
574     case AV_CODEC_ID_DTS:
575         /* use generic seeking with dynamically generated indexes */
576         return -1;
577     default:
578         break;
579     }
580     return ff_pcm_read_seek(s, stream_index, timestamp, flags);
581 }
582
583 #define OFFSET(x) offsetof(WAVDemuxContext, x)
584 #define DEC AV_OPT_FLAG_DECODING_PARAM
585 static const AVOption demux_options[] = {
586     { "ignore_length", "Ignore length", OFFSET(ignore_length), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, DEC },
587     { NULL },
588 };
589
590 static const AVClass wav_demuxer_class = {
591     .class_name = "WAV demuxer",
592     .item_name  = av_default_item_name,
593     .option     = demux_options,
594     .version    = LIBAVUTIL_VERSION_INT,
595 };
596 AVInputFormat ff_wav_demuxer = {
597     .name           = "wav",
598     .long_name      = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
599     .priv_data_size = sizeof(WAVDemuxContext),
600     .read_probe     = wav_probe,
601     .read_header    = wav_read_header,
602     .read_packet    = wav_read_packet,
603     .read_seek      = wav_read_seek,
604     .flags          = AVFMT_GENERIC_INDEX,
605     .codec_tag      = (const AVCodecTag * const []) { ff_codec_wav_tags,  0 },
606     .priv_class     = &wav_demuxer_class,
607 };
608 #endif /* CONFIG_WAV_DEMUXER */
609
610 #if CONFIG_W64_DEMUXER
611 static int w64_probe(AVProbeData *p)
612 {
613     if (p->buf_size <= 40)
614         return 0;
615     if (!memcmp(p->buf,      ff_w64_guid_riff, 16) &&
616         !memcmp(p->buf + 24, ff_w64_guid_wave, 16))
617         return AVPROBE_SCORE_MAX;
618     else
619         return 0;
620 }
621
622 static int w64_read_header(AVFormatContext *s)
623 {
624     int64_t size, data_ofs = 0;
625     AVIOContext *pb      = s->pb;
626     WAVDemuxContext *wav = s->priv_data;
627     AVStream *st;
628     uint8_t guid[16];
629     int ret;
630
631     avio_read(pb, guid, 16);
632     if (memcmp(guid, ff_w64_guid_riff, 16))
633         return AVERROR_INVALIDDATA;
634
635     /* riff + wave + fmt + sizes */
636     if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8)
637         return AVERROR_INVALIDDATA;
638
639     avio_read(pb, guid, 16);
640     if (memcmp(guid, ff_w64_guid_wave, 16)) {
641         av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
642         return AVERROR_INVALIDDATA;
643     }
644
645     wav->w64 = 1;
646
647     st = avformat_new_stream(s, NULL);
648     if (!st)
649         return AVERROR(ENOMEM);
650
651     while (!url_feof(pb)) {
652         if (avio_read(pb, guid, 16) != 16)
653             break;
654         size = avio_rl64(pb);
655         if (size <= 24 || INT64_MAX - size < avio_tell(pb))
656             return AVERROR_INVALIDDATA;
657
658         if (!memcmp(guid, ff_w64_guid_fmt, 16)) {
659             /* subtract chunk header size - normal wav file doesn't count it */
660             ret = ff_get_wav_header(pb, st->codec, size - 24);
661             if (ret < 0)
662                 return ret;
663             avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
664
665             avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
666         } else if (!memcmp(guid, ff_w64_guid_fact, 16)) {
667             int64_t samples;
668
669             samples = avio_rl64(pb);
670             if (samples > 0)
671                 st->duration = samples;
672         } else if (!memcmp(guid, ff_w64_guid_data, 16)) {
673             wav->data_end = avio_tell(pb) + size - 24;
674
675             data_ofs = avio_tell(pb);
676             if (!pb->seekable)
677                 break;
678
679             avio_skip(pb, size - 24);
680         } else if (!memcmp(guid, ff_w64_guid_summarylist, 16)) {
681             int64_t start, end, cur;
682             uint32_t count, chunk_size, i;
683
684             start = avio_tell(pb);
685             end = start + FFALIGN(size, INT64_C(8)) - 24;
686             count = avio_rl32(pb);
687
688             for (i = 0; i < count; i++) {
689                 char chunk_key[5], *value;
690
691                 if (url_feof(pb) || (cur = avio_tell(pb)) < 0 || cur > end - 8 /* = tag + size */)
692                     break;
693
694                 chunk_key[4] = 0;
695                 avio_read(pb, chunk_key, 4);
696                 chunk_size = avio_rl32(pb);
697
698                 value = av_mallocz(chunk_size + 1);
699                 if (!value)
700                     return AVERROR(ENOMEM);
701
702                 ret = avio_get_str16le(pb, chunk_size, value, chunk_size);
703                 avio_skip(pb, chunk_size - ret);
704
705                 av_dict_set(&s->metadata, chunk_key, value, AV_DICT_DONT_STRDUP_VAL);
706             }
707
708             avio_skip(pb, end - avio_tell(pb));
709         } else {
710             av_log(s, AV_LOG_DEBUG, "unknown guid: "FF_PRI_GUID"\n", FF_ARG_GUID(guid));
711             avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
712         }
713     }
714
715     if (!data_ofs)
716         return AVERROR_EOF;
717
718     ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
719     ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
720
721     handle_stream_probing(st);
722     st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
723
724     avio_seek(pb, data_ofs, SEEK_SET);
725
726     return 0;
727 }
728
729 AVInputFormat ff_w64_demuxer = {
730     .name           = "w64",
731     .long_name      = NULL_IF_CONFIG_SMALL("Sony Wave64"),
732     .priv_data_size = sizeof(WAVDemuxContext),
733     .read_probe     = w64_probe,
734     .read_header    = w64_read_header,
735     .read_packet    = wav_read_packet,
736     .read_seek      = wav_read_seek,
737     .flags          = AVFMT_GENERIC_INDEX,
738     .codec_tag      = (const AVCodecTag * const []) { ff_codec_wav_tags, 0 },
739 };
740 #endif /* CONFIG_W64_DEMUXER */