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