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