]> git.sesse.net Git - ffmpeg/blob - libavformat/spdifenc.c
704eb9e3abd196f66d7a8c74006a720108406950
[ffmpeg] / libavformat / spdifenc.c
1 /*
2  * IEC 61937 muxer
3  * Copyright (c) 2009 Bartlomiej Wolowiec
4  * Copyright (c) 2010 Anssi Hannula
5  * Copyright (c) 2010 Carl Eugen Hoyos
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 /**
25  * @file
26  * IEC-61937 encapsulation of various formats, used by S/PDIF
27  * @author Bartlomiej Wolowiec
28  * @author Anssi Hannula
29  * @author Carl Eugen Hoyos
30  */
31
32 /*
33  * Terminology used in specification:
34  * data-burst - IEC61937 frame, contains header and encapsuled frame
35  * burst-preambule - IEC61937 frame header, contains 16-bits words named Pa, Pb, Pc and Pd
36  * burst-payload - encapsuled frame
37  * Pa, Pb - syncword - 0xF872, 0x4E1F
38  * Pc - burst-info, contains data-type (bits 0-6), error flag (bit 7), data-type-dependent info (bits 8-12)
39  *      and bitstream number (bits 13-15)
40  * data-type - determines type of encapsuled frames
41  * Pd - length code (number of bits or bytes of encapsuled frame - according to data_type)
42  *
43  * IEC 61937 frames at normal usage start every specific count of bytes,
44  *      dependent from data-type (spaces between packets are filled by zeros)
45  */
46
47 #include "avformat.h"
48 #include "spdif.h"
49 #include "libavcodec/ac3.h"
50 #include "libavcodec/dca.h"
51 #include "libavcodec/aacadtsdec.h"
52
53 typedef struct IEC61937Context {
54     enum IEC61937DataType data_type;///< burst info - reference to type of payload of the data-burst
55     int length_code;                ///< length code in bits or bytes, depending on data type
56     int pkt_offset;                 ///< data burst repetition period in bytes
57     uint8_t *buffer;                ///< allocated buffer, used for swap bytes
58     int buffer_size;                ///< size of allocated buffer
59
60     uint8_t *out_buf;               ///< pointer to the outgoing data before byte-swapping
61     int out_bytes;                  ///< amount of outgoing bytes
62
63     int use_preamble;               ///< preamble enabled (disabled for exactly pre-padded DTS)
64     int extra_bswap;                ///< extra bswap for payload (for LE DTS => standard BE DTS)
65
66     uint8_t *hd_buf;                ///< allocated buffer to concatenate hd audio frames
67     int hd_buf_size;                ///< size of the hd audio buffer
68     int hd_buf_count;               ///< number of frames in the hd audio buffer
69     int hd_buf_filled;              ///< amount of bytes in the hd audio buffer
70
71     /// function, which generates codec dependent header information.
72     /// Sets data_type and pkt_offset, and length_code, out_bytes, out_buf if necessary
73     int (*header_info) (AVFormatContext *s, AVPacket *pkt);
74 } IEC61937Context;
75
76
77 static int spdif_header_ac3(AVFormatContext *s, AVPacket *pkt)
78 {
79     IEC61937Context *ctx = s->priv_data;
80     int bitstream_mode = pkt->data[5] & 0x7;
81
82     ctx->data_type  = IEC61937_AC3 | (bitstream_mode << 8);
83     ctx->pkt_offset = AC3_FRAME_SIZE << 2;
84     return 0;
85 }
86
87 static int spdif_header_eac3(AVFormatContext *s, AVPacket *pkt)
88 {
89     IEC61937Context *ctx = s->priv_data;
90     static const uint8_t eac3_repeat[4] = {6, 3, 2, 1};
91     int repeat = 1;
92
93     if ((pkt->data[4] & 0xc0) != 0xc0) /* fscod */
94         repeat = eac3_repeat[(pkt->data[4] & 0x30) >> 4]; /* numblkscod */
95
96     ctx->hd_buf = av_fast_realloc(ctx->hd_buf, &ctx->hd_buf_size, ctx->hd_buf_filled + pkt->size);
97     if (!ctx->hd_buf)
98         return AVERROR(ENOMEM);
99
100     memcpy(&ctx->hd_buf[ctx->hd_buf_filled], pkt->data, pkt->size);
101
102     ctx->hd_buf_filled += pkt->size;
103     if (++ctx->hd_buf_count < repeat){
104         ctx->pkt_offset = 0;
105         return 0;
106     }
107     ctx->data_type   = IEC61937_EAC3;
108     ctx->pkt_offset  = 24576;
109     ctx->out_buf     = ctx->hd_buf;
110     ctx->out_bytes   = ctx->hd_buf_filled;
111     ctx->length_code = ctx->hd_buf_filled;
112
113     ctx->hd_buf_count  = 0;
114     ctx->hd_buf_filled = 0;
115     return 0;
116 }
117
118 static int spdif_header_dts(AVFormatContext *s, AVPacket *pkt)
119 {
120     IEC61937Context *ctx = s->priv_data;
121     uint32_t syncword_dts = AV_RB32(pkt->data);
122     int blocks;
123
124     switch (syncword_dts) {
125     case DCA_MARKER_RAW_BE:
126         blocks = (AV_RB16(pkt->data + 4) >> 2) & 0x7f;
127         break;
128     case DCA_MARKER_RAW_LE:
129         blocks = (AV_RL16(pkt->data + 4) >> 2) & 0x7f;
130         ctx->extra_bswap = 1;
131         break;
132     case DCA_MARKER_14B_BE:
133         blocks =
134             (((pkt->data[5] & 0x07) << 4) | ((pkt->data[6] & 0x3f) >> 2));
135         break;
136     case DCA_MARKER_14B_LE:
137         blocks =
138             (((pkt->data[4] & 0x07) << 4) | ((pkt->data[7] & 0x3f) >> 2));
139         ctx->extra_bswap = 1;
140         break;
141     default:
142         av_log(s, AV_LOG_ERROR, "bad DTS syncword 0x%x\n", syncword_dts);
143         return AVERROR_INVALIDDATA;
144     }
145     blocks++;
146     switch (blocks) {
147     case  512 >> 5: ctx->data_type = IEC61937_DTS1; break;
148     case 1024 >> 5: ctx->data_type = IEC61937_DTS2; break;
149     case 2048 >> 5: ctx->data_type = IEC61937_DTS3; break;
150     default:
151         av_log(s, AV_LOG_ERROR, "%i samples in DTS frame not supported\n",
152                blocks << 5);
153         return AVERROR(ENOSYS);
154     }
155     ctx->pkt_offset = blocks << 7;
156
157     if (ctx->out_bytes == ctx->pkt_offset) {
158         /* The DTS stream fits exactly into the output stream, so skip the
159          * preamble as it would not fit in there. This is the case for dts
160          * discs and dts-in-wav. */
161         ctx->use_preamble = 0;
162     }
163
164     return 0;
165 }
166
167 static const enum IEC61937DataType mpeg_data_type[2][3] = {
168     //     LAYER1                      LAYER2                  LAYER3
169     { IEC61937_MPEG2_LAYER1_LSF, IEC61937_MPEG2_LAYER2_LSF, IEC61937_MPEG2_LAYER3_LSF },//MPEG2 LSF
170     { IEC61937_MPEG1_LAYER1,     IEC61937_MPEG1_LAYER23,    IEC61937_MPEG1_LAYER23 },   //MPEG1
171 };
172
173 static int spdif_header_mpeg(AVFormatContext *s, AVPacket *pkt)
174 {
175     IEC61937Context *ctx = s->priv_data;
176     int version =      (pkt->data[1] >> 3) & 3;
177     int layer   = 3 - ((pkt->data[1] >> 1) & 3);
178     int extension = pkt->data[2] & 1;
179
180     if (layer == 3 || version == 1) {
181         av_log(s, AV_LOG_ERROR, "Wrong MPEG file format\n");
182         return AVERROR_INVALIDDATA;
183     }
184     av_log(s, AV_LOG_DEBUG, "version: %i layer: %i extension: %i\n", version, layer, extension);
185     if (version == 2 && extension) {
186         ctx->data_type  = IEC61937_MPEG2_EXT;
187         ctx->pkt_offset = 4608;
188     } else {
189         ctx->data_type  = mpeg_data_type [version & 1][layer];
190         ctx->pkt_offset = spdif_mpeg_pkt_offset[version & 1][layer];
191     }
192     // TODO Data type dependant info (normal/karaoke, dynamic range control)
193     return 0;
194 }
195
196 static int spdif_header_aac(AVFormatContext *s, AVPacket *pkt)
197 {
198     IEC61937Context *ctx = s->priv_data;
199     AACADTSHeaderInfo hdr;
200     GetBitContext gbc;
201     int ret;
202
203     init_get_bits(&gbc, pkt->data, AAC_ADTS_HEADER_SIZE * 8);
204     ret = ff_aac_parse_header(&gbc, &hdr);
205     if (ret < 0) {
206         av_log(s, AV_LOG_ERROR, "Wrong AAC file format\n");
207         return AVERROR_INVALIDDATA;
208     }
209
210     ctx->pkt_offset = hdr.samples << 2;
211     switch (hdr.num_aac_frames) {
212     case 1:
213         ctx->data_type = IEC61937_MPEG2_AAC;
214         break;
215     case 2:
216         ctx->data_type = IEC61937_MPEG2_AAC_LSF_2048;
217         break;
218     case 4:
219         ctx->data_type = IEC61937_MPEG2_AAC_LSF_4096;
220         break;
221     default:
222         av_log(s, AV_LOG_ERROR, "%i samples in AAC frame not supported\n",
223                hdr.samples);
224         return AVERROR(EINVAL);
225     }
226     //TODO Data type dependent info (LC profile/SBR)
227     return 0;
228 }
229
230
231 /*
232  * It seems Dolby TrueHD frames have to be encapsulated in MAT frames before
233  * they can be encapsulated in IEC 61937.
234  * Here we encapsulate 24 TrueHD frames in a single MAT frame, padding them
235  * to achieve constant rate.
236  * The actual format of a MAT frame is unknown, but the below seems to work.
237  * However, it seems it is not actually necessary for the 24 TrueHD frames to
238  * be in an exact alignment with the MAT frame.
239  */
240 #define MAT_FRAME_SIZE          61424
241 #define TRUEHD_FRAME_OFFSET     2560
242 #define MAT_MIDDLE_CODE_OFFSET  -4
243
244 static int spdif_header_truehd(AVFormatContext *s, AVPacket *pkt)
245 {
246     IEC61937Context *ctx = s->priv_data;
247     int mat_code_length = 0;
248     const char mat_end_code[16] = { 0xC3, 0xC2, 0xC0, 0xC4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x97, 0x11 };
249
250     if (!ctx->hd_buf_count) {
251         const char mat_start_code[20] = { 0x07, 0x9E, 0x00, 0x03, 0x84, 0x01, 0x01, 0x01, 0x80, 0x00, 0x56, 0xA5, 0x3B, 0xF4, 0x81, 0x83, 0x49, 0x80, 0x77, 0xE0 };
252         mat_code_length = sizeof(mat_start_code) + BURST_HEADER_SIZE;
253         memcpy(ctx->hd_buf, mat_start_code, sizeof(mat_start_code));
254
255     } else if (ctx->hd_buf_count == 12) {
256         const char mat_middle_code[12] = { 0xC3, 0xC1, 0x42, 0x49, 0x3B, 0xFA, 0x82, 0x83, 0x49, 0x80, 0x77, 0xE0 };
257         mat_code_length = sizeof(mat_middle_code) + MAT_MIDDLE_CODE_OFFSET;
258         memcpy(&ctx->hd_buf[12 * TRUEHD_FRAME_OFFSET - BURST_HEADER_SIZE + MAT_MIDDLE_CODE_OFFSET],
259                mat_middle_code, sizeof(mat_middle_code));
260     }
261
262     if (pkt->size > TRUEHD_FRAME_OFFSET - mat_code_length) {
263         /* if such frames exist, we'd need some more complex logic to
264          * distribute the TrueHD frames in the MAT frame */
265         av_log(s, AV_LOG_ERROR, "TrueHD frame too big, %d bytes\n", pkt->size);
266         av_log_ask_for_sample(s, NULL);
267         return AVERROR_INVALIDDATA;
268     }
269
270     memcpy(&ctx->hd_buf[ctx->hd_buf_count * TRUEHD_FRAME_OFFSET - BURST_HEADER_SIZE + mat_code_length],
271            pkt->data, pkt->size);
272     memset(&ctx->hd_buf[ctx->hd_buf_count * TRUEHD_FRAME_OFFSET - BURST_HEADER_SIZE + mat_code_length + pkt->size],
273            0, TRUEHD_FRAME_OFFSET - pkt->size - mat_code_length);
274
275     if (++ctx->hd_buf_count < 24){
276         ctx->pkt_offset = 0;
277         return 0;
278     }
279     memcpy(&ctx->hd_buf[MAT_FRAME_SIZE - sizeof(mat_end_code)], mat_end_code, sizeof(mat_end_code));
280     ctx->hd_buf_count = 0;
281
282     ctx->data_type   = IEC61937_TRUEHD;
283     ctx->pkt_offset  = 61440;
284     ctx->out_buf     = ctx->hd_buf;
285     ctx->out_bytes   = MAT_FRAME_SIZE;
286     ctx->length_code = MAT_FRAME_SIZE;
287     return 0;
288 }
289
290 static int spdif_write_header(AVFormatContext *s)
291 {
292     IEC61937Context *ctx = s->priv_data;
293
294     switch (s->streams[0]->codec->codec_id) {
295     case CODEC_ID_AC3:
296         ctx->header_info = spdif_header_ac3;
297         break;
298     case CODEC_ID_EAC3:
299         ctx->header_info = spdif_header_eac3;
300         break;
301     case CODEC_ID_MP1:
302     case CODEC_ID_MP2:
303     case CODEC_ID_MP3:
304         ctx->header_info = spdif_header_mpeg;
305         break;
306     case CODEC_ID_DTS:
307         ctx->header_info = spdif_header_dts;
308         break;
309     case CODEC_ID_AAC:
310         ctx->header_info = spdif_header_aac;
311         break;
312     case CODEC_ID_TRUEHD:
313         ctx->header_info = spdif_header_truehd;
314         ctx->hd_buf = av_malloc(MAT_FRAME_SIZE);
315         if (!ctx->hd_buf)
316             return AVERROR(ENOMEM);
317         break;
318     default:
319         av_log(s, AV_LOG_ERROR, "codec not supported\n");
320         return AVERROR_PATCHWELCOME;
321     }
322     return 0;
323 }
324
325 static int spdif_write_trailer(AVFormatContext *s)
326 {
327     IEC61937Context *ctx = s->priv_data;
328     av_freep(&ctx->buffer);
329     av_freep(&ctx->hd_buf);
330     return 0;
331 }
332
333 static int spdif_write_packet(struct AVFormatContext *s, AVPacket *pkt)
334 {
335     IEC61937Context *ctx = s->priv_data;
336     int ret, padding;
337
338     ctx->out_buf = pkt->data;
339     ctx->out_bytes = pkt->size;
340     ctx->length_code = FFALIGN(pkt->size, 2) << 3;
341     ctx->use_preamble = 1;
342     ctx->extra_bswap = 0;
343
344     ret = ctx->header_info(s, pkt);
345     if (ret < 0)
346         return ret;
347     if (!ctx->pkt_offset)
348         return 0;
349
350     padding = (ctx->pkt_offset - ctx->use_preamble * BURST_HEADER_SIZE - ctx->out_bytes) >> 1;
351     if (padding < 0) {
352         av_log(s, AV_LOG_ERROR, "bitrate is too high\n");
353         return AVERROR(EINVAL);
354     }
355
356     if (ctx->use_preamble) {
357     put_le16(s->pb, SYNCWORD1);      //Pa
358     put_le16(s->pb, SYNCWORD2);      //Pb
359     put_le16(s->pb, ctx->data_type); //Pc
360     put_le16(s->pb, ctx->length_code);//Pd
361     }
362
363     if (HAVE_BIGENDIAN ^ ctx->extra_bswap) {
364     put_buffer(s->pb, ctx->out_buf, ctx->out_bytes & ~1);
365     } else {
366     av_fast_malloc(&ctx->buffer, &ctx->buffer_size, ctx->out_bytes + FF_INPUT_BUFFER_PADDING_SIZE);
367     if (!ctx->buffer)
368         return AVERROR(ENOMEM);
369     ff_spdif_bswap_buf16((uint16_t *)ctx->buffer, (uint16_t *)ctx->out_buf, ctx->out_bytes >> 1);
370     put_buffer(s->pb, ctx->buffer, ctx->out_bytes & ~1);
371     }
372
373     if (ctx->out_bytes & 1)
374         put_be16(s->pb, ctx->out_buf[ctx->out_bytes - 1]);
375
376     for (; padding > 0; padding--)
377         put_be16(s->pb, 0);
378
379     av_log(s, AV_LOG_DEBUG, "type=%x len=%i pkt_offset=%i\n",
380            ctx->data_type, ctx->out_bytes, ctx->pkt_offset);
381
382     put_flush_packet(s->pb);
383     return 0;
384 }
385
386 AVOutputFormat spdif_muxer = {
387     "spdif",
388     NULL_IF_CONFIG_SMALL("IEC 61937 (used on S/PDIF - IEC958)"),
389     NULL,
390     "spdif",
391     sizeof(IEC61937Context),
392     CODEC_ID_AC3,
393     CODEC_ID_NONE,
394     spdif_write_header,
395     spdif_write_packet,
396     spdif_write_trailer,
397 };