]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavformat/mxfenc.c
free audio fifo
[frescor/ffmpeg.git] / libavformat / mxfenc.c
1 /*
2  * MXF muxer
3  * Copyright (c) 2008 GUCAS, Zhentan Feng <spyfeng at gmail dot com>
4  * Copyright (c) 2008 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /*
24  * References
25  * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
26  * SMPTE 377M MXF File Format Specifications
27  * SMPTE 379M MXF Generic Container
28  * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
29  * SMPTE RP210: SMPTE Metadata Dictionary
30  * SMPTE RP224: Registry of SMPTE Universal Labels
31  */
32
33 //#define DEBUG
34
35 #include "libavutil/fifo.h"
36 #include "mxf.h"
37
38 static const int NTSC_samples_per_frame[] = { 1602, 1601, 1602, 1601, 1602, 0 };
39 static const int PAL_samples_per_frame[]  = { 1920, 0 };
40
41 typedef struct {
42     AVFifoBuffer fifo;
43     unsigned fifo_size;           ///< current fifo size allocated
44     uint64_t dts;                 ///< current dts
45     int sample_size;              ///< size of one sample all channels included
46     const int *samples_per_frame; ///< must be 0 terminated
47     const int *samples;           ///< current samples per frame, pointer to samples_per_frame
48 } AudioInterleaveContext;
49
50 typedef struct {
51     int local_tag;
52     UID uid;
53 } MXFLocalTagPair;
54
55 typedef struct {
56     AudioInterleaveContext aic;
57     UID track_essence_element_key;
58     int index;            ///< index in mxf_essence_container_uls table
59     const UID *codec_ul;
60     int64_t duration;
61     int order;            ///< interleaving order if dts are equal
62     int interlaced;       ///< wether picture is interlaced
63 } MXFStreamContext;
64
65 typedef struct {
66     UID container_ul;
67     UID element_ul;
68     UID codec_ul;
69     enum CodecID id;
70     void (*write_desc)();
71 } MXFContainerEssenceEntry;
72
73 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st);
74 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st);
75 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st);
76
77 static const MXFContainerEssenceEntry mxf_essence_container_uls[] = {
78     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 },
79       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
80       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
81       CODEC_ID_MPEG2VIDEO, mxf_write_mpegvideo_desc },
82     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x03,0x00 },
83       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x03,0x00 },
84       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
85       CODEC_ID_PCM_S16LE, mxf_write_aes3_desc },
86     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 },
87       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x01,0x00 },
88       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
89       CODEC_ID_PCM_S16LE, mxf_write_wav_desc },
90     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
91       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
92       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
93       CODEC_ID_NONE, NULL },
94 };
95
96 typedef struct MXFContext {
97     int64_t footer_partition_offset;
98     int essence_container_count;
99     uint8_t essence_containers_indices[FF_ARRAY_ELEMS(mxf_essence_container_uls)];
100     AVRational time_base;
101     int header_written;
102 } MXFContext;
103
104 static const uint8_t uuid_base[]            = { 0xAD,0xAB,0x44,0x24,0x2f,0x25,0x4d,0xc7,0x92,0xff,0x29,0xbd };
105 static const uint8_t umid_base[]            = { 0x06,0x0A,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x01,0x0D,0x00,0x13,0x00,0x00,0x00 };
106
107 /**
108  * complete key for operation pattern, partitions, and primer pack
109  */
110 static const uint8_t op1a_ul[]              = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x01,0x01,0x00 };
111 static const uint8_t footer_partition_key[] = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }; // ClosedComplete
112 static const uint8_t primer_pack_key[]      = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x05,0x01,0x00 };
113
114
115 static const uint8_t header_open_partition_key[]   = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }; // OpenIncomplete
116 static const uint8_t header_closed_partition_key[] = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }; // ClosedComplete
117
118 /**
119  * partial key for header metadata
120  */
121 static const uint8_t header_metadata_key[]  = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01 };
122
123 static const uint8_t multiple_desc_ul[] = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x0D,0x01,0x03,0x01,0x02,0x7F,0x01,0x00 };
124
125 /**
126  * SMPTE RP210 http://www.smpte-ra.org/mdd/index.html
127  */
128 static const MXFLocalTagPair mxf_local_tag_batch[] = {
129     // preface set
130     { 0x3C0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x02,0x00,0x00,0x00,0x00}}, /* Instance UID */
131     { 0x3B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x04,0x00,0x00}}, /* Last Modified Date */
132     { 0x3B05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x01,0x05,0x00,0x00,0x00}}, /* Version */
133     { 0x3B06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x04,0x00,0x00}}, /* Identifications reference */
134     { 0x3B03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x01,0x00,0x00}}, /* Content Storage reference */
135     { 0x3B09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x03,0x00,0x00,0x00,0x00}}, /* Operational Pattern UL */
136     { 0x3B0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x01,0x00,0x00}}, /* Essence Containers UL batch */
137     { 0x3B0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x02,0x00,0x00}}, /* DM Schemes UL batch */
138     // Identification
139     { 0x3C09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x01,0x00,0x00,0x00}}, /* This Generation UID */
140     { 0x3C01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x02,0x01,0x00,0x00}}, /* Company Name */
141     { 0x3C02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x03,0x01,0x00,0x00}}, /* Product Name */
142     { 0x3C04, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x05,0x01,0x00,0x00}}, /* Version String */
143     { 0x3C05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x07,0x00,0x00,0x00}}, /* Product ID */
144     { 0x3C06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x03,0x00,0x00}}, /* Modification Date */
145     // Content Storage
146     { 0x1901, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x01,0x00,0x00}}, /* Package strong reference batch */
147     { 0x1902, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x02,0x00,0x00}}, /* Package strong reference batch */
148     // Essence Container Data
149     { 0x2701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x06,0x01,0x00,0x00,0x00}}, /* Linked Package UID */
150     { 0x3F07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x04,0x00,0x00,0x00,0x00}}, /* BodySID */
151     // Package
152     { 0x4401, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x10,0x00,0x00,0x00,0x00}}, /* Package UID */
153     { 0x4405, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x01,0x03,0x00,0x00}}, /* Package Creation Date */
154     { 0x4404, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x05,0x00,0x00}}, /* Package Modified Date */
155     { 0x4403, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x05,0x00,0x00}}, /* Tracks Strong reference array */
156     { 0x4701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x03,0x00,0x00}}, /* Descriptor */
157     // Track
158     { 0x4801, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x07,0x01,0x01,0x00,0x00,0x00,0x00}}, /* Track ID */
159     { 0x4804, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x04,0x01,0x03,0x00,0x00,0x00,0x00}}, /* Track Number */
160     { 0x4B01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x30,0x04,0x05,0x00,0x00,0x00,0x00}}, /* Edit Rate */
161     { 0x4B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x03,0x00,0x00}}, /* Origin */
162     { 0x4803, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x04,0x00,0x00}}, /* Sequence reference */
163     // Sequence
164     { 0x0201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x07,0x01,0x00,0x00,0x00,0x00,0x00}}, /* Data Definition UL */
165     { 0x0202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x02,0x01,0x01,0x03,0x00,0x00}}, /* Duration */
166     { 0x1001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x09,0x00,0x00}}, /* Structural Components reference array */
167     // Source Clip
168     { 0x1201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x01,0x03,0x01,0x04,0x00,0x00}}, /* Start position */
169     { 0x1101, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x01,0x00,0x00,0x00}}, /* SourcePackageID */
170     { 0x1102, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x02,0x00,0x00,0x00}}, /* SourceTrackID */
171     // File Descriptor
172     { 0x3F01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x04,0x06,0x0B,0x00,0x00}}, /* Sub Descriptors reference array */
173     { 0x3006, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x06,0x01,0x01,0x03,0x05,0x00,0x00,0x00}}, /* Linked Track ID */
174     { 0x3001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x00,0x00,0x00,0x00}}, /* SampleRate */
175     { 0x3004, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x01,0x02,0x00,0x00}}, /* Essence Container */
176     // Generic Picture Essence Descriptor
177     { 0x320C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Frame Layout */
178     { 0x320D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x03,0x02,0x05,0x00,0x00,0x00}}, /* Video Line Map */
179     { 0x3203, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x02,0x00,0x00,0x00}}, /* Stored Width */
180     { 0x3202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x01,0x00,0x00,0x00}}, /* Stored Height */
181     { 0x320E, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x01,0x01,0x01,0x00,0x00,0x00}}, /* Aspect Ratio */
182     { 0x3201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x06,0x01,0x00,0x00,0x00,0x00}}, /* Picture Essence Coding */
183     // Generic Sound Essence Descriptor
184     { 0x3D02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Locked/Unlocked */
185     { 0x3D03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x01,0x01,0x01,0x00,0x00}}, /* Audio sampling rate */
186     { 0x3D07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x01,0x01,0x04,0x00,0x00,0x00}}, /* ChannelCount */
187     { 0x3D01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x03,0x04,0x00,0x00,0x00}}, /* Quantization bits */
188     { 0x3D06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x02,0x04,0x02,0x00,0x00,0x00,0x00}}, /* Sound Essence Compression */
189 };
190
191 static void mxf_write_uuid(ByteIOContext *pb, enum MXFMetadataSetType type, int value)
192 {
193     put_buffer(pb, uuid_base, 12);
194     put_be16(pb, type);
195     put_be16(pb, value);
196 }
197
198 static void mxf_write_umid(ByteIOContext *pb, enum MXFMetadataSetType type, int value)
199 {
200     put_buffer(pb, umid_base, 16);
201     mxf_write_uuid(pb, type, value);
202 }
203
204 static void mxf_write_refs_count(ByteIOContext *pb, int ref_count)
205 {
206     put_be32(pb, ref_count);
207     put_be32(pb, 16);
208 }
209
210 static int klv_encode_ber_length(ByteIOContext *pb, uint64_t len)
211 {
212     // Determine the best BER size
213     int size;
214     if (len < 128) {
215         //short form
216         put_byte(pb, len);
217         return 1;
218     }
219
220     size = (av_log2(len) >> 3) + 1;
221
222     // long form
223     put_byte(pb, 0x80 + size);
224     while(size) {
225         size --;
226         put_byte(pb, len >> 8 * size & 0xff);
227     }
228     return 0;
229 }
230
231 /*
232  * Get essence container ul index
233  */
234 static int mxf_get_essence_container_ul_index(enum CodecID id)
235 {
236     int i;
237     for (i = 0; i < FF_ARRAY_ELEMS(mxf_essence_container_uls); i++)
238         if (mxf_essence_container_uls[i].id == id)
239             return i;
240     return -1;
241 }
242
243 static void mxf_write_primer_pack(AVFormatContext *s)
244 {
245     ByteIOContext *pb = s->pb;
246     int local_tag_number, i = 0;
247
248     local_tag_number = FF_ARRAY_ELEMS(mxf_local_tag_batch);
249
250     put_buffer(pb, primer_pack_key, 16);
251     klv_encode_ber_length(pb, local_tag_number * 18 + 8);
252
253     put_be32(pb, local_tag_number); // local_tag num
254     put_be32(pb, 18); // item size, always 18 according to the specs
255
256     for (i = 0; i < local_tag_number; i++) {
257         put_be16(pb, mxf_local_tag_batch[i].local_tag);
258         put_buffer(pb, mxf_local_tag_batch[i].uid, 16);
259     }
260 }
261
262 static void mxf_write_local_tag(ByteIOContext *pb, int size, int tag)
263 {
264     put_be16(pb, tag);
265     put_be16(pb, size);
266 }
267
268 static void mxf_write_metadata_key(ByteIOContext *pb, unsigned int value)
269 {
270     put_buffer(pb, header_metadata_key, 13);
271     put_be24(pb, value);
272 }
273
274 static void mxf_free(AVFormatContext *s)
275 {
276     int i;
277
278     for (i = 0; i < s->nb_streams; i++) {
279         AVStream *st = s->streams[i];
280         av_freep(&st->priv_data);
281     }
282 }
283
284 static const MXFDataDefinitionUL *mxf_get_data_definition_ul(enum CodecType type)
285 {
286     const MXFDataDefinitionUL *uls = ff_mxf_data_definition_uls;
287     while (uls->type != CODEC_TYPE_DATA) {
288         if (type == uls->type)
289             break;
290         uls++;
291     }
292     return uls;
293 }
294
295 static void mxf_write_essence_container_refs(AVFormatContext *s)
296 {
297     MXFContext *c = s->priv_data;
298     ByteIOContext *pb = s->pb;
299     int i;
300
301     mxf_write_refs_count(pb, c->essence_container_count);
302     av_log(s,AV_LOG_DEBUG, "essence container count:%d\n", c->essence_container_count);
303     for (i = 0; i < c->essence_container_count; i++) {
304         put_buffer(pb, mxf_essence_container_uls[c->essence_containers_indices[i]].container_ul, 16);
305         PRINT_KEY(s, "essence container ul:\n", mxf_essence_container_uls[c->essence_containers_indices[i]].container_ul);
306     }
307 }
308
309 static void mxf_write_preface(AVFormatContext *s)
310 {
311     MXFContext *mxf = s->priv_data;
312     ByteIOContext *pb = s->pb;
313
314     mxf_write_metadata_key(pb, 0x012f00);
315     PRINT_KEY(s, "preface key", pb->buf_ptr - 16);
316     klv_encode_ber_length(pb, 130 + 16 * mxf->essence_container_count);
317
318     // write preface set uid
319     mxf_write_local_tag(pb, 16, 0x3C0A);
320     mxf_write_uuid(pb, Preface, 0);
321     PRINT_KEY(s, "preface uid", pb->buf_ptr - 16);
322
323     // write create date as unknown
324     mxf_write_local_tag(pb, 8, 0x3B02);
325     put_be64(pb, 0);
326
327     // write version
328     mxf_write_local_tag(pb, 2, 0x3B05);
329     put_be16(pb, 1);
330
331     // write identification_refs
332     mxf_write_local_tag(pb, 16 + 8, 0x3B06);
333     mxf_write_refs_count(pb, 1);
334     mxf_write_uuid(pb, Identification, 0);
335
336     // write content_storage_refs
337     mxf_write_local_tag(pb, 16, 0x3B03);
338     mxf_write_uuid(pb, ContentStorage, 0);
339
340     mxf_write_local_tag(pb, 16, 0x3B09);
341     put_buffer(pb, op1a_ul, 16);
342
343     // write essence_container_refs
344     mxf_write_local_tag(pb, 8 + 16 * mxf->essence_container_count, 0x3B0A);
345     mxf_write_essence_container_refs(s);
346
347     // write dm_scheme_refs
348     mxf_write_local_tag(pb, 8, 0x3B0B);
349     put_be64(pb, 0);
350 }
351
352 /*
353  * Write a local tag containing an ascii string as utf-16
354  */
355 static void mxf_write_local_tag_utf16(ByteIOContext *pb, int tag, const char *value)
356 {
357     int i, size = strlen(value);
358     mxf_write_local_tag(pb, size*2, tag);
359     for (i = 0; i < size; i++)
360         put_be16(pb, value[i]);
361 }
362
363 static void mxf_write_identification(AVFormatContext *s)
364 {
365     ByteIOContext *pb = s->pb;
366     const char *company = "FFmpeg";
367     const char *product = "OP1a Muxer";
368     const char *version;
369     int length;
370
371     mxf_write_metadata_key(pb, 0x013000);
372     PRINT_KEY(s, "identification key", pb->buf_ptr - 16);
373
374     version = s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT ?
375         "0.0.0" : AV_STRINGIFY(LIBAVFORMAT_VERSION);
376     length = 84 + (strlen(company)+strlen(product)+strlen(version))*2; // utf-16
377     klv_encode_ber_length(pb, length);
378
379     // write uid
380     mxf_write_local_tag(pb, 16, 0x3C0A);
381     mxf_write_uuid(pb, Identification, 0);
382     PRINT_KEY(s, "identification uid", pb->buf_ptr - 16);
383
384     // write generation uid
385     mxf_write_local_tag(pb, 16, 0x3C09);
386     mxf_write_uuid(pb, Identification, 1);
387
388     mxf_write_local_tag_utf16(pb, 0x3C01, company); // Company Name
389     mxf_write_local_tag_utf16(pb, 0x3C02, product); // Product Name
390     mxf_write_local_tag_utf16(pb, 0x3C04, version); // Version String
391
392     // write product uid
393     mxf_write_local_tag(pb, 16, 0x3C05);
394     mxf_write_uuid(pb, Identification, 2);
395
396     // write modified date
397     mxf_write_local_tag(pb, 8, 0x3C06);
398     put_be64(pb, 0);
399 }
400
401 static void mxf_write_content_storage(AVFormatContext *s)
402 {
403     ByteIOContext *pb = s->pb;
404
405     mxf_write_metadata_key(pb, 0x011800);
406     PRINT_KEY(s, "content storage key", pb->buf_ptr - 16);
407     klv_encode_ber_length(pb, 92);
408
409     // write uid
410     mxf_write_local_tag(pb, 16, 0x3C0A);
411     mxf_write_uuid(pb, ContentStorage, 0);
412     PRINT_KEY(s, "content storage uid", pb->buf_ptr - 16);
413
414     // write package reference
415     mxf_write_local_tag(pb, 16 * 2 + 8, 0x1901);
416     mxf_write_refs_count(pb, 2);
417     mxf_write_uuid(pb, MaterialPackage, 0);
418     mxf_write_uuid(pb, SourcePackage, 0);
419
420     // write essence container data
421     mxf_write_local_tag(pb, 8 + 16, 0x1902);
422     mxf_write_refs_count(pb, 1);
423     mxf_write_uuid(pb, EssenceContainerData, 0);
424 }
425
426 static void mxf_write_track(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
427 {
428     ByteIOContext *pb = s->pb;
429     MXFStreamContext *sc = st->priv_data;
430
431     mxf_write_metadata_key(pb, 0x013b00);
432     PRINT_KEY(s, "track key", pb->buf_ptr - 16);
433     klv_encode_ber_length(pb, 80);
434
435     // write track uid
436     mxf_write_local_tag(pb, 16, 0x3C0A);
437     mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, st->index);
438     PRINT_KEY(s, "track uid", pb->buf_ptr - 16);
439
440     // write track id
441     mxf_write_local_tag(pb, 4, 0x4801);
442     put_be32(pb, st->index);
443
444     // write track number
445     mxf_write_local_tag(pb, 4, 0x4804);
446     if (type == MaterialPackage)
447         put_be32(pb, 0); // track number of material package is 0
448     else
449         put_buffer(pb, sc->track_essence_element_key + 12, 4);
450
451     mxf_write_local_tag(pb, 8, 0x4B01);
452     put_be32(pb, st->time_base.den);
453     put_be32(pb, st->time_base.num);
454
455     // write origin
456     mxf_write_local_tag(pb, 8, 0x4B02);
457     put_be64(pb, 0);
458
459     // write sequence refs
460     mxf_write_local_tag(pb, 16, 0x4803);
461     mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
462 }
463
464 static void mxf_write_common_fields(ByteIOContext *pb, AVStream *st)
465 {
466     const MXFDataDefinitionUL *data_def_ul = mxf_get_data_definition_ul(st->codec->codec_type);
467     MXFStreamContext *sc = st->priv_data;
468
469     // find data define uls
470     mxf_write_local_tag(pb, 16, 0x0201);
471     put_buffer(pb, data_def_ul->uid, 16);
472
473     // write duration
474     mxf_write_local_tag(pb, 8, 0x0202);
475     put_be64(pb, sc->duration);
476 }
477
478 static void mxf_write_sequence(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
479 {
480     ByteIOContext *pb = s->pb;
481
482     mxf_write_metadata_key(pb, 0x010f00);
483     PRINT_KEY(s, "sequence key", pb->buf_ptr - 16);
484     klv_encode_ber_length(pb, 80);
485
486     mxf_write_local_tag(pb, 16, 0x3C0A);
487     mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
488
489     PRINT_KEY(s, "sequence uid", pb->buf_ptr - 16);
490     mxf_write_common_fields(pb, st);
491
492     // write structural component
493     mxf_write_local_tag(pb, 16 + 8, 0x1001);
494     mxf_write_refs_count(pb, 1);
495     mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
496 }
497
498 static void mxf_write_structural_component(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
499 {
500     ByteIOContext *pb = s->pb;
501     int i;
502
503     mxf_write_metadata_key(pb, 0x011100);
504     PRINT_KEY(s, "sturctural component key", pb->buf_ptr - 16);
505     klv_encode_ber_length(pb, 108);
506
507     // write uid
508     mxf_write_local_tag(pb, 16, 0x3C0A);
509     mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
510
511     PRINT_KEY(s, "structural component uid", pb->buf_ptr - 16);
512     mxf_write_common_fields(pb, st);
513
514     // write start_position
515     mxf_write_local_tag(pb, 8, 0x1201);
516     put_be64(pb, 0);
517
518     // write source package uid, end of the reference
519     mxf_write_local_tag(pb, 32, 0x1101);
520     if (type == SourcePackage) {
521         for (i = 0; i < 4; i++)
522             put_be64(pb, 0);
523     } else
524         mxf_write_umid(pb, SourcePackage, 0);
525
526     // write source track id
527     mxf_write_local_tag(pb, 4, 0x1102);
528     if (type == SourcePackage)
529         put_be32(pb, 0);
530     else
531         put_be32(pb, st->index);
532 }
533
534 static void mxf_write_multi_descriptor(AVFormatContext *s)
535 {
536     ByteIOContext *pb = s->pb;
537     int i;
538
539     mxf_write_metadata_key(pb, 0x014400);
540     PRINT_KEY(s, "multiple descriptor key", pb->buf_ptr - 16);
541     klv_encode_ber_length(pb, 64 + 16 * s->nb_streams);
542
543     mxf_write_local_tag(pb, 16, 0x3C0A);
544     mxf_write_uuid(pb, MultipleDescriptor, 0);
545     PRINT_KEY(s, "multi_desc uid", pb->buf_ptr - 16);
546
547     // write sample rate
548     mxf_write_local_tag(pb, 8, 0x3001);
549     put_be32(pb, s->streams[0]->time_base.den);
550     put_be32(pb, s->streams[0]->time_base.num);
551
552     // write essence container ul
553     mxf_write_local_tag(pb, 16, 0x3004);
554     put_buffer(pb, multiple_desc_ul, 16);
555
556     // write sub descriptor refs
557     mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x3F01);
558     mxf_write_refs_count(pb, s->nb_streams);
559     for (i = 0; i < s->nb_streams; i++)
560         mxf_write_uuid(pb, SubDescriptor, i);
561 }
562
563 static void mxf_write_generic_desc(ByteIOContext *pb, AVStream *st, const UID key, unsigned size)
564 {
565     MXFStreamContext *sc = st->priv_data;
566
567     put_buffer(pb, key, 16);
568     klv_encode_ber_length(pb, size);
569
570     mxf_write_local_tag(pb, 16, 0x3C0A);
571     mxf_write_uuid(pb, SubDescriptor, st->index);
572
573     mxf_write_local_tag(pb, 4, 0x3006);
574     put_be32(pb, st->index);
575
576     mxf_write_local_tag(pb, 8, 0x3001);
577     put_be32(pb, st->time_base.den);
578     put_be32(pb, st->time_base.num);
579
580     mxf_write_local_tag(pb, 16, 0x3004);
581     put_buffer(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
582 }
583
584 static const UID mxf_mpegvideo_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 };
585 static const UID mxf_wav_descriptor_key       = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 };
586 static const UID mxf_aes3_descriptor_key      = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 };
587
588 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st)
589 {
590     MXFStreamContext *sc = st->priv_data;
591     ByteIOContext *pb = s->pb;
592     int stored_height = (st->codec->height+15)/16*16;
593     AVRational dar;
594     int f1, f2;
595
596     mxf_write_generic_desc(pb, st, mxf_mpegvideo_descriptor_key, 133);
597
598     mxf_write_local_tag(pb, 4, 0x3203);
599     put_be32(pb, st->codec->width);
600
601     mxf_write_local_tag(pb, 4, 0x3202);
602     put_be32(pb, stored_height>>sc->interlaced);
603
604     // frame layout
605     mxf_write_local_tag(pb, 1, 0x320C);
606     put_byte(pb, sc->interlaced);
607
608     // video line map
609     mxf_write_local_tag(pb, 16, 0x320D);
610     put_be32(pb, 2);
611     put_be32(pb, 4);
612     switch (st->codec->height) {
613     case  576: f1 = 23; f2 = 336; break;
614     case  608: f1 =  7; f2 = 320; break;
615     case  480: f1 = 20; f2 = 283; break;
616     case  512: f1 =  7; f2 = 270; break;
617     case  720: f1 = 26; f2 =   0; break; // progressive
618     case 1080: f1 = 21; f2 = 584; break;
619     default:   f1 =  0; f2 =   0; break;
620     }
621
622     if (!sc->interlaced) {
623         f2  = 0;
624         f1 *= 2;
625     }
626
627     put_be32(pb, f1);
628     put_be32(pb, f2);
629
630     av_reduce(&dar.num, &dar.den,
631               st->codec->width*st->codec->sample_aspect_ratio.num,
632               st->codec->height*st->codec->sample_aspect_ratio.den,
633               1024*1024);
634
635     mxf_write_local_tag(pb, 8, 0x320E);
636     put_be32(pb, dar.num);
637     put_be32(pb, dar.den);
638
639     mxf_write_local_tag(pb, 16, 0x3201);
640     put_buffer(pb, *sc->codec_ul, 16);
641 }
642
643 static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
644 {
645     ByteIOContext *pb = s->pb;
646
647     mxf_write_generic_desc(pb, st, key, size);
648
649     // audio locked
650     mxf_write_local_tag(pb, 1, 0x3D02);
651     put_byte(pb, 1);
652
653     // write audio sampling rate
654     mxf_write_local_tag(pb, 8, 0x3D03);
655     put_be32(pb, st->codec->sample_rate);
656     put_be32(pb, 1);
657
658     mxf_write_local_tag(pb, 4, 0x3D07);
659     put_be32(pb, st->codec->channels);
660
661     mxf_write_local_tag(pb, 4, 0x3D01);
662     put_be32(pb, st->codec->bits_per_coded_sample);
663 }
664
665 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st)
666 {
667     mxf_write_generic_sound_desc(s, st, mxf_wav_descriptor_key, 93);
668 }
669
670 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st)
671 {
672     mxf_write_generic_sound_desc(s, st, mxf_aes3_descriptor_key, 93);
673 }
674
675 static void mxf_write_package(AVFormatContext *s, enum MXFMetadataSetType type)
676 {
677     ByteIOContext *pb = s->pb;
678     int i;
679
680     if (type == MaterialPackage) {
681         mxf_write_metadata_key(pb, 0x013600);
682         PRINT_KEY(s, "Material Package key", pb->buf_ptr - 16);
683         klv_encode_ber_length(pb, 92 + 16 * s->nb_streams);
684     } else {
685         mxf_write_metadata_key(pb, 0x013700);
686         PRINT_KEY(s, "Source Package key", pb->buf_ptr - 16);
687         klv_encode_ber_length(pb, 112 + 16 * s->nb_streams); // 20 bytes length for descriptor reference
688     }
689
690     // write uid
691     mxf_write_local_tag(pb, 16, 0x3C0A);
692     mxf_write_uuid(pb, type, 0);
693     av_log(s,AV_LOG_DEBUG, "package type:%d\n", type);
694     PRINT_KEY(s, "package uid", pb->buf_ptr - 16);
695
696     // write package umid
697     mxf_write_local_tag(pb, 32, 0x4401);
698     mxf_write_umid(pb, type, 0);
699     PRINT_KEY(s, "package umid second part", pb->buf_ptr - 16);
700
701     // write create date
702     mxf_write_local_tag(pb, 8, 0x4405);
703     put_be64(pb, 0);
704
705     // write modified date
706     mxf_write_local_tag(pb, 8, 0x4404);
707     put_be64(pb, 0);
708
709     // write track refs
710     mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x4403);
711     mxf_write_refs_count(pb, s->nb_streams);
712     for (i = 0; i < s->nb_streams; i++)
713         mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, i);
714
715     // write multiple descriptor reference
716     if (type == SourcePackage) {
717         mxf_write_local_tag(pb, 16, 0x4701);
718         if (s->nb_streams > 1) {
719             mxf_write_uuid(pb, MultipleDescriptor, 0);
720             mxf_write_multi_descriptor(s);
721         } else
722             mxf_write_uuid(pb, SubDescriptor, 0);
723     }
724
725     for (i = 0; i < s->nb_streams; i++) {
726         AVStream *st = s->streams[i];
727         mxf_write_track(s, st, type);
728         mxf_write_sequence(s, st, type);
729         mxf_write_structural_component(s, st, type);
730
731         if (type == SourcePackage) {
732             MXFStreamContext *sc = st->priv_data;
733             mxf_essence_container_uls[sc->index].write_desc(s, st);
734         }
735     }
736 }
737
738 static int mxf_write_essence_container_data(AVFormatContext *s)
739 {
740     ByteIOContext *pb = s->pb;
741
742     mxf_write_metadata_key(pb, 0x012300);
743     klv_encode_ber_length(pb, 64);
744
745     mxf_write_local_tag(pb, 16, 0x3C0A); // Instance UID
746     mxf_write_uuid(pb, EssenceContainerData, 0);
747
748     mxf_write_local_tag(pb, 32, 0x2701); // Linked Package UID
749     mxf_write_umid(pb, SourcePackage, 0);
750
751     mxf_write_local_tag(pb, 4, 0x3F07); // BodySID
752     put_be32(pb, 1);
753
754     return 0;
755 }
756
757 static int mxf_write_header_metadata_sets(AVFormatContext *s)
758 {
759     mxf_write_preface(s);
760     mxf_write_identification(s);
761     mxf_write_content_storage(s);
762     mxf_write_package(s, MaterialPackage);
763     mxf_write_package(s, SourcePackage);
764     mxf_write_essence_container_data(s);
765     return 0;
766 }
767
768 static void mxf_write_partition(AVFormatContext *s, int bodysid, const uint8_t *key, int write_metadata)
769 {
770     MXFContext *mxf = s->priv_data;
771     ByteIOContext *pb = s->pb;
772     int64_t header_byte_count_offset;
773
774     // write klv
775     put_buffer(pb, key, 16);
776
777     klv_encode_ber_length(pb, 88 + 16 * mxf->essence_container_count);
778
779     // write partition value
780     put_be16(pb, 1); // majorVersion
781     put_be16(pb, 2); // minorVersion
782     put_be32(pb, 1); // kagSize
783
784     put_be64(pb, url_ftell(pb) - 25); // thisPartition
785     put_be64(pb, 0); // previousPartition
786
787     put_be64(pb, mxf->footer_partition_offset); // footerPartition
788
789     // set offset
790     header_byte_count_offset = url_ftell(pb);
791     put_be64(pb, 0); // headerByteCount, update later
792
793     // no indexTable
794     put_be64(pb, 0); // indexByteCount
795     put_be32(pb, 0); // indexSID
796     put_be64(pb, 0); // bodyOffset
797
798     put_be32(pb, bodysid); // bodySID
799     put_buffer(pb, op1a_ul, 16); // operational pattern
800
801     // essence container
802     mxf_write_essence_container_refs(s);
803
804     if (write_metadata) {
805         // mark the start of the headermetadata and calculate metadata size
806         int64_t pos, start = url_ftell(s->pb);
807         mxf_write_primer_pack(s);
808         mxf_write_header_metadata_sets(s);
809         pos = url_ftell(s->pb);
810         // update header_byte_count
811         url_fseek(pb, header_byte_count_offset, SEEK_SET);
812         put_be64(pb, pos - start);
813         url_fseek(pb, pos, SEEK_SET);
814     }
815
816     put_flush_packet(pb);
817 }
818
819 static const UID mxf_mpeg2_codec_uls[] = {
820     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x10,0x00 }, // MP-ML I-Frame
821     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, // MP-ML Long GOP
822     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, // 422P-ML I-Frame
823     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, // 422P-ML Long GOP
824     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x02,0x00 }, // MP-HL I-Frame
825     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, // MP-HL Long GOP
826     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, // 422P-HL I-Frame
827     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, // 422P-HL Long GOP
828 };
829
830 static const UID *mxf_get_mpeg2_codec_ul(AVCodecContext *avctx)
831 {
832     if (avctx->profile == 4) { // Main
833         if (avctx->level == 8) // Main
834             return avctx->gop_size ?
835                 &mxf_mpeg2_codec_uls[1] :
836                 &mxf_mpeg2_codec_uls[0];
837         else if (avctx->level == 4) // High
838             return avctx->gop_size ?
839                 &mxf_mpeg2_codec_uls[5] :
840                 &mxf_mpeg2_codec_uls[4];
841     } else if (avctx->profile == 0) { // 422
842         if (avctx->level == 5) // Main
843             return avctx->gop_size ?
844                 &mxf_mpeg2_codec_uls[3] :
845                 &mxf_mpeg2_codec_uls[2];
846         else if (avctx->level == 2) // High
847             return avctx->gop_size ?
848                 &mxf_mpeg2_codec_uls[7] :
849                 &mxf_mpeg2_codec_uls[6];
850     }
851     return NULL;
852 }
853
854 static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
855 {
856     MXFStreamContext *sc = st->priv_data;
857     uint32_t c = -1;
858     int i;
859
860     for(i = 0; i < pkt->size - 4; i++) {
861         c = (c<<8) + pkt->data[i];
862         if (c == 0x1B5) {
863             if (i + 2 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x10) { // seq ext
864                 st->codec->profile = pkt->data[i+1] & 0x07;
865                 st->codec->level   = pkt->data[i+2] >> 4;
866             } else if (i + 5 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x80) { // pict coding ext
867                 sc->interlaced = !(pkt->data[i+5] & 0x80); // progressive frame
868                 break;
869             }
870         }
871     }
872     sc->codec_ul = mxf_get_mpeg2_codec_ul(st->codec);
873     return !!sc->codec_ul;
874 }
875
876 static int ff_audio_interleave_init(AVFormatContext *s, const int *samples_per_frame)
877 {
878     int i;
879
880     if (!samples_per_frame)
881         return -1;
882
883     for (i = 0; i < s->nb_streams; i++) {
884         AVStream *st = s->streams[i];
885         AudioInterleaveContext *aic = st->priv_data;
886
887         if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
888             aic->sample_size = (st->codec->channels *
889                                 av_get_bits_per_sample(st->codec->codec_id)) / 8;
890             if (!aic->sample_size) {
891                 av_log(s, AV_LOG_ERROR, "could not compute sample size\n");
892                 return -1;
893             }
894             aic->samples_per_frame = samples_per_frame;
895             aic->samples = aic->samples_per_frame;
896
897             av_fifo_init(&aic->fifo, 100 * *aic->samples);
898         }
899     }
900
901     return 0;
902 }
903
904 static void ff_audio_interleave_close(AVFormatContext *s)
905 {
906     int i;
907     for (i = 0; i < s->nb_streams; i++) {
908         AVStream *st = s->streams[i];
909         AudioInterleaveContext *aic = st->priv_data;
910
911         if (st->codec->codec_type == CODEC_TYPE_AUDIO)
912             av_fifo_free(&aic->fifo);
913     }
914 }
915
916 static int mxf_write_header(AVFormatContext *s)
917 {
918     MXFContext *mxf = s->priv_data;
919     int i;
920     uint8_t present[FF_ARRAY_ELEMS(mxf_essence_container_uls)] = {0};
921     const int *samples_per_frame = NULL;
922
923     for (i = 0; i < s->nb_streams; i++) {
924         AVStream *st = s->streams[i];
925         MXFStreamContext *sc = av_mallocz(sizeof(*sc));
926         if (!sc)
927             return AVERROR(ENOMEM);
928         st->priv_data = sc;
929
930         if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
931             if (!av_cmp_q(st->codec->time_base, (AVRational){ 1, 25 })) {
932                 samples_per_frame = PAL_samples_per_frame;
933                 mxf->time_base = (AVRational){ 1, 25 };
934             } else if (!av_cmp_q(st->codec->time_base, (AVRational){ 1001, 30000 })) {
935                 samples_per_frame = NTSC_samples_per_frame;
936                 mxf->time_base = (AVRational){ 1001, 30000 };
937             } else {
938                 av_log(s, AV_LOG_ERROR, "unsupported video frame rate\n");
939                 return -1;
940             }
941         } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
942             if (st->codec->sample_rate != 48000) {
943                 av_log(s, AV_LOG_ERROR, "only 48khz is implemented\n");
944                 return -1;
945             }
946         }
947         sc->duration = -1;
948
949         sc->index = mxf_get_essence_container_ul_index(st->codec->codec_id);
950         if (sc->index == -1) {
951             av_log(s, AV_LOG_ERROR, "track %d: could not find essence container ul, "
952                    "codec not currently supported in container\n", i);
953             return -1;
954         }
955
956         sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
957
958         if (!present[sc->index]) {
959             mxf->essence_containers_indices[mxf->essence_container_count++] = sc->index;
960             present[sc->index] = 1;
961         } else
962             present[sc->index]++;
963         memcpy(sc->track_essence_element_key, mxf_essence_container_uls[sc->index].element_ul, 15);
964         sc->track_essence_element_key[15] = present[sc->index];
965         PRINT_KEY(s, "track essence element key", sc->track_essence_element_key);
966     }
967
968     for (i = 0; i < s->nb_streams; i++) {
969         MXFStreamContext *sc = s->streams[i]->priv_data;
970         av_set_pts_info(s->streams[i], 64, mxf->time_base.num, mxf->time_base.den);
971         // update element count
972         sc->track_essence_element_key[13] = present[sc->index];
973         sc->order = AV_RB32(sc->track_essence_element_key+12);
974     }
975
976     if (!samples_per_frame)
977         samples_per_frame = PAL_samples_per_frame;
978
979     if (ff_audio_interleave_init(s, samples_per_frame) < 0)
980         return -1;
981
982     return 0;
983 }
984
985 static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
986 {
987     MXFContext *mxf = s->priv_data;
988     ByteIOContext *pb = s->pb;
989     AVStream *st = s->streams[pkt->stream_index];
990     MXFStreamContext *sc = st->priv_data;
991
992     if (!mxf->header_written) {
993         if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO) {
994             if (!mxf_parse_mpeg2_frame(s, st, pkt)) {
995                 av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
996                 return -1;
997             }
998         }
999         mxf_write_partition(s, 1, header_open_partition_key, 1);
1000         mxf->header_written = 1;
1001     }
1002
1003     put_buffer(pb, sc->track_essence_element_key, 16); // write key
1004     klv_encode_ber_length(pb, pkt->size); // write length
1005     put_buffer(pb, pkt->data, pkt->size); // write value
1006
1007     sc->duration = FFMAX(pkt->pts + pkt->duration, sc->duration);
1008
1009     put_flush_packet(pb);
1010     return 0;
1011 }
1012
1013 static int mxf_write_footer(AVFormatContext *s)
1014 {
1015     MXFContext *mxf = s->priv_data;
1016     ByteIOContext *pb = s->pb;
1017
1018     mxf->footer_partition_offset = url_ftell(pb);
1019     mxf_write_partition(s, 0, footer_partition_key, 0);
1020     if (!url_is_streamed(s->pb)) {
1021         url_fseek(pb, 0, SEEK_SET);
1022         mxf_write_partition(s, 1, header_closed_partition_key, 1);
1023     }
1024
1025     ff_audio_interleave_close(s);
1026
1027     mxf_free(s);
1028     return 0;
1029 }
1030
1031 static int mxf_interleave_new_audio_packet(AVFormatContext *s, AVPacket *pkt,
1032                                            int stream_index, int flush)
1033 {
1034     AVStream *st = s->streams[stream_index];
1035     AudioInterleaveContext *aic = st->priv_data;
1036
1037     int size = FFMIN(av_fifo_size(&aic->fifo), *aic->samples * aic->sample_size);
1038     if (!size || (!flush && size == av_fifo_size(&aic->fifo)))
1039         return 0;
1040
1041     av_new_packet(pkt, size);
1042     av_fifo_read(&aic->fifo, pkt->data, size);
1043
1044     pkt->dts = pkt->pts = aic->dts;
1045     pkt->duration = av_rescale_q(*aic->samples,
1046                                  (AVRational){ 1, st->codec->sample_rate },
1047                                  st->time_base);
1048     pkt->stream_index = stream_index;
1049     aic->dts += pkt->duration;
1050
1051     aic->samples++;
1052     if (!*aic->samples)
1053         aic->samples = aic->samples_per_frame;
1054
1055     return size;
1056 }
1057
1058 static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1059 {
1060     AVPacketList *pktl;
1061     int stream_count = 0;
1062     int streams[MAX_STREAMS];
1063
1064     memset(streams, 0, sizeof(streams));
1065     pktl = s->packet_buffer;
1066     while (pktl) {
1067         //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
1068         if (!streams[pktl->pkt.stream_index])
1069             stream_count++;
1070         streams[pktl->pkt.stream_index]++;
1071         pktl = pktl->next;
1072     }
1073
1074     if (stream_count && (s->nb_streams == stream_count || flush)) {
1075         pktl = s->packet_buffer;
1076         *out = pktl->pkt;
1077         //av_log(s, AV_LOG_DEBUG, "out st:%d dts:%lld\n", (*out).stream_index, (*out).dts);
1078         s->packet_buffer = pktl->next;
1079         av_freep(&pktl);
1080
1081         if (flush && stream_count < s->nb_streams) {
1082             // purge packet queue
1083             pktl = s->packet_buffer;
1084             while (pktl) {
1085                 AVPacketList *next = pktl->next;
1086                 av_free_packet(&pktl->pkt);
1087                 av_freep(&pktl);
1088                 pktl = next;
1089             }
1090             s->packet_buffer = NULL;
1091         }
1092
1093         return 1;
1094     } else {
1095         av_init_packet(out);
1096         return 0;
1097     }
1098 }
1099
1100 static int mxf_compare_timestamps(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
1101 {
1102     AVStream *st  = s->streams[pkt ->stream_index];
1103     AVStream *st2 = s->streams[next->stream_index];
1104     MXFStreamContext *sc  = st ->priv_data;
1105     MXFStreamContext *sc2 = st2->priv_data;
1106
1107     int64_t left  = st2->time_base.num * (int64_t)st ->time_base.den;
1108     int64_t right = st ->time_base.num * (int64_t)st2->time_base.den;
1109
1110     return next->dts * left > pkt->dts * right || // FIXME this can overflow
1111         (next->dts * left == pkt->dts * right && sc->order < sc2->order);
1112 }
1113
1114 static int mxf_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1115 {
1116     int i;
1117
1118     if (pkt) {
1119         AVStream *st = s->streams[pkt->stream_index];
1120         AudioInterleaveContext *aic = st->priv_data;
1121         if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1122             av_fifo_generic_write(&aic->fifo, pkt->data, pkt->size, NULL);
1123         } else {
1124             // rewrite pts and dts to be decoded time line position
1125             pkt->pts = pkt->dts = aic->dts;
1126             aic->dts += pkt->duration;
1127             ff_interleave_add_packet(s, pkt, mxf_compare_timestamps);
1128         }
1129         pkt = NULL;
1130     }
1131
1132     for (i = 0; i < s->nb_streams; i++) {
1133         AVStream *st = s->streams[i];
1134         if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1135             AVPacket new_pkt;
1136             while (mxf_interleave_new_audio_packet(s, &new_pkt, i, flush))
1137                 ff_interleave_add_packet(s, &new_pkt, mxf_compare_timestamps);
1138         }
1139     }
1140
1141     return mxf_interleave_get_packet(s, out, pkt, flush);
1142 }
1143
1144 AVOutputFormat mxf_muxer = {
1145     "mxf",
1146     NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1147     NULL,
1148     "mxf",
1149     sizeof(MXFContext),
1150     CODEC_ID_PCM_S16LE,
1151     CODEC_ID_MPEG2VIDEO,
1152     mxf_write_header,
1153     mxf_write_packet,
1154     mxf_write_footer,
1155     0,
1156     NULL,
1157     mxf_interleave,
1158 };