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