bce4876976064ad7054d6efd8ff52ef6be7f9f45
[ffmpeg.git] / libavformat / wavenc.c
1 /*
2  * WAV muxer
3  * Copyright (c) 2001, 2002 Fabrice Bellard
4  *
5  * Sony Wave64 muxer
6  * Copyright (c) 2012 Paul B Mahol
7  *
8  * WAV muxer RF64 support
9  * Copyright (c) 2013 Daniel Verkamp <daniel@drv.nu>
10  *
11  * EBU Tech 3285 - Supplement 3 - Peak Envelope Chunk encoder
12  * Copyright (c) 2014 Georg Lippitsch <georg.lippitsch@gmx.at>
13  *
14  * This file is part of FFmpeg.
15  *
16  * FFmpeg is free software; you can redistribute it and/or
17  * modify it under the terms of the GNU Lesser General Public
18  * License as published by the Free Software Foundation; either
19  * version 2.1 of the License, or (at your option) any later version.
20  *
21  * FFmpeg is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
24  * Lesser General Public License for more details.
25  *
26  * You should have received a copy of the GNU Lesser General Public
27  * License along with FFmpeg; if not, write to the Free Software
28  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29  */
30
31 #include <stdint.h>
32 #include <string.h>
33
34 #include "libavutil/avstring.h"
35 #include "libavutil/dict.h"
36 #include "libavutil/common.h"
37 #include "libavutil/intreadwrite.h"
38 #include "libavutil/mathematics.h"
39 #include "libavutil/opt.h"
40 #include "libavutil/time.h"
41 #include "libavutil/time_internal.h"
42
43 #include "avformat.h"
44 #include "avio.h"
45 #include "avio_internal.h"
46 #include "internal.h"
47 #include "riff.h"
48
49 #define RF64_AUTO   (-1)
50 #define RF64_NEVER  0
51 #define RF64_ALWAYS 1
52
53 #define PEAK_BUFFER_SIZE   1024
54
55 typedef enum {
56     PEAK_OFF = 0,
57     PEAK_ON,
58     PEAK_ONLY
59 } PeakType;
60
61 typedef enum {
62     PEAK_FORMAT_UINT8 = 1,
63     PEAK_FORMAT_UINT16
64 } PeakFormat;
65
66 typedef struct WAVMuxContext {
67     const AVClass *class;
68     int64_t data;
69     int64_t fact_pos;
70     int64_t ds64;
71     int64_t minpts;
72     int64_t maxpts;
73     int16_t *peak_maxpos, *peak_maxneg;
74     uint32_t peak_num_frames;
75     uint32_t peak_outbuf_size;
76     uint32_t peak_outbuf_bytes;
77     uint32_t peak_pos_pop;
78     uint16_t peak_pop;
79     uint8_t *peak_output;
80     int last_duration;
81     int write_bext;
82     int write_peak;
83     int rf64;
84     int peak_block_size;
85     PeakFormat peak_format;
86     int peak_block_pos;
87     int peak_ppv;
88     int peak_bps;
89 } WAVMuxContext;
90
91 #if CONFIG_WAV_MUXER
92 static inline void bwf_write_bext_string(AVFormatContext *s, const char *key, int maxlen)
93 {
94     AVDictionaryEntry *tag;
95     int len = 0;
96
97     if (tag = av_dict_get(s->metadata, key, NULL, 0)) {
98         len = strlen(tag->value);
99         len = FFMIN(len, maxlen);
100         avio_write(s->pb, tag->value, len);
101     }
102
103     ffio_fill(s->pb, 0, maxlen - len);
104 }
105
106 static void bwf_write_bext_chunk(AVFormatContext *s)
107 {
108     AVDictionaryEntry *tmp_tag;
109     uint64_t time_reference = 0;
110     int64_t bext = ff_start_tag(s->pb, "bext");
111
112     bwf_write_bext_string(s, "description", 256);
113     bwf_write_bext_string(s, "originator", 32);
114     bwf_write_bext_string(s, "originator_reference", 32);
115     bwf_write_bext_string(s, "origination_date", 10);
116     bwf_write_bext_string(s, "origination_time", 8);
117
118     if (tmp_tag = av_dict_get(s->metadata, "time_reference", NULL, 0))
119         time_reference = strtoll(tmp_tag->value, NULL, 10);
120     avio_wl64(s->pb, time_reference);
121     avio_wl16(s->pb, 1);  // set version to 1
122
123     if (tmp_tag = av_dict_get(s->metadata, "umid", NULL, 0)) {
124         unsigned char umidpart_str[17] = {0};
125         int i;
126         uint64_t umidpart;
127         int len = strlen(tmp_tag->value+2);
128
129         for (i = 0; i < len/16; i++) {
130             memcpy(umidpart_str, tmp_tag->value + 2 + (i*16), 16);
131             umidpart = strtoll(umidpart_str, NULL, 16);
132             avio_wb64(s->pb, umidpart);
133         }
134         ffio_fill(s->pb, 0, 64 - i*8);
135     } else
136         ffio_fill(s->pb, 0, 64); // zero UMID
137
138     ffio_fill(s->pb, 0, 190); // Reserved
139
140     if (tmp_tag = av_dict_get(s->metadata, "coding_history", NULL, 0))
141         avio_put_str(s->pb, tmp_tag->value);
142
143     ff_end_tag(s->pb, bext);
144 }
145
146 static av_cold void peak_free_buffers(AVFormatContext *s)
147 {
148     WAVMuxContext *wav = s->priv_data;
149
150     av_freep(&wav->peak_maxpos);
151     av_freep(&wav->peak_maxneg);
152     av_freep(&wav->peak_output);
153 }
154
155 static av_cold int peak_init_writer(AVFormatContext *s)
156 {
157     WAVMuxContext *wav = s->priv_data;
158     AVCodecContext *enc = s->streams[0]->codec;
159
160     if (enc->codec_id != AV_CODEC_ID_PCM_S8 &&
161         enc->codec_id != AV_CODEC_ID_PCM_S16LE &&
162         enc->codec_id != AV_CODEC_ID_PCM_U8 &&
163         enc->codec_id != AV_CODEC_ID_PCM_U16LE) {
164         av_log(s, AV_LOG_ERROR, "%s codec not supported for Peak Chunk\n",
165                s->streams[0]->codec->codec ? s->streams[0]->codec->codec->name : "NONE");
166         return -1;
167     }
168
169     wav->peak_bps = av_get_bits_per_sample(enc->codec_id) / 8;
170
171     if (wav->peak_bps == 1 && wav->peak_format == PEAK_FORMAT_UINT16) {
172         av_log(s, AV_LOG_ERROR,
173                "Writing 16 bit peak for 8 bit audio does not make sense\n");
174         return AVERROR(EINVAL);
175     }
176
177     wav->peak_maxpos = av_mallocz_array(enc->channels, sizeof(*wav->peak_maxpos));
178     wav->peak_maxneg = av_mallocz_array(enc->channels, sizeof(*wav->peak_maxneg));
179     wav->peak_output = av_malloc(PEAK_BUFFER_SIZE);
180     if (!wav->peak_maxpos || !wav->peak_maxneg || !wav->peak_output)
181         goto nomem;
182
183     wav->peak_outbuf_size = PEAK_BUFFER_SIZE;
184
185     return 0;
186
187 nomem:
188     av_log(s, AV_LOG_ERROR, "Out of memory\n");
189     peak_free_buffers(s);
190     return AVERROR(ENOMEM);
191 }
192
193 static void peak_write_frame(AVFormatContext *s)
194 {
195     WAVMuxContext *wav = s->priv_data;
196     AVCodecContext *enc = s->streams[0]->codec;
197     int peak_of_peaks;
198     int c;
199
200     if (!wav->peak_output)
201         return;
202
203     for (c = 0; c < enc->channels; c++) {
204         wav->peak_maxneg[c] = -wav->peak_maxneg[c];
205
206         if (wav->peak_bps == 2 && wav->peak_format == PEAK_FORMAT_UINT8) {
207             wav->peak_maxpos[c] = wav->peak_maxpos[c] / 256;
208             wav->peak_maxneg[c] = wav->peak_maxneg[c] / 256;
209         }
210
211         if (wav->peak_ppv == 1)
212             wav->peak_maxpos[c] =
213                 FFMAX(wav->peak_maxpos[c], wav->peak_maxneg[c]);
214
215         peak_of_peaks = FFMAX3(wav->peak_maxpos[c], wav->peak_maxneg[c],
216                                wav->peak_pop);
217         if (peak_of_peaks > wav->peak_pop)
218             wav->peak_pos_pop = wav->peak_num_frames;
219         wav->peak_pop = peak_of_peaks;
220
221         if (wav->peak_outbuf_size - wav->peak_outbuf_bytes <
222             wav->peak_format * wav->peak_ppv) {
223             wav->peak_outbuf_size += PEAK_BUFFER_SIZE;
224             wav->peak_output = av_realloc(wav->peak_output,
225                                           wav->peak_outbuf_size);
226             if (!wav->peak_output) {
227                 av_log(s, AV_LOG_ERROR, "No memory for peak data\n");
228                 return;
229             }
230         }
231
232         if (wav->peak_format == PEAK_FORMAT_UINT8) {
233             wav->peak_output[wav->peak_outbuf_bytes++] =
234                 wav->peak_maxpos[c];
235             if (wav->peak_ppv == 2) {
236                 wav->peak_output[wav->peak_outbuf_bytes++] =
237                     wav->peak_maxneg[c];
238             }
239         } else {
240             AV_WL16(wav->peak_output + wav->peak_outbuf_bytes,
241                     wav->peak_maxpos[c]);
242             wav->peak_outbuf_bytes += 2;
243             if (wav->peak_ppv == 2) {
244                 AV_WL16(wav->peak_output + wav->peak_outbuf_bytes,
245                         wav->peak_maxneg[c]);
246                 wav->peak_outbuf_bytes += 2;
247             }
248         }
249         wav->peak_maxpos[c] = 0;
250         wav->peak_maxneg[c] = 0;
251     }
252     wav->peak_num_frames++;
253 }
254
255 static void peak_write_chunk(AVFormatContext *s)
256 {
257     WAVMuxContext *wav = s->priv_data;
258     AVIOContext *pb = s->pb;
259     AVCodecContext *enc = s->streams[0]->codec;
260     int64_t peak = ff_start_tag(s->pb, "levl");
261     int64_t now0;
262     time_t now_secs;
263     char timestamp[28];
264
265     /* Peak frame of incomplete block at end */
266     if (wav->peak_block_pos)
267         peak_write_frame(s);
268
269     memset(timestamp, 0, sizeof(timestamp));
270     if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
271         struct tm tmpbuf;
272         av_log(s, AV_LOG_INFO, "Writing local time and date to Peak Envelope Chunk\n");
273         now0 = av_gettime();
274         now_secs = now0 / 1000000;
275         strftime(timestamp, sizeof(timestamp), "%Y:%m:%d:%H:%M:%S:", localtime_r(&now_secs, &tmpbuf));
276         av_strlcatf(timestamp, sizeof(timestamp), "%03d", (int)((now0 / 1000) % 1000));
277     }
278
279     avio_wl32(pb, 1);                           /* version */
280     avio_wl32(pb, wav->peak_format);            /* 8 or 16 bit */
281     avio_wl32(pb, wav->peak_ppv);               /* positive and negative */
282     avio_wl32(pb, wav->peak_block_size);        /* frames per value */
283     avio_wl32(pb, enc->channels);               /* number of channels */
284     avio_wl32(pb, wav->peak_num_frames);        /* number of peak frames */
285     avio_wl32(pb, wav->peak_pos_pop);           /* audio sample frame index */
286     avio_wl32(pb, 128);                         /* equal to size of header */
287     avio_write(pb, timestamp, 28);              /* ASCII time stamp */
288     ffio_fill(pb, 0, 60);
289
290     avio_write(pb, wav->peak_output, wav->peak_outbuf_bytes);
291
292     ff_end_tag(pb, peak);
293
294     if (!wav->data)
295         wav->data = peak;
296 }
297
298 static int wav_write_header(AVFormatContext *s)
299 {
300     WAVMuxContext *wav = s->priv_data;
301     AVIOContext *pb = s->pb;
302     int64_t fmt;
303
304     if (s->nb_streams != 1) {
305         av_log(s, AV_LOG_ERROR, "WAVE files have exactly one stream\n");
306         return AVERROR(EINVAL);
307     }
308
309     if (wav->rf64 == RF64_ALWAYS) {
310         ffio_wfourcc(pb, "RF64");
311         avio_wl32(pb, -1); /* RF64 chunk size: use size in ds64 */
312     } else {
313         ffio_wfourcc(pb, "RIFF");
314         avio_wl32(pb, -1); /* file length */
315     }
316
317     ffio_wfourcc(pb, "WAVE");
318
319     if (wav->rf64 != RF64_NEVER) {
320         /* write empty ds64 chunk or JUNK chunk to reserve space for ds64 */
321         ffio_wfourcc(pb, wav->rf64 == RF64_ALWAYS ? "ds64" : "JUNK");
322         avio_wl32(pb, 28); /* chunk size */
323         wav->ds64 = avio_tell(pb);
324         ffio_fill(pb, 0, 28);
325     }
326
327     if (wav->write_peak != 2) {
328         /* format header */
329         fmt = ff_start_tag(pb, "fmt ");
330         if (ff_put_wav_header(pb, s->streams[0]->codec, 0) < 0) {
331             const AVCodecDescriptor *desc = avcodec_descriptor_get(s->streams[0]->codec->codec_id);
332             av_log(s, AV_LOG_ERROR, "%s codec not supported in WAVE format\n",
333                    desc ? desc->name : "unknown");
334             return AVERROR(ENOSYS);
335         }
336         ff_end_tag(pb, fmt);
337     }
338
339     if (s->streams[0]->codec->codec_tag != 0x01 /* hence for all other than PCM */
340         && s->pb->seekable) {
341         wav->fact_pos = ff_start_tag(pb, "fact");
342         avio_wl32(pb, 0);
343         ff_end_tag(pb, wav->fact_pos);
344     }
345
346     if (wav->write_bext)
347         bwf_write_bext_chunk(s);
348
349     if (wav->write_peak) {
350         int ret;
351         if ((ret = peak_init_writer(s)) < 0)
352             return ret;
353     }
354
355     avpriv_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codec->sample_rate);
356     wav->maxpts = wav->last_duration = 0;
357     wav->minpts = INT64_MAX;
358
359     if (wav->write_peak != 2) {
360         /* info header */
361         ff_riff_write_info(s);
362
363         /* data header */
364         wav->data = ff_start_tag(pb, "data");
365     }
366
367     avio_flush(pb);
368
369     return 0;
370 }
371
372 static int wav_write_packet(AVFormatContext *s, AVPacket *pkt)
373 {
374     AVIOContext *pb  = s->pb;
375     WAVMuxContext    *wav = s->priv_data;
376
377     if (wav->write_peak != 2)
378         avio_write(pb, pkt->data, pkt->size);
379
380     if (wav->write_peak) {
381         int c = 0;
382         int i;
383         for (i = 0; i < pkt->size; i += wav->peak_bps) {
384             if (wav->peak_bps == 1) {
385                 wav->peak_maxpos[c] = FFMAX(wav->peak_maxpos[c], *(int8_t*)(pkt->data + i));
386                 wav->peak_maxneg[c] = FFMIN(wav->peak_maxneg[c], *(int8_t*)(pkt->data + i));
387             } else {
388                 wav->peak_maxpos[c] = FFMAX(wav->peak_maxpos[c], (int16_t)AV_RL16(pkt->data + i));
389                 wav->peak_maxneg[c] = FFMIN(wav->peak_maxneg[c], (int16_t)AV_RL16(pkt->data + i));
390             }
391             if (++c == s->streams[0]->codec->channels) {
392                 c = 0;
393                 if (++wav->peak_block_pos == wav->peak_block_size) {
394                     peak_write_frame(s);
395                     wav->peak_block_pos = 0;
396                 }
397             }
398         }
399     }
400
401     if(pkt->pts != AV_NOPTS_VALUE) {
402         wav->minpts        = FFMIN(wav->minpts, pkt->pts);
403         wav->maxpts        = FFMAX(wav->maxpts, pkt->pts);
404         wav->last_duration = pkt->duration;
405     } else
406         av_log(s, AV_LOG_ERROR, "wav_write_packet: NOPTS\n");
407     return 0;
408 }
409
410 static int wav_write_trailer(AVFormatContext *s)
411 {
412     AVIOContext *pb  = s->pb;
413     WAVMuxContext    *wav = s->priv_data;
414     int64_t file_size, data_size;
415     int64_t number_of_samples = 0;
416     int rf64 = 0;
417
418     avio_flush(pb);
419
420     if (s->pb->seekable) {
421         if (wav->write_peak != 2) {
422             ff_end_tag(pb, wav->data);
423             avio_flush(pb);
424         }
425
426         if (wav->write_peak && wav->peak_output) {
427             peak_write_chunk(s);
428             avio_flush(pb);
429         }
430
431         /* update file size */
432         file_size = avio_tell(pb);
433         data_size = file_size - wav->data;
434         if (wav->rf64 == RF64_ALWAYS || (wav->rf64 == RF64_AUTO && file_size - 8 > UINT32_MAX)) {
435             rf64 = 1;
436         } else {
437             avio_seek(pb, 4, SEEK_SET);
438             avio_wl32(pb, (uint32_t)(file_size - 8));
439             avio_seek(pb, file_size, SEEK_SET);
440
441             avio_flush(pb);
442         }
443
444         number_of_samples = av_rescale(wav->maxpts - wav->minpts + wav->last_duration,
445                                        s->streams[0]->codec->sample_rate * (int64_t)s->streams[0]->time_base.num,
446                                        s->streams[0]->time_base.den);
447
448         if(s->streams[0]->codec->codec_tag != 0x01) {
449             /* Update num_samps in fact chunk */
450             avio_seek(pb, wav->fact_pos, SEEK_SET);
451             if (rf64 || (wav->rf64 == RF64_AUTO && number_of_samples > UINT32_MAX)) {
452                 rf64 = 1;
453                 avio_wl32(pb, -1);
454             } else {
455                 avio_wl32(pb, number_of_samples);
456                 avio_seek(pb, file_size, SEEK_SET);
457                 avio_flush(pb);
458             }
459         }
460
461         if (rf64) {
462             /* overwrite RIFF with RF64 */
463             avio_seek(pb, 0, SEEK_SET);
464             ffio_wfourcc(pb, "RF64");
465             avio_wl32(pb, -1);
466
467             /* write ds64 chunk (overwrite JUNK if rf64 == RF64_AUTO) */
468             avio_seek(pb, wav->ds64 - 8, SEEK_SET);
469             ffio_wfourcc(pb, "ds64");
470             avio_wl32(pb, 28);                  /* ds64 chunk size */
471             avio_wl64(pb, file_size - 8);       /* RF64 chunk size */
472             avio_wl64(pb, data_size);           /* data chunk size */
473             avio_wl64(pb, number_of_samples);   /* fact chunk number of samples */
474             avio_wl32(pb, 0);                   /* number of table entries for non-'data' chunks */
475
476             /* write -1 in data chunk size */
477             avio_seek(pb, wav->data - 4, SEEK_SET);
478             avio_wl32(pb, -1);
479
480             avio_seek(pb, file_size, SEEK_SET);
481             avio_flush(pb);
482         }
483     }
484
485     if (wav->write_peak)
486         peak_free_buffers(s);
487
488     return 0;
489 }
490
491 #define OFFSET(x) offsetof(WAVMuxContext, x)
492 #define ENC AV_OPT_FLAG_ENCODING_PARAM
493 static const AVOption options[] = {
494     { "write_bext", "Write BEXT chunk.", OFFSET(write_bext), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, ENC },
495     { "write_peak", "Write Peak Envelope chunk.",            OFFSET(write_peak), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, ENC, "peak" },
496     { "off",        "Do not write peak chunk.",              0,                  AV_OPT_TYPE_CONST, { .i64 = PEAK_OFF  }, 0, 0, ENC, "peak" },
497     { "on",         "Append peak chunk after wav data.",     0,                  AV_OPT_TYPE_CONST, { .i64 = PEAK_ON   }, 0, 0, ENC, "peak" },
498     { "only",       "Write only peak chunk, omit wav data.", 0,                  AV_OPT_TYPE_CONST, { .i64 = PEAK_ONLY }, 0, 0, ENC, "peak" },
499     { "rf64",       "Use RF64 header rather than RIFF for large files.",    OFFSET(rf64), AV_OPT_TYPE_INT,   { .i64 = RF64_NEVER  },-1, 1, ENC, "rf64" },
500     { "auto",       "Write RF64 header if file grows large enough.",        0,            AV_OPT_TYPE_CONST, { .i64 = RF64_AUTO   }, 0, 0, ENC, "rf64" },
501     { "always",     "Always write RF64 header regardless of file size.",    0,            AV_OPT_TYPE_CONST, { .i64 = RF64_ALWAYS }, 0, 0, ENC, "rf64" },
502     { "never",      "Never write RF64 header regardless of file size.",     0,            AV_OPT_TYPE_CONST, { .i64 = RF64_NEVER  }, 0, 0, ENC, "rf64" },
503     { "peak_block_size", "Number of audio samples used to generate each peak frame.",   OFFSET(peak_block_size), AV_OPT_TYPE_INT, { .i64 = 256 }, 0, 65536, ENC },
504     { "peak_format",     "The format of the peak envelope data (1: uint8, 2: uint16).", OFFSET(peak_format), AV_OPT_TYPE_INT,     { .i64 = PEAK_FORMAT_UINT16 }, PEAK_FORMAT_UINT8, PEAK_FORMAT_UINT16, ENC },
505     { "peak_ppv",        "Number of peak points per peak value (1 or 2).",              OFFSET(peak_ppv), AV_OPT_TYPE_INT, { .i64 = 2 }, 1, 2, ENC },
506     { NULL },
507 };
508
509 static const AVClass wav_muxer_class = {
510     .class_name = "WAV muxer",
511     .item_name  = av_default_item_name,
512     .option     = options,
513     .version    = LIBAVUTIL_VERSION_INT,
514 };
515
516 AVOutputFormat ff_wav_muxer = {
517     .name              = "wav",
518     .long_name         = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
519     .mime_type         = "audio/x-wav",
520     .extensions        = "wav",
521     .priv_data_size    = sizeof(WAVMuxContext),
522     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
523     .video_codec       = AV_CODEC_ID_NONE,
524     .write_header      = wav_write_header,
525     .write_packet      = wav_write_packet,
526     .write_trailer     = wav_write_trailer,
527     .flags             = AVFMT_TS_NONSTRICT,
528     .codec_tag         = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
529     .priv_class        = &wav_muxer_class,
530 };
531 #endif /* CONFIG_WAV_MUXER */
532
533 #if CONFIG_W64_MUXER
534 #include "w64.h"
535
536 static void start_guid(AVIOContext *pb, const uint8_t *guid, int64_t *pos)
537 {
538     *pos = avio_tell(pb);
539
540     avio_write(pb, guid, 16);
541     avio_wl64(pb, INT64_MAX);
542 }
543
544 static void end_guid(AVIOContext *pb, int64_t start)
545 {
546     int64_t end, pos = avio_tell(pb);
547
548     end = FFALIGN(pos, 8);
549     ffio_fill(pb, 0, end - pos);
550     avio_seek(pb, start + 16, SEEK_SET);
551     avio_wl64(pb, end - start);
552     avio_seek(pb, end, SEEK_SET);
553 }
554
555 static int w64_write_header(AVFormatContext *s)
556 {
557     WAVMuxContext *wav = s->priv_data;
558     AVIOContext *pb = s->pb;
559     int64_t start;
560     int ret;
561
562     avio_write(pb, ff_w64_guid_riff, sizeof(ff_w64_guid_riff));
563     avio_wl64(pb, -1);
564     avio_write(pb, ff_w64_guid_wave, sizeof(ff_w64_guid_wave));
565     start_guid(pb, ff_w64_guid_fmt, &start);
566     if ((ret = ff_put_wav_header(pb, s->streams[0]->codec, 0)) < 0) {
567         av_log(s, AV_LOG_ERROR, "%s codec not supported\n",
568                s->streams[0]->codec->codec ? s->streams[0]->codec->codec->name : "NONE");
569         return ret;
570     }
571     end_guid(pb, start);
572
573     if (s->streams[0]->codec->codec_tag != 0x01 /* hence for all other than PCM */
574         && s->pb->seekable) {
575         start_guid(pb, ff_w64_guid_fact, &wav->fact_pos);
576         avio_wl64(pb, 0);
577         end_guid(pb, wav->fact_pos);
578     }
579
580     start_guid(pb, ff_w64_guid_data, &wav->data);
581
582     return 0;
583 }
584
585 static int w64_write_trailer(AVFormatContext *s)
586 {
587     AVIOContext    *pb = s->pb;
588     WAVMuxContext *wav = s->priv_data;
589     int64_t file_size;
590
591     if (pb->seekable) {
592         end_guid(pb, wav->data);
593
594         file_size = avio_tell(pb);
595         avio_seek(pb, 16, SEEK_SET);
596         avio_wl64(pb, file_size);
597
598         if (s->streams[0]->codec->codec_tag != 0x01) {
599             int64_t number_of_samples;
600
601             number_of_samples = av_rescale(wav->maxpts - wav->minpts + wav->last_duration,
602                                            s->streams[0]->codec->sample_rate * (int64_t)s->streams[0]->time_base.num,
603                                            s->streams[0]->time_base.den);
604             avio_seek(pb, wav->fact_pos + 24, SEEK_SET);
605             avio_wl64(pb, number_of_samples);
606         }
607
608         avio_seek(pb, file_size, SEEK_SET);
609         avio_flush(pb);
610     }
611
612     return 0;
613 }
614
615 AVOutputFormat ff_w64_muxer = {
616     .name              = "w64",
617     .long_name         = NULL_IF_CONFIG_SMALL("Sony Wave64"),
618     .extensions        = "w64",
619     .priv_data_size    = sizeof(WAVMuxContext),
620     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
621     .video_codec       = AV_CODEC_ID_NONE,
622     .write_header      = w64_write_header,
623     .write_packet      = wav_write_packet,
624     .write_trailer     = w64_write_trailer,
625     .flags             = AVFMT_TS_NONSTRICT,
626     .codec_tag         = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
627 };
628 #endif /* CONFIG_W64_MUXER */