header partition is open incomplete for now
[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 "mxf.h"
35
36 typedef struct {
37     int local_tag;
38     UID uid;
39 } MXFLocalTagPair;
40
41 typedef struct {
42     UID track_essence_element_key;
43     const UID *essence_container_ul;
44     const UID *codec_ul;
45     int64_t duration;
46 } MXFStreamContext;
47
48 typedef struct {
49     UID container_ul;
50     UID element_ul;
51     UID codec_ul;
52     enum CodecID id;
53 } MXFContainerEssencePair;
54
55 static const MXFContainerEssencePair mxf_essence_container_uls[] = {
56     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 },
57       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
58       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 }, CODEC_ID_MPEG2VIDEO },
59     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 },
60       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x01,0x00 },
61       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 }, CODEC_ID_PCM_S16LE },
62     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
63       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
64       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, CODEC_ID_NONE },
65 };
66
67 typedef struct MXFContext {
68     int64_t header_byte_count;
69     int64_t header_byte_count_offset;
70     int64_t header_footer_partition_offset;
71     int essence_container_count;
72     uint8_t essence_containers_indices[sizeof(mxf_essence_container_uls)/
73                                        sizeof(*mxf_essence_container_uls)];
74 } MXFContext;
75
76 typedef struct {
77     const UID key;
78     void (*write)();
79     enum CodecType type;
80 } MXFDescriptorWriteTableEntry;
81
82 static const uint8_t uuid_base[]            = { 0xAD,0xAB,0x44,0x24,0x2f,0x25,0x4d,0xc7,0x92,0xff,0x29,0xbd };
83 static const uint8_t umid_base[]            = { 0x06,0x0A,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x0F,0x00,0x13,0x00,0x00,0x00 };
84
85 /**
86  * complete key for operation pattern, partitions, and primer pack
87  */
88 static const uint8_t op1a_ul[]              = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x01,0x01,0x00 };
89 static const uint8_t footer_partition_key[] = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }; // ClosedComplete
90 static const uint8_t primer_pack_key[]      = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x05,0x01,0x00 };
91
92
93 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
94 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
95
96 /**
97  * partial key for header metadata
98  */
99 static const uint8_t header_metadata_key[]  = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01 };
100
101 static const uint8_t multiple_desc_ul[] = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x0D,0x01,0x03,0x01,0x02,0x7F,0x01,0x00 };
102
103 /**
104  * SMPTE RP210 http://www.smpte-ra.org/mdd/index.html
105  */
106 static const MXFLocalTagPair mxf_local_tag_batch[] = {
107     // preface set
108     { 0x3C0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x02,0x00,0x00,0x00,0x00}}, /* Instance UID */
109     { 0x3B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x04,0x00,0x00}}, /* Last Modified Date */
110     { 0x3B05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x01,0x05,0x00,0x00,0x00}}, /* Version */
111     { 0x3B06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x04,0x00,0x00}}, /* Identifications reference */
112     { 0x3B03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x01,0x00,0x00}}, /* Content Storage reference */
113     { 0x3B09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x03,0x00,0x00,0x00,0x00}}, /* Operational Pattern UL */
114     { 0x3B0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x01,0x00,0x00}}, /* Essence Containers UL batch */
115     { 0x3B0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x02,0x00,0x00}}, /* DM Schemes UL batch */
116     // Identification
117     { 0x3C09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x01,0x00,0x00,0x00}}, /* This Generation UID */
118     { 0x3C01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x02,0x01,0x00,0x00}}, /* Company Name */
119     { 0x3C02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x03,0x01,0x00,0x00}}, /* Product Name */
120     { 0x3C04, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x05,0x01,0x00,0x00}}, /* Version String */
121     { 0x3C05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x07,0x00,0x00,0x00}}, /* Product ID */
122     { 0x3C06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x03,0x00,0x00}}, /* Modification Date */
123     // Content Storage
124     { 0x1901, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x01,0x00,0x00}}, /* Package strong reference batch */
125     // Essence Container Data
126     { 0x2701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x06,0x01,0x00,0x00,0x00}}, /* Linked Package UID */
127     { 0x3F07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x04,0x00,0x00,0x00,0x00}}, /* BodySID */
128     // Package
129     { 0x4401, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x10,0x00,0x00,0x00,0x00}}, /* Package UID */
130     { 0x4405, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x01,0x03,0x00,0x00}}, /* Package Creation Date */
131     { 0x4404, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x05,0x00,0x00}}, /* Package Modified Date */
132     { 0x4403, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x05,0x00,0x00}}, /* Tracks Strong reference array */
133     { 0x4701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x03,0x00,0x00}}, /* Descriptor */
134     // Track
135     { 0x4801, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x07,0x01,0x01,0x00,0x00,0x00,0x00}}, /* Track ID */
136     { 0x4804, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x04,0x01,0x03,0x00,0x00,0x00,0x00}}, /* Track Number */
137     { 0x4B01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x30,0x04,0x05,0x00,0x00,0x00,0x00}}, /* Edit Rate */
138     { 0x4B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x03,0x00,0x00}}, /* Origin */
139     { 0x4803, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x04,0x00,0x00}}, /* Sequence reference */
140     // Sequence
141     { 0x0201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x07,0x01,0x00,0x00,0x00,0x00,0x00}}, /* Data Definition UL */
142     { 0x0202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x02,0x01,0x01,0x03,0x00,0x00}}, /* Duration */
143     { 0x1001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x09,0x00,0x00}}, /* Structural Components reference array */
144     // Source Clip
145     { 0x1201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x01,0x03,0x01,0x0A,0x00,0x00}}, /* Start position */
146     { 0x1101, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x01,0x00,0x00,0x00}}, /* SourcePackageID */
147     { 0x1102, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x02,0x00,0x00,0x00}}, /* SourceTrackID */
148     // File Descriptor
149     { 0x3F01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x04,0x06,0x0B,0x00,0x00}}, /* Sub Descriptors reference array */
150     { 0x3006, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x06,0x01,0x01,0x03,0x05,0x00,0x00,0x00}}, /* Linked Track ID */
151     { 0x3001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x00,0x00,0x00,0x00}}, /* SampleRate */
152     { 0x3004, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x01,0x02,0x00,0x00}}, /* Essence Container */
153     // Generic Picture Essence Descriptor
154     { 0x3203, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x02,0x00,0x00,0x00}}, /* Stored Width */
155     { 0x3202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x01,0x00,0x00,0x00}}, /* Stored Height */
156     { 0x320E, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x01,0x01,0x01,0x00,0x00,0x00}}, /* Aspect Ratio */
157     { 0x3201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x06,0x01,0x00,0x00,0x00,0x00}}, /* Picture Essence Coding */
158     // Generic Sound Essence Descriptor
159     { 0x3D03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x01,0x01,0x01,0x00,0x00}}, /* Audio sampling rate */
160     { 0x3D07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x01,0x01,0x04,0x00,0x00,0x00}}, /* ChannelCount */
161     { 0x3D01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x03,0x04,0x00,0x00,0x00}}, /* Quantization bits */
162     { 0x3D06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x06,0x01,0x00,0x00,0x00,0x00}}, /* Sound Essence Compression */
163 };
164
165 static void mxf_write_uuid(ByteIOContext *pb, enum CodecID type, int value)
166 {
167     put_buffer(pb, uuid_base, 12);
168     put_be16(pb, type);
169     put_be16(pb, value);
170 }
171
172 static void mxf_write_umid(ByteIOContext *pb, enum CodecID type, int value)
173 {
174     put_buffer(pb, umid_base, 16);
175     mxf_write_uuid(pb, type, value);
176 }
177
178 static void mxf_write_refs_count(ByteIOContext *pb, int ref_count)
179 {
180     put_be32(pb, ref_count);
181     put_be32(pb, 16);
182 }
183
184 static int klv_encode_ber_length(ByteIOContext *pb, uint64_t len)
185 {
186     // Determine the best BER size
187     int size;
188     if (len < 128) {
189         //short form
190         put_byte(pb, len);
191         return 1;
192     }
193
194     size = (av_log2(len) >> 3) + 1;
195
196     // long form
197     put_byte(pb, 0x80 + size);
198     while(size) {
199         size --;
200         put_byte(pb, len >> 8 * size & 0xff);
201     }
202     return 0;
203 }
204
205 /*
206  * Get essence container ul and return its index position
207  */
208 static const UID *mxf_get_essence_container_ul(enum CodecID type, int *index)
209 {
210     for (*index = 0; *index < sizeof(mxf_essence_container_uls)/
211                               sizeof(*mxf_essence_container_uls); (*index)++)
212         if (mxf_essence_container_uls[*index].id == type)
213             return &mxf_essence_container_uls[*index].container_ul;
214     *index = -1;
215     return NULL;
216 }
217
218 static void mxf_write_primer_pack(AVFormatContext *s)
219 {
220     ByteIOContext *pb = s->pb;
221     int local_tag_number, i = 0;
222
223     local_tag_number = sizeof(mxf_local_tag_batch)/sizeof(*mxf_local_tag_batch);
224
225     put_buffer(pb, primer_pack_key, 16);
226     klv_encode_ber_length(pb, local_tag_number * 18 + 8);
227
228     put_be32(pb, local_tag_number); // local_tag num
229     put_be32(pb, 18); // item size, always 18 according to the specs
230
231     for (i = 0; i < local_tag_number; i++) {
232         put_be16(pb, mxf_local_tag_batch[i].local_tag);
233         put_buffer(pb, mxf_local_tag_batch[i].uid, 16);
234     }
235 }
236
237 static void mxf_write_local_tag(ByteIOContext *pb, int size, int tag)
238 {
239     put_be16(pb, tag);
240     put_be16(pb, size);
241 }
242
243 static void mxf_write_metadata_key(ByteIOContext *pb, unsigned int value)
244 {
245     put_buffer(pb, header_metadata_key, 13);
246     put_be24(pb, value);
247 }
248
249 static void mxf_free(AVFormatContext *s)
250 {
251     int i;
252
253     for (i = 0; i < s->nb_streams; i++) {
254         AVStream *st = s->streams[i];
255         av_freep(&st->priv_data);
256     }
257 }
258
259 static const MXFDataDefinitionUL *mxf_get_data_definition_ul(enum CodecType type)
260 {
261     const MXFDataDefinitionUL *uls = ff_mxf_data_definition_uls;
262     while (uls->type != CODEC_TYPE_DATA) {
263         if (type == uls->type)
264             break;
265         uls++;
266     }
267     return uls;
268 }
269
270 static void mxf_write_essence_container_refs(AVFormatContext *s)
271 {
272     MXFContext *c = s->priv_data;
273     ByteIOContext *pb = s->pb;
274     int i;
275
276     mxf_write_refs_count(pb, c->essence_container_count);
277     av_log(s,AV_LOG_DEBUG, "essence container count:%d\n", c->essence_container_count);
278     for (i = 0; i < c->essence_container_count; i++) {
279         put_buffer(pb, mxf_essence_container_uls[c->essence_containers_indices[i]].container_ul, 16);
280         PRINT_KEY(s, "essence container ul:\n", mxf_essence_container_uls[c->essence_containers_indices[i]].container_ul);
281     }
282 }
283
284 static void mxf_write_preface(AVFormatContext *s)
285 {
286     MXFContext *mxf = s->priv_data;
287     ByteIOContext *pb = s->pb;
288
289     mxf_write_metadata_key(pb, 0x012f00);
290     PRINT_KEY(s, "preface key", pb->buf_ptr - 16);
291     klv_encode_ber_length(pb, 130 + 16 * mxf->essence_container_count);
292
293     // write preface set uid
294     mxf_write_local_tag(pb, 16, 0x3C0A);
295     mxf_write_uuid(pb, Preface, 0);
296     PRINT_KEY(s, "preface uid", pb->buf_ptr - 16);
297
298     // write create date as unknown
299     mxf_write_local_tag(pb, 8, 0x3B02);
300     put_be64(pb, 0);
301
302     // write version
303     mxf_write_local_tag(pb, 2, 0x3B05);
304     put_be16(pb, 1);
305
306     // write identification_refs
307     mxf_write_local_tag(pb, 16 + 8, 0x3B06);
308     mxf_write_refs_count(pb, 1);
309     mxf_write_uuid(pb, Identification, 0);
310
311     // write content_storage_refs
312     mxf_write_local_tag(pb, 16, 0x3B03);
313     mxf_write_uuid(pb, ContentStorage, 0);
314
315     mxf_write_local_tag(pb, 16, 0x3B09);
316     put_buffer(pb, op1a_ul, 16);
317
318     // write essence_container_refs
319     mxf_write_local_tag(pb, 8 + 16 * mxf->essence_container_count, 0x3B0A);
320     mxf_write_essence_container_refs(s);
321
322     // write dm_scheme_refs
323     mxf_write_local_tag(pb, 8, 0x3B0B);
324     put_be64(pb, 0);
325 }
326
327 /*
328  * Write a local tag containing an ascii string as utf-16
329  */
330 static void mxf_write_local_tag_utf16(ByteIOContext *pb, int tag, const char *value)
331 {
332     int i, size = strlen(value);
333     mxf_write_local_tag(pb, size*2, tag);
334     for (i = 0; i < size; i++)
335         put_be16(pb, value[i]);
336 }
337
338 static void mxf_write_identification(AVFormatContext *s)
339 {
340     ByteIOContext *pb = s->pb;
341     const char *company = "FFmpeg";
342     const char *product = "OP1a Muxer";
343     const char *version;
344     int length;
345
346     mxf_write_metadata_key(pb, 0x013000);
347     PRINT_KEY(s, "identification key", pb->buf_ptr - 16);
348
349     version = s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT ?
350         "0.0.0" : AV_STRINGIFY(LIBAVFORMAT_VERSION);
351     length = 84 + (strlen(company)+strlen(product)+strlen(version))*2; // utf-16
352     klv_encode_ber_length(pb, length);
353
354     // write uid
355     mxf_write_local_tag(pb, 16, 0x3C0A);
356     mxf_write_uuid(pb, Identification, 0);
357     PRINT_KEY(s, "identification uid", pb->buf_ptr - 16);
358
359     // write generation uid
360     mxf_write_local_tag(pb, 16, 0x3C09);
361     mxf_write_uuid(pb, Identification, 1);
362
363     mxf_write_local_tag_utf16(pb, 0x3C01, company); // Company Name
364     mxf_write_local_tag_utf16(pb, 0x3C02, product); // Product Name
365     mxf_write_local_tag_utf16(pb, 0x3C04, version); // Version String
366
367     // write product uid
368     mxf_write_local_tag(pb, 16, 0x3C05);
369     mxf_write_uuid(pb, Identification, 2);
370
371     // write modified date
372     mxf_write_local_tag(pb, 8, 0x3C06);
373     put_be64(pb, 0);
374 }
375
376 static void mxf_write_content_storage(AVFormatContext *s)
377 {
378     ByteIOContext *pb = s->pb;
379
380     mxf_write_metadata_key(pb, 0x011800);
381     PRINT_KEY(s, "content storage key", pb->buf_ptr - 16);
382     klv_encode_ber_length(pb, 64);
383
384     // write uid
385     mxf_write_local_tag(pb, 16, 0x3C0A);
386     mxf_write_uuid(pb, ContentStorage, 0);
387     PRINT_KEY(s, "content storage uid", pb->buf_ptr - 16);
388
389     // write package reference
390     mxf_write_local_tag(pb, 16 * 2 + 8, 0x1901);
391     mxf_write_refs_count(pb, 2);
392     mxf_write_uuid(pb, MaterialPackage, 0);
393     mxf_write_uuid(pb, SourcePackage, 0);
394 }
395
396 static void mxf_write_package(AVFormatContext *s, enum MXFMetadataSetType type)
397 {
398     ByteIOContext *pb = s->pb;
399     int i;
400
401     if (type == MaterialPackage) {
402         mxf_write_metadata_key(pb, 0x013600);
403         PRINT_KEY(s, "Material Package key", pb->buf_ptr - 16);
404         klv_encode_ber_length(pb, 92 + 16 * s->nb_streams);
405     } else {
406         mxf_write_metadata_key(pb, 0x013700);
407         PRINT_KEY(s, "Source Package key", pb->buf_ptr - 16);
408         klv_encode_ber_length(pb, 112 + 16 * s->nb_streams); // 20 bytes length for descriptor reference
409     }
410
411     // write uid
412     mxf_write_local_tag(pb, 16, 0x3C0A);
413     mxf_write_uuid(pb, type, 0);
414     av_log(s,AV_LOG_DEBUG, "package type:%d\n", type);
415     PRINT_KEY(s, "package uid", pb->buf_ptr - 16);
416
417     // write package umid
418     mxf_write_local_tag(pb, 32, 0x4401);
419     mxf_write_umid(pb, type, 0);
420     PRINT_KEY(s, "package umid second part", pb->buf_ptr - 16);
421
422     // write create date
423     mxf_write_local_tag(pb, 8, 0x4405);
424     put_be64(pb, 0);
425
426     // write modified date
427     mxf_write_local_tag(pb, 8, 0x4404);
428     put_be64(pb, 0);
429
430     // write track refs
431     mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x4403);
432     mxf_write_refs_count(pb, s->nb_streams);
433     for (i = 0; i < s->nb_streams; i++)
434         mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, i);
435
436     // write multiple descriptor reference
437     if (type == SourcePackage) {
438         mxf_write_local_tag(pb, 16, 0x4701);
439         mxf_write_uuid(pb, MultipleDescriptor, 0);
440     }
441 }
442
443 static void mxf_write_track(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
444 {
445     ByteIOContext *pb = s->pb;
446     MXFStreamContext *sc = st->priv_data;
447
448     mxf_write_metadata_key(pb, 0x013b00);
449     PRINT_KEY(s, "track key", pb->buf_ptr - 16);
450     klv_encode_ber_length(pb, 80);
451
452     // write track uid
453     mxf_write_local_tag(pb, 16, 0x3C0A);
454     mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, st->index);
455     PRINT_KEY(s, "track uid", pb->buf_ptr - 16);
456
457     // write track id
458     mxf_write_local_tag(pb, 4, 0x4801);
459     put_be32(pb, st->index);
460
461     // write track number
462     mxf_write_local_tag(pb, 4, 0x4804);
463     if (type == MaterialPackage)
464         put_be32(pb, 0); // track number of material package is 0
465     else
466         put_buffer(pb, sc->track_essence_element_key + 12, 4);
467
468     mxf_write_local_tag(pb, 8, 0x4B01);
469     put_be32(pb, st->time_base.den);
470     put_be32(pb, st->time_base.num);
471
472     // write origin
473     mxf_write_local_tag(pb, 8, 0x4B02);
474     put_be64(pb, 0);
475
476     // write sequence refs
477     mxf_write_local_tag(pb, 16, 0x4803);
478     mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
479 }
480
481 static void mxf_write_common_fields(ByteIOContext *pb, AVStream *st)
482 {
483     const MXFDataDefinitionUL *data_def_ul = mxf_get_data_definition_ul(st->codec->codec_type);
484     MXFStreamContext *sc = st->priv_data;
485
486     // find data define uls
487     mxf_write_local_tag(pb, 16, 0x0201);
488     put_buffer(pb, data_def_ul->uid, 16);
489
490     // write duration
491     mxf_write_local_tag(pb, 8, 0x0202);
492     put_be64(pb, sc->duration);
493 }
494
495 static void mxf_write_sequence(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
496 {
497     ByteIOContext *pb = s->pb;
498
499     mxf_write_metadata_key(pb, 0x010f00);
500     PRINT_KEY(s, "sequence key", pb->buf_ptr - 16);
501     klv_encode_ber_length(pb, 80);
502
503     mxf_write_local_tag(pb, 16, 0x3C0A);
504     mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
505
506     PRINT_KEY(s, "sequence uid", pb->buf_ptr - 16);
507     mxf_write_common_fields(pb, st);
508
509     // write structural component
510     mxf_write_local_tag(pb, 16 + 8, 0x1001);
511     mxf_write_refs_count(pb, 1);
512     mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
513 }
514
515 static void mxf_write_structural_component(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
516 {
517     ByteIOContext *pb = s->pb;
518     int i;
519
520     mxf_write_metadata_key(pb, 0x011100);
521     PRINT_KEY(s, "sturctural component key", pb->buf_ptr - 16);
522     klv_encode_ber_length(pb, 108);
523
524     // write uid
525     mxf_write_local_tag(pb, 16, 0x3C0A);
526     mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
527
528     PRINT_KEY(s, "structural component uid", pb->buf_ptr - 16);
529     mxf_write_common_fields(pb, st);
530
531     // write start_position
532     mxf_write_local_tag(pb, 8, 0x1201);
533     put_be64(pb, 0);
534
535     // write source package uid, end of the reference
536     mxf_write_local_tag(pb, 32, 0x1101);
537     if (type == SourcePackage) {
538         for (i = 0; i < 4; i++)
539             put_be64(pb, 0);
540     } else
541         mxf_write_umid(pb, SourcePackage, 0);
542
543     // write source track id
544     mxf_write_local_tag(pb, 4, 0x1102);
545     if (type == SourcePackage)
546         put_be32(pb, 0);
547     else
548         put_be32(pb, st->index);
549 }
550
551 static void mxf_write_multi_descriptor(AVFormatContext *s)
552 {
553     ByteIOContext *pb = s->pb;
554     int i;
555
556     mxf_write_metadata_key(pb, 0x014400);
557     PRINT_KEY(s, "multiple descriptor key", pb->buf_ptr - 16);
558     klv_encode_ber_length(pb, 64 + 16 * s->nb_streams);
559
560     mxf_write_local_tag(pb, 16, 0x3C0A);
561     mxf_write_uuid(pb, MultipleDescriptor, 0);
562     PRINT_KEY(s, "multi_desc uid", pb->buf_ptr - 16);
563
564     // write sample rate
565     mxf_write_local_tag(pb, 8, 0x3001);
566     put_be32(pb, s->streams[0]->time_base.den);
567     put_be32(pb, s->streams[0]->time_base.num);
568
569     // write essence container ul
570     mxf_write_local_tag(pb, 16, 0x3004);
571     put_buffer(pb, multiple_desc_ul, 16);
572
573     // write sub descriptor refs
574     mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x3F01);
575     mxf_write_refs_count(pb, s->nb_streams);
576     for (i = 0; i < s->nb_streams; i++)
577         mxf_write_uuid(pb, SubDescriptor, i);
578 }
579
580 static void mxf_write_generic_desc(ByteIOContext *pb, const MXFDescriptorWriteTableEntry *desc_tbl, AVStream *st)
581 {
582     MXFStreamContext *sc = st->priv_data;
583
584     put_buffer(pb, desc_tbl->key, 16);
585     klv_encode_ber_length(pb, 108);
586
587     mxf_write_local_tag(pb, 16, 0x3C0A);
588     mxf_write_uuid(pb, SubDescriptor, st->index);
589
590     mxf_write_local_tag(pb, 4, 0x3006);
591     put_be32(pb, st->index);
592
593     mxf_write_local_tag(pb, 8, 0x3001);
594     put_be32(pb, st->time_base.den);
595     put_be32(pb, st->time_base.num);
596
597     mxf_write_local_tag(pb, 16, 0x3004);
598     put_buffer(pb, *sc->essence_container_ul, 16);
599
600     mxf_write_local_tag(pb, 16, 0x3201);
601     put_buffer(pb, *sc->codec_ul, 16);
602 }
603
604 static void mxf_write_mpegvideo_desc(AVFormatContext *s, const MXFDescriptorWriteTableEntry *desc_tbl, AVStream *st)
605 {
606     ByteIOContext *pb = s->pb;
607
608     mxf_write_generic_desc(pb, desc_tbl, st);
609
610     mxf_write_local_tag(pb, 4, 0x3203);
611     put_be32(pb, st->codec->width);
612
613     mxf_write_local_tag(pb, 4, 0x3202);
614     put_be32(pb, st->codec->height);
615
616     mxf_write_local_tag(pb, 8, 0x320E);
617     put_be32(pb, st->codec->height * st->sample_aspect_ratio.den);
618     put_be32(pb, st->codec->width  * st->sample_aspect_ratio.num);
619 }
620
621 static void mxf_write_wav_desc(AVFormatContext *s, const MXFDescriptorWriteTableEntry *desc_tbl, AVStream *st)
622 {
623     ByteIOContext *pb = s->pb;
624
625     mxf_write_generic_desc(pb, desc_tbl, st);
626
627     // write audio sampling rate
628     mxf_write_local_tag(pb, 8, 0x3D03);
629     put_be32(pb, st->codec->sample_rate);
630     put_be32(pb, 1);
631
632     mxf_write_local_tag(pb, 4, 0x3D07);
633     put_be32(pb, st->codec->channels);
634
635     mxf_write_local_tag(pb, 4, 0x3D01);
636     put_be32(pb, st->codec->bits_per_sample);
637 }
638
639 static const MXFDescriptorWriteTableEntry mxf_descriptor_write_table[] = {
640     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_write_mpegvideo_desc, CODEC_ID_MPEG2VIDEO},
641     { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_write_wav_desc, CODEC_ID_PCM_S16LE},
642     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, CODEC_ID_NONE},
643 };
644
645 static void mxf_build_structural_metadata(AVFormatContext *s, enum MXFMetadataSetType type)
646 {
647     int i;
648     const MXFDescriptorWriteTableEntry *desc = NULL;
649
650     mxf_write_package(s, type);
651     if (type == SourcePackage)
652         mxf_write_multi_descriptor(s);
653
654     for (i = 0; i < s->nb_streams; i++) {
655         AVStream *st = s->streams[i];
656         mxf_write_track(s, st, type);
657         mxf_write_sequence(s, st, type);
658         mxf_write_structural_component(s, st, type);
659
660         if (type == SourcePackage) {
661             for (desc = mxf_descriptor_write_table; desc->write; desc++) {
662                 if (s->streams[i]->codec->codec_id == desc->type) {
663                     desc->write(s, desc, st);
664                     break;
665                 }
666             }
667         }
668     }
669 }
670
671 static int mxf_write_header_metadata_sets(AVFormatContext *s)
672 {
673     mxf_write_preface(s);
674     mxf_write_identification(s);
675     mxf_write_content_storage(s);
676     mxf_build_structural_metadata(s, MaterialPackage);
677     mxf_build_structural_metadata(s, SourcePackage);
678     return 0;
679 }
680
681 static void mxf_write_partition(AVFormatContext *s, int64_t byte_position, int bodysid, const uint8_t *key)
682 {
683     MXFContext *mxf = s->priv_data;
684     ByteIOContext *pb = s->pb;
685
686     // write klv
687     put_buffer(pb, key, 16);
688
689     klv_encode_ber_length(pb, 88 + 16 * mxf->essence_container_count);
690
691     // write partition value
692     put_be16(pb, 1); // majorVersion
693     put_be16(pb, 2); // minorVersion
694     put_be32(pb, 1); // kagSize
695
696     put_be64(pb, byte_position); // thisPartition
697     put_be64(pb, 0); // previousPartition
698
699     // set offset
700     if (!byte_position)
701         mxf->header_footer_partition_offset = url_ftell(pb);
702     put_be64(pb, byte_position); // footerPartition,update later
703
704     // set offset
705     if (!byte_position)
706         mxf->header_byte_count_offset = url_ftell(pb);
707     put_be64(pb, 0); // headerByteCount, update later
708
709     // no indexTable
710     put_be64(pb, 0); // indexByteCount
711     put_be32(pb, 0); // indexSID
712     put_be64(pb, 0); // bodyOffset
713
714     put_be32(pb, bodysid); // bodySID
715     put_buffer(pb, op1a_ul, 16); // operational pattern
716
717     // essence container
718     mxf_write_essence_container_refs(s);
719 }
720
721 static const UID mxf_mpeg2_codec_uls[] = {
722     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x10,0x00 }, // MP-ML I-Frame
723     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, // MP-ML Long GOP
724     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, // 422P-ML I-Frame
725     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, // 422P-ML Long GOP
726     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x02,0x00 }, // MP-HL I-Frame
727     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, // MP-HL Long GOP
728     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, // 422P-HL I-Frame
729     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, // 422P-HL Long GOP
730 };
731
732 static const UID *mxf_get_mpeg2_codec_ul(AVCodecContext *avctx)
733 {
734     if (avctx->profile == 4) { // Main
735         if (avctx->level == 8) // Main
736             return avctx->gop_size ?
737                 &mxf_mpeg2_codec_uls[1] :
738                 &mxf_mpeg2_codec_uls[0];
739         else if (avctx->level == 4) // High
740             return avctx->gop_size ?
741                 &mxf_mpeg2_codec_uls[5] :
742                 &mxf_mpeg2_codec_uls[4];
743     } else if (avctx->profile == 0) { // 422
744         if (avctx->level == 5) // Main
745             return avctx->gop_size ?
746                 &mxf_mpeg2_codec_uls[3] :
747                 &mxf_mpeg2_codec_uls[2];
748         else if (avctx->level == 2) // High
749             return avctx->gop_size ?
750                 &mxf_mpeg2_codec_uls[7] :
751                 &mxf_mpeg2_codec_uls[6];
752     }
753     return NULL;
754 }
755
756 static int mxf_write_header(AVFormatContext *s)
757 {
758     MXFContext *mxf = s->priv_data;
759     ByteIOContext *pb = s->pb;
760     int64_t header_metadata_start, offset_now;
761     int i, index;
762     uint8_t present[sizeof(mxf_essence_container_uls)/
763                     sizeof(*mxf_essence_container_uls)] = {0};
764
765     for (i = 0; i < s->nb_streams; i++) {
766         AVStream *st = s->streams[i];
767         MXFStreamContext *sc = av_mallocz(sizeof(*sc));
768         if (!sc)
769             return AVERROR(ENOMEM);
770         st->priv_data = sc;
771         // set pts information
772         if (st->codec->codec_type == CODEC_TYPE_VIDEO)
773             av_set_pts_info(st, 64, 1, st->codec->time_base.den);
774         else if (st->codec->codec_type == CODEC_TYPE_AUDIO)
775             av_set_pts_info(st, 64, 1, st->codec->sample_rate);
776         sc->duration = -1;
777
778         sc->essence_container_ul = mxf_get_essence_container_ul(st->codec->codec_id, &index);
779         if (!sc->essence_container_ul) {
780             av_log(s, AV_LOG_ERROR, "track %d: could not find essence container ul, "
781                    "codec not currently supported in container\n", i);
782             return -1;
783         }
784
785         if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO) {
786             if (st->codec->profile == FF_PROFILE_UNKNOWN ||
787                 st->codec->level == FF_LEVEL_UNKNOWN) {
788                 av_log(s, AV_LOG_ERROR, "track %d: profile and level must be set for mpeg-2\n", i);
789                 return -1;
790             }
791             sc->codec_ul = mxf_get_mpeg2_codec_ul(st->codec);
792             if (!sc->codec_ul) {
793                 av_log(s, AV_LOG_ERROR, "track %d: could not find codec ul for mpeg-2, "
794                        "unsupported profile/level\n", i);
795                 return -1;
796             }
797         } else
798             sc->codec_ul = &mxf_essence_container_uls[index].codec_ul;
799
800         if (!present[index]) {
801             mxf->essence_containers_indices[mxf->essence_container_count++] = index;
802             present[index] = 1;
803         } else
804             present[index]++;
805         memcpy(sc->track_essence_element_key, mxf_essence_container_uls[index].element_ul, 15);
806         sc->track_essence_element_key[15] = present[index];
807         PRINT_KEY(s, "track essence element key", sc->track_essence_element_key);
808     }
809
810     mxf_write_partition(s, 0, 1, header_open_partition_key);
811
812     // mark the start of the headermetadata and calculate metadata size
813     header_metadata_start = url_ftell(s->pb);
814     mxf_write_primer_pack(s);
815     if (mxf_write_header_metadata_sets(s) < 0)
816         goto fail;
817     offset_now = url_ftell(s->pb);
818     mxf->header_byte_count = offset_now - header_metadata_start;
819     // update header_byte_count
820     url_fseek(pb, mxf->header_byte_count_offset, SEEK_SET);
821     put_be64(pb, mxf->header_byte_count);
822     url_fseek(pb, offset_now, SEEK_SET);
823
824     put_flush_packet(pb);
825     return 0;
826 fail:
827     mxf_free(s);
828     return -1;
829 }
830
831 static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
832 {
833     ByteIOContext *pb = s->pb;
834     AVStream *st = s->streams[pkt->stream_index];
835     MXFStreamContext *sc = st->priv_data;
836
837     put_buffer(pb, sc->track_essence_element_key, 16); // write key
838     klv_encode_ber_length(pb, pkt->size); // write length
839     put_buffer(pb, pkt->data, pkt->size); // write value
840
841     sc->duration = FFMAX(pkt->pts + pkt->duration, sc->duration);
842
843     put_flush_packet(pb);
844     return 0;
845 }
846
847 static void mxf_update_header_partition(AVFormatContext *s, int64_t footer_partition_offset)
848 {
849     MXFContext *mxf = s->priv_data;
850     ByteIOContext *pb = s->pb;
851
852     url_fseek(pb, mxf->header_footer_partition_offset, SEEK_SET);
853     put_be64(pb, footer_partition_offset);
854     put_flush_packet(pb);
855 }
856
857
858 static int mxf_write_footer(AVFormatContext *s)
859 {
860     ByteIOContext *pb = s->pb;
861     int64_t byte_position= url_ftell(pb);
862
863     mxf_write_partition(s, byte_position, 0, footer_partition_key);
864     put_flush_packet(pb);
865     if (!url_is_streamed(s->pb))
866         mxf_update_header_partition(s, byte_position);
867     mxf_free(s);
868     return 0;
869 }
870
871 AVOutputFormat mxf_muxer = {
872     "mxf",
873     NULL_IF_CONFIG_SMALL("Material eXchange Format"),
874     NULL,
875     "mxf",
876     sizeof(MXFContext),
877     CODEC_ID_PCM_S16LE,
878     CODEC_ID_MPEG2VIDEO,
879     mxf_write_header,
880     mxf_write_packet,
881     mxf_write_footer,
882 };
883
884