mxfenc: write optional field dominance flag in picture description
[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 <math.h>
36 #include <time.h>
37
38 #include "libavutil/opt.h"
39 #include "libavutil/random_seed.h"
40 #include "libavutil/timecode.h"
41 #include "libavcodec/bytestream.h"
42 #include "audiointerleave.h"
43 #include "avformat.h"
44 #include "internal.h"
45 #include "mxf.h"
46
47 static const int NTSC_samples_per_frame[]    = { 1602, 1601, 1602, 1601, 1602, 0 };
48 static const int NTSC_60_samples_per_frame[] = { 801, 801, 801, 801, 800, 0 };
49 static const int PAL_samples_per_frame[]     = { 1920, 0 };
50 static const int PAL_50_samples_per_frame[]  = { 960, 0 };
51
52 extern AVOutputFormat ff_mxf_d10_muxer;
53
54 #define EDIT_UNITS_PER_BODY 250
55 #define KAG_SIZE 512
56
57 typedef struct {
58     int local_tag;
59     UID uid;
60 } MXFLocalTagPair;
61
62 typedef struct {
63     uint8_t flags;
64     uint64_t offset;
65     unsigned slice_offset; ///< offset of audio slice
66     uint16_t temporal_ref;
67 } MXFIndexEntry;
68
69 typedef struct {
70     AudioInterleaveContext aic;
71     UID track_essence_element_key;
72     int index;               ///< index in mxf_essence_container_uls table
73     const UID *codec_ul;
74     int order;               ///< interleaving order if dts are equal
75     int interlaced;          ///< whether picture is interlaced
76     int field_dominance;     ///< tff=1, bff=2
77     int temporal_reordering;
78     AVRational aspect_ratio; ///< display aspect ratio
79     int closed_gop;          ///< gop is closed, used in mpeg-2 frame parsing
80 } MXFStreamContext;
81
82 typedef struct {
83     UID container_ul;
84     UID element_ul;
85     UID codec_ul;
86     void (*write_desc)(AVFormatContext *, AVStream *);
87 } MXFContainerEssenceEntry;
88
89 static const struct {
90     enum CodecID id;
91     int index;
92 } mxf_essence_mappings[] = {
93     { CODEC_ID_MPEG2VIDEO, 0 },
94     { CODEC_ID_PCM_S24LE,  1 },
95     { CODEC_ID_PCM_S16LE,  1 },
96     { CODEC_ID_NONE }
97 };
98
99 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st);
100 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st);
101 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st);
102 static void mxf_write_cdci_desc(AVFormatContext *s, AVStream *st);
103 static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st);
104
105 static const MXFContainerEssenceEntry mxf_essence_container_uls[] = {
106     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 },
107       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
108       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
109       mxf_write_mpegvideo_desc },
110     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x03,0x00 },
111       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x03,0x00 },
112       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
113       mxf_write_aes3_desc },
114     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 },
115       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x01,0x00 },
116       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
117       mxf_write_wav_desc },
118     // D-10 625/50 PAL 50mb/s
119     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 },
120       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
121       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x01 },
122       mxf_write_cdci_desc },
123     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 },
124       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
125       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
126       mxf_write_generic_sound_desc },
127     // D-10 525/60 NTSC 50mb/s
128     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x02,0x01 },
129       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
130       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x02 },
131       mxf_write_cdci_desc },
132     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x02,0x01 },
133       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
134       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
135       mxf_write_generic_sound_desc },
136     // D-10 625/50 PAL 40mb/s
137     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x03,0x01 },
138       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
139       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x03 },
140       mxf_write_cdci_desc },
141     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x03,0x01 },
142       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
143       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
144       mxf_write_generic_sound_desc },
145     // D-10 525/60 NTSC 40mb/s
146     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x04,0x01 },
147       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
148       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x04 },
149       mxf_write_cdci_desc },
150     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x04,0x01 },
151       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
152       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
153       mxf_write_generic_sound_desc },
154     // D-10 625/50 PAL 30mb/s
155     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x05,0x01 },
156       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
157       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x05 },
158       mxf_write_cdci_desc },
159     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x05,0x01 },
160       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
161       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
162       mxf_write_generic_sound_desc },
163     // D-10 525/60 NTSC 30mb/s
164     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x06,0x01 },
165       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
166       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x06 },
167       mxf_write_cdci_desc },
168     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x06,0x01 },
169       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
170       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
171       mxf_write_generic_sound_desc },
172     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
173       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
174       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
175       NULL },
176 };
177
178 typedef struct MXFContext {
179     AVClass *av_class;
180     int64_t footer_partition_offset;
181     int essence_container_count;
182     AVRational time_base;
183     int header_written;
184     MXFIndexEntry *index_entries;
185     unsigned edit_units_count;
186     uint64_t timestamp;   ///< timestamp, as year(16),month(8),day(8),hour(8),minutes(8),msec/4(8)
187     uint8_t slice_count;  ///< index slice count minus 1 (1 if no audio, 0 otherwise)
188     int last_indexed_edit_unit;
189     uint64_t *body_partition_offset;
190     unsigned body_partitions_count;
191     int last_key_index;  ///< index of last key frame
192     uint64_t duration;
193     AVTimecode tc;       ///< timecode context
194     AVStream *timecode_track;
195     int timecode_base;       ///< rounded time code base (25 or 30)
196     int edit_unit_byte_count; ///< fixed edit unit byte count
197     uint64_t body_offset;
198     uint32_t instance_number;
199     uint8_t umid[16];        ///< unique material identifier
200 } MXFContext;
201
202 static const uint8_t uuid_base[]            = { 0xAD,0xAB,0x44,0x24,0x2f,0x25,0x4d,0xc7,0x92,0xff,0x29,0xbd };
203 static const uint8_t umid_ul[]              = { 0x06,0x0A,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x01,0x0D,0x00,0x13 };
204
205 /**
206  * complete key for operation pattern, partitions, and primer pack
207  */
208 static const uint8_t op1a_ul[]                     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x01,0x09,0x00 };
209 static const uint8_t footer_partition_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }; // ClosedComplete
210 static const uint8_t primer_pack_key[]             = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x05,0x01,0x00 };
211 static const uint8_t index_table_segment_key[]     = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 };
212 static const uint8_t random_index_pack_key[]       = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x11,0x01,0x00 };
213 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
214 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
215 static const uint8_t klv_fill_key[]                = { 0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x03,0x01,0x02,0x10,0x01,0x00,0x00,0x00 };
216 static const uint8_t body_partition_key[]          = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }; // ClosedComplete
217
218 /**
219  * partial key for header metadata
220  */
221 static const uint8_t header_metadata_key[]  = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01 };
222 static const uint8_t multiple_desc_ul[]     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x0D,0x01,0x03,0x01,0x02,0x7F,0x01,0x00 };
223
224 /**
225  * SMPTE RP210 http://www.smpte-ra.org/mdd/index.html
226  */
227 static const MXFLocalTagPair mxf_local_tag_batch[] = {
228     // preface set
229     { 0x3C0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x02,0x00,0x00,0x00,0x00}}, /* Instance UID */
230     { 0x3B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x04,0x00,0x00}}, /* Last Modified Date */
231     { 0x3B05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x01,0x05,0x00,0x00,0x00}}, /* Version */
232     { 0x3B06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x04,0x00,0x00}}, /* Identifications reference */
233     { 0x3B03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x01,0x00,0x00}}, /* Content Storage reference */
234     { 0x3B09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x03,0x00,0x00,0x00,0x00}}, /* Operational Pattern UL */
235     { 0x3B0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x01,0x00,0x00}}, /* Essence Containers UL batch */
236     { 0x3B0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x02,0x00,0x00}}, /* DM Schemes UL batch */
237     // Identification
238     { 0x3C09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x01,0x00,0x00,0x00}}, /* This Generation UID */
239     { 0x3C01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x02,0x01,0x00,0x00}}, /* Company Name */
240     { 0x3C02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x03,0x01,0x00,0x00}}, /* Product Name */
241     { 0x3C04, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x05,0x01,0x00,0x00}}, /* Version String */
242     { 0x3C05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x07,0x00,0x00,0x00}}, /* Product ID */
243     { 0x3C06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x03,0x00,0x00}}, /* Modification Date */
244     // Content Storage
245     { 0x1901, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x01,0x00,0x00}}, /* Package strong reference batch */
246     { 0x1902, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x02,0x00,0x00}}, /* Package strong reference batch */
247     // Essence Container Data
248     { 0x2701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x06,0x01,0x00,0x00,0x00}}, /* Linked Package UID */
249     { 0x3F07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x04,0x00,0x00,0x00,0x00}}, /* BodySID */
250     // Package
251     { 0x4401, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x10,0x00,0x00,0x00,0x00}}, /* Package UID */
252     { 0x4405, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x01,0x03,0x00,0x00}}, /* Package Creation Date */
253     { 0x4404, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x05,0x00,0x00}}, /* Package Modified Date */
254     { 0x4403, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x05,0x00,0x00}}, /* Tracks Strong reference array */
255     { 0x4701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x03,0x00,0x00}}, /* Descriptor */
256     // Track
257     { 0x4801, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x07,0x01,0x01,0x00,0x00,0x00,0x00}}, /* Track ID */
258     { 0x4804, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x04,0x01,0x03,0x00,0x00,0x00,0x00}}, /* Track Number */
259     { 0x4B01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x30,0x04,0x05,0x00,0x00,0x00,0x00}}, /* Edit Rate */
260     { 0x4B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x03,0x00,0x00}}, /* Origin */
261     { 0x4803, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x04,0x00,0x00}}, /* Sequence reference */
262     // Sequence
263     { 0x0201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x07,0x01,0x00,0x00,0x00,0x00,0x00}}, /* Data Definition UL */
264     { 0x0202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x02,0x01,0x01,0x03,0x00,0x00}}, /* Duration */
265     { 0x1001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x09,0x00,0x00}}, /* Structural Components reference array */
266     // Source Clip
267     { 0x1201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x04,0x00,0x00}}, /* Start position */
268     { 0x1101, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x01,0x00,0x00,0x00}}, /* SourcePackageID */
269     { 0x1102, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x02,0x00,0x00,0x00}}, /* SourceTrackID */
270     // Timecode Component
271     { 0x1501, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x05,0x00,0x00}}, /* Start Time Code */
272     { 0x1502, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x04,0x01,0x01,0x02,0x06,0x00,0x00}}, /* Rounded Time Code Base */
273     { 0x1503, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x04,0x01,0x01,0x05,0x00,0x00,0x00}}, /* Drop Frame */
274     // File Descriptor
275     { 0x3F01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x04,0x06,0x0B,0x00,0x00}}, /* Sub Descriptors reference array */
276     { 0x3006, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x06,0x01,0x01,0x03,0x05,0x00,0x00,0x00}}, /* Linked Track ID */
277     { 0x3001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x00,0x00,0x00,0x00}}, /* SampleRate */
278     { 0x3004, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x01,0x02,0x00,0x00}}, /* Essence Container */
279     // Generic Picture Essence Descriptor
280     { 0x320C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Frame Layout */
281     { 0x320D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x03,0x02,0x05,0x00,0x00,0x00}}, /* Video Line Map */
282     { 0x3203, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x02,0x00,0x00,0x00}}, /* Stored Width */
283     { 0x3202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x01,0x00,0x00,0x00}}, /* Stored Height */
284     { 0x3209, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0C,0x00,0x00,0x00}}, /* Display Width */
285     { 0x3208, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0B,0x00,0x00,0x00}}, /* Display Height */
286     { 0x320E, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x01,0x01,0x01,0x00,0x00,0x00}}, /* Aspect Ratio */
287     { 0x3201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x06,0x01,0x00,0x00,0x00,0x00}}, /* Picture Essence Coding */
288     { 0x3212, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x03,0x01,0x06,0x00,0x00,0x00}}, /* Field Dominance (Opt) */
289     // CDCI Picture Essence Descriptor
290     { 0x3301, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x05,0x03,0x0A,0x00,0x00,0x00}}, /* Component Depth */
291     { 0x3302, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x05,0x00,0x00,0x00}}, /* Horizontal Subsampling */
292     // Generic Sound Essence Descriptor
293     { 0x3D02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Locked/Unlocked */
294     { 0x3D03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x01,0x01,0x01,0x00,0x00}}, /* Audio sampling rate */
295     { 0x3D07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x01,0x01,0x04,0x00,0x00,0x00}}, /* ChannelCount */
296     { 0x3D01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x03,0x04,0x00,0x00,0x00}}, /* Quantization bits */
297     { 0x3D06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x02,0x04,0x02,0x00,0x00,0x00,0x00}}, /* Sound Essence Compression */
298     // Index Table Segment
299     { 0x3F0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x05,0x30,0x04,0x06,0x00,0x00,0x00,0x00}}, /* Index Edit Rate */
300     { 0x3F0C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x01,0x03,0x01,0x0A,0x00,0x00}}, /* Index Start Position */
301     { 0x3F0D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x02,0x01,0x01,0x02,0x00,0x00}}, /* Index Duration */
302     { 0x3F05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x06,0x02,0x01,0x00,0x00,0x00,0x00}}, /* Edit Unit Byte Count */
303     { 0x3F06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x05,0x00,0x00,0x00,0x00}}, /* IndexSID */
304     { 0x3F08, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x04,0x04,0x01,0x01,0x00,0x00,0x00}}, /* Slice Count */
305     { 0x3F09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x01,0x06,0x00,0x00,0x00}}, /* Delta Entry Array */
306     { 0x3F0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x02,0x05,0x00,0x00,0x00}}, /* Index Entry Array */
307     // MPEG video Descriptor
308     { 0x8000, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x0B,0x00,0x00}}, /* BitRate */
309     { 0x8007, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x0A,0x00,0x00}}, /* ProfileAndLevel */
310     // Wave Audio Essence Descriptor
311     { 0x3D09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x03,0x05,0x00,0x00,0x00}}, /* Average Bytes Per Second */
312     { 0x3D0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x02,0x01,0x00,0x00,0x00}}, /* Block Align */
313 };
314
315 static void mxf_write_uuid(AVIOContext *pb, enum MXFMetadataSetType type, int value)
316 {
317     avio_write(pb, uuid_base, 12);
318     avio_wb16(pb, type);
319     avio_wb16(pb, value);
320 }
321
322 static void mxf_write_umid(AVFormatContext *s, int type)
323 {
324     MXFContext *mxf = s->priv_data;
325     avio_write(s->pb, umid_ul, 13);
326     avio_wb24(s->pb, mxf->instance_number);
327     avio_write(s->pb, mxf->umid, 15);
328     avio_w8(s->pb, type);
329 }
330
331 static void mxf_write_refs_count(AVIOContext *pb, int ref_count)
332 {
333     avio_wb32(pb, ref_count);
334     avio_wb32(pb, 16);
335 }
336
337 static int klv_ber_length(uint64_t len)
338 {
339     if (len < 128)
340         return 1;
341     else
342         return (av_log2(len) >> 3) + 2;
343 }
344
345 static int klv_encode_ber_length(AVIOContext *pb, uint64_t len)
346 {
347     // Determine the best BER size
348     int size;
349     if (len < 128) {
350         //short form
351         avio_w8(pb, len);
352         return 1;
353     }
354
355     size = (av_log2(len) >> 3) + 1;
356
357     // long form
358     avio_w8(pb, 0x80 + size);
359     while(size) {
360         size--;
361         avio_w8(pb, len >> 8 * size & 0xff);
362     }
363     return 0;
364 }
365
366 static void klv_encode_ber4_length(AVIOContext *pb, int len)
367 {
368     avio_w8(pb, 0x80 + 3);
369     avio_wb24(pb, len);
370 }
371
372 /*
373  * Get essence container ul index
374  */
375 static int mxf_get_essence_container_ul_index(enum CodecID id)
376 {
377     int i;
378     for (i = 0; mxf_essence_mappings[i].id; i++)
379         if (mxf_essence_mappings[i].id == id)
380             return mxf_essence_mappings[i].index;
381     return -1;
382 }
383
384 static void mxf_write_primer_pack(AVFormatContext *s)
385 {
386     AVIOContext *pb = s->pb;
387     int local_tag_number, i = 0;
388
389     local_tag_number = FF_ARRAY_ELEMS(mxf_local_tag_batch);
390
391     avio_write(pb, primer_pack_key, 16);
392     klv_encode_ber_length(pb, local_tag_number * 18 + 8);
393
394     avio_wb32(pb, local_tag_number); // local_tag num
395     avio_wb32(pb, 18); // item size, always 18 according to the specs
396
397     for (i = 0; i < local_tag_number; i++) {
398         avio_wb16(pb, mxf_local_tag_batch[i].local_tag);
399         avio_write(pb, mxf_local_tag_batch[i].uid, 16);
400     }
401 }
402
403 static void mxf_write_local_tag(AVIOContext *pb, int size, int tag)
404 {
405     avio_wb16(pb, tag);
406     avio_wb16(pb, size);
407 }
408
409 static void mxf_write_metadata_key(AVIOContext *pb, unsigned int value)
410 {
411     avio_write(pb, header_metadata_key, 13);
412     avio_wb24(pb, value);
413 }
414
415 static void mxf_free(AVFormatContext *s)
416 {
417     int i;
418
419     for (i = 0; i < s->nb_streams; i++) {
420         AVStream *st = s->streams[i];
421         av_freep(&st->priv_data);
422     }
423 }
424
425 static const MXFCodecUL *mxf_get_data_definition_ul(int type)
426 {
427     const MXFCodecUL *uls = ff_mxf_data_definition_uls;
428     while (uls->uid[0]) {
429         if (type == uls->id)
430             break;
431         uls++;
432     }
433     return uls;
434 }
435
436 static void mxf_write_essence_container_refs(AVFormatContext *s)
437 {
438     MXFContext *c = s->priv_data;
439     AVIOContext *pb = s->pb;
440     int i;
441
442     mxf_write_refs_count(pb, c->essence_container_count);
443     av_log(s,AV_LOG_DEBUG, "essence container count:%d\n", c->essence_container_count);
444     for (i = 0; i < c->essence_container_count; i++) {
445         MXFStreamContext *sc = s->streams[i]->priv_data;
446         avio_write(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
447     }
448 }
449
450 static void mxf_write_preface(AVFormatContext *s)
451 {
452     MXFContext *mxf = s->priv_data;
453     AVIOContext *pb = s->pb;
454
455     mxf_write_metadata_key(pb, 0x012f00);
456     PRINT_KEY(s, "preface key", pb->buf_ptr - 16);
457     klv_encode_ber_length(pb, 130 + 16 * mxf->essence_container_count);
458
459     // write preface set uid
460     mxf_write_local_tag(pb, 16, 0x3C0A);
461     mxf_write_uuid(pb, Preface, 0);
462     PRINT_KEY(s, "preface uid", pb->buf_ptr - 16);
463
464     // last modified date
465     mxf_write_local_tag(pb, 8, 0x3B02);
466     avio_wb64(pb, mxf->timestamp);
467
468     // write version
469     mxf_write_local_tag(pb, 2, 0x3B05);
470     avio_wb16(pb, 258); // v1.2
471
472     // write identification_refs
473     mxf_write_local_tag(pb, 16 + 8, 0x3B06);
474     mxf_write_refs_count(pb, 1);
475     mxf_write_uuid(pb, Identification, 0);
476
477     // write content_storage_refs
478     mxf_write_local_tag(pb, 16, 0x3B03);
479     mxf_write_uuid(pb, ContentStorage, 0);
480
481     // operational pattern
482     mxf_write_local_tag(pb, 16, 0x3B09);
483     avio_write(pb, op1a_ul, 16);
484
485     // write essence_container_refs
486     mxf_write_local_tag(pb, 8 + 16 * mxf->essence_container_count, 0x3B0A);
487     mxf_write_essence_container_refs(s);
488
489     // write dm_scheme_refs
490     mxf_write_local_tag(pb, 8, 0x3B0B);
491     avio_wb64(pb, 0);
492 }
493
494 /*
495  * Write a local tag containing an ascii string as utf-16
496  */
497 static void mxf_write_local_tag_utf16(AVIOContext *pb, int tag, const char *value)
498 {
499     int i, size = strlen(value);
500     mxf_write_local_tag(pb, size*2, tag);
501     for (i = 0; i < size; i++)
502         avio_wb16(pb, value[i]);
503 }
504
505 static void mxf_write_identification(AVFormatContext *s)
506 {
507     MXFContext *mxf = s->priv_data;
508     AVIOContext *pb = s->pb;
509     const char *company = "FFmpeg";
510     const char *product = "OP1a Muxer";
511     const char *version;
512     int length;
513
514     mxf_write_metadata_key(pb, 0x013000);
515     PRINT_KEY(s, "identification key", pb->buf_ptr - 16);
516
517     version = s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT ?
518         "0.0.0" : AV_STRINGIFY(LIBAVFORMAT_VERSION);
519     length = 84 + (strlen(company)+strlen(product)+strlen(version))*2; // utf-16
520     klv_encode_ber_length(pb, length);
521
522     // write uid
523     mxf_write_local_tag(pb, 16, 0x3C0A);
524     mxf_write_uuid(pb, Identification, 0);
525     PRINT_KEY(s, "identification uid", pb->buf_ptr - 16);
526
527     // write generation uid
528     mxf_write_local_tag(pb, 16, 0x3C09);
529     mxf_write_uuid(pb, Identification, 1);
530
531     mxf_write_local_tag_utf16(pb, 0x3C01, company); // Company Name
532     mxf_write_local_tag_utf16(pb, 0x3C02, product); // Product Name
533     mxf_write_local_tag_utf16(pb, 0x3C04, version); // Version String
534
535     // write product uid
536     mxf_write_local_tag(pb, 16, 0x3C05);
537     mxf_write_uuid(pb, Identification, 2);
538
539     // modification date
540     mxf_write_local_tag(pb, 8, 0x3C06);
541     avio_wb64(pb, mxf->timestamp);
542 }
543
544 static void mxf_write_content_storage(AVFormatContext *s)
545 {
546     AVIOContext *pb = s->pb;
547
548     mxf_write_metadata_key(pb, 0x011800);
549     PRINT_KEY(s, "content storage key", pb->buf_ptr - 16);
550     klv_encode_ber_length(pb, 92);
551
552     // write uid
553     mxf_write_local_tag(pb, 16, 0x3C0A);
554     mxf_write_uuid(pb, ContentStorage, 0);
555     PRINT_KEY(s, "content storage uid", pb->buf_ptr - 16);
556
557     // write package reference
558     mxf_write_local_tag(pb, 16 * 2 + 8, 0x1901);
559     mxf_write_refs_count(pb, 2);
560     mxf_write_uuid(pb, MaterialPackage, 0);
561     mxf_write_uuid(pb, SourcePackage, 0);
562
563     // write essence container data
564     mxf_write_local_tag(pb, 8 + 16, 0x1902);
565     mxf_write_refs_count(pb, 1);
566     mxf_write_uuid(pb, EssenceContainerData, 0);
567 }
568
569 static void mxf_write_track(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
570 {
571     MXFContext *mxf = s->priv_data;
572     AVIOContext *pb = s->pb;
573     MXFStreamContext *sc = st->priv_data;
574
575     mxf_write_metadata_key(pb, 0x013b00);
576     PRINT_KEY(s, "track key", pb->buf_ptr - 16);
577     klv_encode_ber_length(pb, 80);
578
579     // write track uid
580     mxf_write_local_tag(pb, 16, 0x3C0A);
581     mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, st->index);
582     PRINT_KEY(s, "track uid", pb->buf_ptr - 16);
583
584     // write track id
585     mxf_write_local_tag(pb, 4, 0x4801);
586     avio_wb32(pb, st->index+2);
587
588     // write track number
589     mxf_write_local_tag(pb, 4, 0x4804);
590     if (type == MaterialPackage)
591         avio_wb32(pb, 0); // track number of material package is 0
592     else
593         avio_write(pb, sc->track_essence_element_key + 12, 4);
594
595     mxf_write_local_tag(pb, 8, 0x4B01);
596     avio_wb32(pb, mxf->time_base.den);
597     avio_wb32(pb, mxf->time_base.num);
598
599     // write origin
600     mxf_write_local_tag(pb, 8, 0x4B02);
601     avio_wb64(pb, 0);
602
603     // write sequence refs
604     mxf_write_local_tag(pb, 16, 0x4803);
605     mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
606 }
607
608 static const uint8_t smpte_12m_timecode_track_data_ul[] = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x01,0x03,0x02,0x01,0x01,0x00,0x00,0x00 };
609
610 static void mxf_write_common_fields(AVFormatContext *s, AVStream *st)
611 {
612     MXFContext *mxf = s->priv_data;
613     AVIOContext *pb = s->pb;
614
615     // find data define uls
616     mxf_write_local_tag(pb, 16, 0x0201);
617     if (st == mxf->timecode_track)
618         avio_write(pb, smpte_12m_timecode_track_data_ul, 16);
619     else {
620         const MXFCodecUL *data_def_ul = mxf_get_data_definition_ul(st->codec->codec_type);
621         avio_write(pb, data_def_ul->uid, 16);
622     }
623
624     // write duration
625     mxf_write_local_tag(pb, 8, 0x0202);
626     avio_wb64(pb, mxf->duration);
627 }
628
629 static void mxf_write_sequence(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
630 {
631     MXFContext *mxf = s->priv_data;
632     AVIOContext *pb = s->pb;
633     enum MXFMetadataSetType component;
634
635     mxf_write_metadata_key(pb, 0x010f00);
636     PRINT_KEY(s, "sequence key", pb->buf_ptr - 16);
637     klv_encode_ber_length(pb, 80);
638
639     mxf_write_local_tag(pb, 16, 0x3C0A);
640     mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
641
642     PRINT_KEY(s, "sequence uid", pb->buf_ptr - 16);
643     mxf_write_common_fields(s, st);
644
645     // write structural component
646     mxf_write_local_tag(pb, 16 + 8, 0x1001);
647     mxf_write_refs_count(pb, 1);
648     if (st == mxf->timecode_track)
649         component = TimecodeComponent;
650     else
651         component = SourceClip;
652     if (type == SourcePackage)
653         component += TypeBottom;
654     mxf_write_uuid(pb, component, st->index);
655 }
656
657 static void mxf_write_timecode_component(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
658 {
659     MXFContext *mxf = s->priv_data;
660     AVIOContext *pb = s->pb;
661
662     mxf_write_metadata_key(pb, 0x011400);
663     klv_encode_ber_length(pb, 75);
664
665     // UID
666     mxf_write_local_tag(pb, 16, 0x3C0A);
667     mxf_write_uuid(pb, type == MaterialPackage ? TimecodeComponent :
668                    TimecodeComponent + TypeBottom, st->index);
669
670     mxf_write_common_fields(s, st);
671
672     // Start Time Code
673     mxf_write_local_tag(pb, 8, 0x1501);
674     avio_wb64(pb, mxf->tc.start);
675
676     // Rounded Time Code Base
677     mxf_write_local_tag(pb, 2, 0x1502);
678     avio_wb16(pb, mxf->timecode_base);
679
680     // Drop Frame
681     mxf_write_local_tag(pb, 1, 0x1503);
682     avio_w8(pb, !!(mxf->tc.flags & AV_TIMECODE_FLAG_DROPFRAME));
683 }
684
685 static void mxf_write_structural_component(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
686 {
687     AVIOContext *pb = s->pb;
688     int i;
689
690     mxf_write_metadata_key(pb, 0x011100);
691     PRINT_KEY(s, "sturctural component key", pb->buf_ptr - 16);
692     klv_encode_ber_length(pb, 108);
693
694     // write uid
695     mxf_write_local_tag(pb, 16, 0x3C0A);
696     mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
697
698     PRINT_KEY(s, "structural component uid", pb->buf_ptr - 16);
699     mxf_write_common_fields(s, st);
700
701     // write start_position
702     mxf_write_local_tag(pb, 8, 0x1201);
703     avio_wb64(pb, 0);
704
705     // write source package uid, end of the reference
706     mxf_write_local_tag(pb, 32, 0x1101);
707     if (type == SourcePackage) {
708         for (i = 0; i < 4; i++)
709             avio_wb64(pb, 0);
710     } else
711         mxf_write_umid(s, 1);
712
713     // write source track id
714     mxf_write_local_tag(pb, 4, 0x1102);
715     if (type == SourcePackage)
716         avio_wb32(pb, 0);
717     else
718         avio_wb32(pb, st->index+2);
719 }
720
721 static void mxf_write_multi_descriptor(AVFormatContext *s)
722 {
723     MXFContext *mxf = s->priv_data;
724     AVIOContext *pb = s->pb;
725     const uint8_t *ul;
726     int i;
727
728     mxf_write_metadata_key(pb, 0x014400);
729     PRINT_KEY(s, "multiple descriptor key", pb->buf_ptr - 16);
730     klv_encode_ber_length(pb, 64 + 16 * s->nb_streams);
731
732     mxf_write_local_tag(pb, 16, 0x3C0A);
733     mxf_write_uuid(pb, MultipleDescriptor, 0);
734     PRINT_KEY(s, "multi_desc uid", pb->buf_ptr - 16);
735
736     // write sample rate
737     mxf_write_local_tag(pb, 8, 0x3001);
738     avio_wb32(pb, mxf->time_base.den);
739     avio_wb32(pb, mxf->time_base.num);
740
741     // write essence container ul
742     mxf_write_local_tag(pb, 16, 0x3004);
743     if (mxf->essence_container_count > 1)
744         ul = multiple_desc_ul;
745     else {
746         MXFStreamContext *sc = s->streams[0]->priv_data;
747         ul = mxf_essence_container_uls[sc->index].container_ul;
748     }
749     avio_write(pb, ul, 16);
750
751     // write sub descriptor refs
752     mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x3F01);
753     mxf_write_refs_count(pb, s->nb_streams);
754     for (i = 0; i < s->nb_streams; i++)
755         mxf_write_uuid(pb, SubDescriptor, i);
756 }
757
758 static void mxf_write_generic_desc(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
759 {
760     MXFContext *mxf = s->priv_data;
761     MXFStreamContext *sc = st->priv_data;
762     AVIOContext *pb = s->pb;
763
764     avio_write(pb, key, 16);
765     klv_encode_ber4_length(pb, size+20+8+12+20);
766
767     mxf_write_local_tag(pb, 16, 0x3C0A);
768     mxf_write_uuid(pb, SubDescriptor, st->index);
769
770     mxf_write_local_tag(pb, 4, 0x3006);
771     avio_wb32(pb, st->index+2);
772
773     mxf_write_local_tag(pb, 8, 0x3001);
774     avio_wb32(pb, mxf->time_base.den);
775     avio_wb32(pb, mxf->time_base.num);
776
777     mxf_write_local_tag(pb, 16, 0x3004);
778     avio_write(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
779 }
780
781 static const UID mxf_mpegvideo_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 };
782 static const UID mxf_wav_descriptor_key       = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 };
783 static const UID mxf_aes3_descriptor_key      = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 };
784 static const UID mxf_cdci_descriptor_key      = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x28,0x00 };
785 static const UID mxf_generic_sound_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x42,0x00 };
786
787 static void mxf_write_cdci_common(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
788 {
789     MXFStreamContext *sc = st->priv_data;
790     AVIOContext *pb = s->pb;
791     int stored_height = (st->codec->height+15)/16*16;
792     int display_height;
793     int f1, f2;
794     unsigned desc_size = size+8+8+8+8+8+8+5+16+sc->interlaced*4+12+20;
795     if (sc->interlaced && sc->field_dominance)
796         desc_size += 5;
797
798     mxf_write_generic_desc(s, st, key, desc_size);
799
800     mxf_write_local_tag(pb, 4, 0x3203);
801     avio_wb32(pb, st->codec->width);
802
803     mxf_write_local_tag(pb, 4, 0x3202);
804     avio_wb32(pb, stored_height>>sc->interlaced);
805
806     mxf_write_local_tag(pb, 4, 0x3209);
807     avio_wb32(pb, st->codec->width);
808
809     if (st->codec->height == 608) // PAL + VBI
810         display_height = 576;
811     else if (st->codec->height == 512)  // NTSC + VBI
812         display_height = 486;
813     else
814         display_height = st->codec->height;
815
816     mxf_write_local_tag(pb, 4, 0x3208);
817     avio_wb32(pb, display_height>>sc->interlaced);
818
819     // component depth
820     mxf_write_local_tag(pb, 4, 0x3301);
821     avio_wb32(pb, 8);
822
823     // horizontal subsampling
824     mxf_write_local_tag(pb, 4, 0x3302);
825     avio_wb32(pb, 2);
826
827     // frame layout
828     mxf_write_local_tag(pb, 1, 0x320C);
829     avio_w8(pb, sc->interlaced);
830
831     // video line map
832     switch (st->codec->height) {
833     case  576: f1 = 23; f2 = 336; break;
834     case  608: f1 =  7; f2 = 320; break;
835     case  480: f1 = 20; f2 = 283; break;
836     case  512: f1 =  7; f2 = 270; break;
837     case  720: f1 = 26; f2 =   0; break; // progressive
838     case 1080: f1 = 21; f2 = 584; break;
839     default:   f1 =  0; f2 =   0; break;
840     }
841
842     if (!sc->interlaced) {
843         f2  = 0;
844         f1 *= 2;
845     }
846
847     mxf_write_local_tag(pb, 12+sc->interlaced*4, 0x320D);
848     avio_wb32(pb, sc->interlaced ? 2 : 1);
849     avio_wb32(pb, 4);
850     avio_wb32(pb, f1);
851     if (sc->interlaced)
852         avio_wb32(pb, f2);
853
854     mxf_write_local_tag(pb, 8, 0x320E);
855     avio_wb32(pb, sc->aspect_ratio.num);
856     avio_wb32(pb, sc->aspect_ratio.den);
857
858     mxf_write_local_tag(pb, 16, 0x3201);
859     avio_write(pb, *sc->codec_ul, 16);
860
861     if (sc->interlaced && sc->field_dominance) {
862         mxf_write_local_tag(pb, 1, 0x3212);
863         avio_w8(pb, sc->field_dominance);
864     }
865
866 }
867
868 static void mxf_write_cdci_desc(AVFormatContext *s, AVStream *st)
869 {
870     mxf_write_cdci_common(s, st, mxf_cdci_descriptor_key, 0);
871 }
872
873 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st)
874 {
875     AVIOContext *pb = s->pb;
876     int profile_and_level = (st->codec->profile<<4) | st->codec->level;
877
878     mxf_write_cdci_common(s, st, mxf_mpegvideo_descriptor_key, 8+5);
879
880     // bit rate
881     mxf_write_local_tag(pb, 4, 0x8000);
882     avio_wb32(pb, st->codec->bit_rate);
883
884     // profile and level
885     mxf_write_local_tag(pb, 1, 0x8007);
886     if (!st->codec->profile)
887         profile_and_level |= 0x80; // escape bit
888     avio_w8(pb, profile_and_level);
889 }
890
891 static void mxf_write_generic_sound_common(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
892 {
893     AVIOContext *pb = s->pb;
894
895     mxf_write_generic_desc(s, st, key, size+5+12+8+8);
896
897     // audio locked
898     mxf_write_local_tag(pb, 1, 0x3D02);
899     avio_w8(pb, 1);
900
901     // write audio sampling rate
902     mxf_write_local_tag(pb, 8, 0x3D03);
903     avio_wb32(pb, st->codec->sample_rate);
904     avio_wb32(pb, 1);
905
906     mxf_write_local_tag(pb, 4, 0x3D07);
907     avio_wb32(pb, st->codec->channels);
908
909     mxf_write_local_tag(pb, 4, 0x3D01);
910     avio_wb32(pb, av_get_bits_per_sample(st->codec->codec_id));
911 }
912
913 static void mxf_write_wav_common(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
914 {
915     AVIOContext *pb = s->pb;
916
917     mxf_write_generic_sound_common(s, st, key, size+6+8);
918
919     mxf_write_local_tag(pb, 2, 0x3D0A);
920     avio_wb16(pb, st->codec->block_align);
921
922     // avg bytes per sec
923     mxf_write_local_tag(pb, 4, 0x3D09);
924     avio_wb32(pb, st->codec->block_align*st->codec->sample_rate);
925 }
926
927 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st)
928 {
929     mxf_write_wav_common(s, st, mxf_wav_descriptor_key, 0);
930 }
931
932 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st)
933 {
934     mxf_write_wav_common(s, st, mxf_aes3_descriptor_key, 0);
935 }
936
937 static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st)
938 {
939     mxf_write_generic_sound_common(s, st, mxf_generic_sound_descriptor_key, 0);
940 }
941
942 static void mxf_write_package(AVFormatContext *s, enum MXFMetadataSetType type)
943 {
944     MXFContext *mxf = s->priv_data;
945     AVIOContext *pb = s->pb;
946     int i, track_count = s->nb_streams+1;
947
948     if (type == MaterialPackage) {
949         mxf_write_metadata_key(pb, 0x013600);
950         PRINT_KEY(s, "Material Package key", pb->buf_ptr - 16);
951         klv_encode_ber_length(pb, 92 + 16*track_count);
952     } else {
953         mxf_write_metadata_key(pb, 0x013700);
954         PRINT_KEY(s, "Source Package key", pb->buf_ptr - 16);
955         klv_encode_ber_length(pb, 112 + 16*track_count); // 20 bytes length for descriptor reference
956     }
957
958     // write uid
959     mxf_write_local_tag(pb, 16, 0x3C0A);
960     mxf_write_uuid(pb, type, 0);
961     av_log(s,AV_LOG_DEBUG, "package type:%d\n", type);
962     PRINT_KEY(s, "package uid", pb->buf_ptr - 16);
963
964     // write package umid
965     mxf_write_local_tag(pb, 32, 0x4401);
966     mxf_write_umid(s, type == SourcePackage);
967     PRINT_KEY(s, "package umid second part", pb->buf_ptr - 16);
968
969     // package creation date
970     mxf_write_local_tag(pb, 8, 0x4405);
971     avio_wb64(pb, mxf->timestamp);
972
973     // package modified date
974     mxf_write_local_tag(pb, 8, 0x4404);
975     avio_wb64(pb, mxf->timestamp);
976
977     // write track refs
978     mxf_write_local_tag(pb, track_count*16 + 8, 0x4403);
979     mxf_write_refs_count(pb, track_count);
980     mxf_write_uuid(pb, type == MaterialPackage ? Track :
981                    Track + TypeBottom, -1); // timecode track
982     for (i = 0; i < s->nb_streams; i++)
983         mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, i);
984
985     // write multiple descriptor reference
986     if (type == SourcePackage) {
987         mxf_write_local_tag(pb, 16, 0x4701);
988         if (s->nb_streams > 1) {
989             mxf_write_uuid(pb, MultipleDescriptor, 0);
990             mxf_write_multi_descriptor(s);
991         } else
992             mxf_write_uuid(pb, SubDescriptor, 0);
993     }
994
995     // write timecode track
996     mxf_write_track(s, mxf->timecode_track, type);
997     mxf_write_sequence(s, mxf->timecode_track, type);
998     mxf_write_timecode_component(s, mxf->timecode_track, type);
999
1000     for (i = 0; i < s->nb_streams; i++) {
1001         AVStream *st = s->streams[i];
1002         mxf_write_track(s, st, type);
1003         mxf_write_sequence(s, st, type);
1004         mxf_write_structural_component(s, st, type);
1005
1006         if (type == SourcePackage) {
1007             MXFStreamContext *sc = st->priv_data;
1008             mxf_essence_container_uls[sc->index].write_desc(s, st);
1009         }
1010     }
1011 }
1012
1013 static int mxf_write_essence_container_data(AVFormatContext *s)
1014 {
1015     AVIOContext *pb = s->pb;
1016
1017     mxf_write_metadata_key(pb, 0x012300);
1018     klv_encode_ber_length(pb, 72);
1019
1020     mxf_write_local_tag(pb, 16, 0x3C0A); // Instance UID
1021     mxf_write_uuid(pb, EssenceContainerData, 0);
1022
1023     mxf_write_local_tag(pb, 32, 0x2701); // Linked Package UID
1024     mxf_write_umid(s, 1);
1025
1026     mxf_write_local_tag(pb, 4, 0x3F07); // BodySID
1027     avio_wb32(pb, 1);
1028
1029     mxf_write_local_tag(pb, 4, 0x3F06); // IndexSID
1030     avio_wb32(pb, 2);
1031
1032     return 0;
1033 }
1034
1035 static int mxf_write_header_metadata_sets(AVFormatContext *s)
1036 {
1037     mxf_write_preface(s);
1038     mxf_write_identification(s);
1039     mxf_write_content_storage(s);
1040     mxf_write_package(s, MaterialPackage);
1041     mxf_write_package(s, SourcePackage);
1042     mxf_write_essence_container_data(s);
1043     return 0;
1044 }
1045
1046 static unsigned klv_fill_size(uint64_t size)
1047 {
1048     unsigned pad = KAG_SIZE - (size & (KAG_SIZE-1));
1049     if (pad < 20) // smallest fill item possible
1050         return pad + KAG_SIZE;
1051     else
1052         return pad & (KAG_SIZE-1);
1053 }
1054
1055 static void mxf_write_index_table_segment(AVFormatContext *s)
1056 {
1057     MXFContext *mxf = s->priv_data;
1058     AVIOContext *pb = s->pb;
1059     int i, j, temporal_reordering = 0;
1060     int key_index = mxf->last_key_index;
1061
1062     av_log(s, AV_LOG_DEBUG, "edit units count %d\n", mxf->edit_units_count);
1063
1064     if (!mxf->edit_units_count && !mxf->edit_unit_byte_count)
1065         return;
1066
1067     avio_write(pb, index_table_segment_key, 16);
1068
1069     if (mxf->edit_unit_byte_count) {
1070         klv_encode_ber_length(pb, 80);
1071     } else {
1072         klv_encode_ber_length(pb, 85 + 12+(s->nb_streams+1)*6 +
1073                               12+mxf->edit_units_count*(11+mxf->slice_count*4));
1074     }
1075
1076     // instance id
1077     mxf_write_local_tag(pb, 16, 0x3C0A);
1078     mxf_write_uuid(pb, IndexTableSegment, 0);
1079
1080     // index edit rate
1081     mxf_write_local_tag(pb, 8, 0x3F0B);
1082     avio_wb32(pb, mxf->time_base.den);
1083     avio_wb32(pb, mxf->time_base.num);
1084
1085     // index start position
1086     mxf_write_local_tag(pb, 8, 0x3F0C);
1087     avio_wb64(pb, mxf->last_indexed_edit_unit);
1088
1089     // index duration
1090     mxf_write_local_tag(pb, 8, 0x3F0D);
1091     if (mxf->edit_unit_byte_count)
1092         avio_wb64(pb, 0); // index table covers whole container
1093     else
1094         avio_wb64(pb, mxf->edit_units_count);
1095
1096     // edit unit byte count
1097     mxf_write_local_tag(pb, 4, 0x3F05);
1098     avio_wb32(pb, mxf->edit_unit_byte_count);
1099
1100     // index sid
1101     mxf_write_local_tag(pb, 4, 0x3F06);
1102     avio_wb32(pb, 2);
1103
1104     // body sid
1105     mxf_write_local_tag(pb, 4, 0x3F07);
1106     avio_wb32(pb, 1);
1107
1108     if (!mxf->edit_unit_byte_count) {
1109         // real slice count - 1
1110         mxf_write_local_tag(pb, 1, 0x3F08);
1111         avio_w8(pb, mxf->slice_count);
1112
1113         // delta entry array
1114         mxf_write_local_tag(pb, 8 + (s->nb_streams+1)*6, 0x3F09);
1115         avio_wb32(pb, s->nb_streams+1); // num of entries
1116         avio_wb32(pb, 6);               // size of one entry
1117         // write system item delta entry
1118         avio_w8(pb, 0);
1119         avio_w8(pb, 0); // slice entry
1120         avio_wb32(pb, 0); // element delta
1121         for (i = 0; i < s->nb_streams; i++) {
1122             AVStream *st = s->streams[i];
1123             MXFStreamContext *sc = st->priv_data;
1124             avio_w8(pb, sc->temporal_reordering);
1125             if (sc->temporal_reordering)
1126                 temporal_reordering = 1;
1127             if (i == 0) { // video track
1128                 avio_w8(pb, 0); // slice number
1129                 avio_wb32(pb, KAG_SIZE); // system item size including klv fill
1130             } else { // audio track
1131                 unsigned audio_frame_size = sc->aic.samples[0]*sc->aic.sample_size;
1132                 audio_frame_size += klv_fill_size(audio_frame_size);
1133                 avio_w8(pb, 1);
1134                 avio_wb32(pb, (i-1)*audio_frame_size); // element delta
1135             }
1136         }
1137
1138         mxf_write_local_tag(pb, 8 + mxf->edit_units_count*(11+mxf->slice_count*4), 0x3F0A);
1139         avio_wb32(pb, mxf->edit_units_count);  // num of entries
1140         avio_wb32(pb, 11+mxf->slice_count*4);  // size of one entry
1141
1142         for (i = 0; i < mxf->edit_units_count; i++) {
1143             int temporal_offset = 0;
1144
1145             if (!(mxf->index_entries[i].flags & 0x33)) { // I frame
1146                 mxf->last_key_index = key_index;
1147                 key_index = i;
1148             }
1149
1150             if (temporal_reordering) {
1151                 int pic_num_in_gop = i - key_index;
1152                 if (pic_num_in_gop != mxf->index_entries[i].temporal_ref) {
1153                     for (j = key_index; j < mxf->edit_units_count; j++) {
1154                         if (pic_num_in_gop == mxf->index_entries[j].temporal_ref)
1155                             break;
1156                     }
1157                     if (j == mxf->edit_units_count)
1158                         av_log(s, AV_LOG_WARNING, "missing frames\n");
1159                     temporal_offset = j - key_index - pic_num_in_gop;
1160                 }
1161             }
1162             avio_w8(pb, temporal_offset);
1163
1164             if ((mxf->index_entries[i].flags & 0x30) == 0x30) { // back and forward prediction
1165                 avio_w8(pb, mxf->last_key_index - i);
1166             } else {
1167                 avio_w8(pb, key_index - i); // key frame offset
1168                 if ((mxf->index_entries[i].flags & 0x20) == 0x20) // only forward
1169                     mxf->last_key_index = key_index;
1170             }
1171
1172             if (!(mxf->index_entries[i].flags & 0x33) && // I frame
1173                 mxf->index_entries[i].flags & 0x40 && !temporal_offset)
1174                 mxf->index_entries[i].flags |= 0x80; // random access
1175             avio_w8(pb, mxf->index_entries[i].flags);
1176             // stream offset
1177             avio_wb64(pb, mxf->index_entries[i].offset);
1178             if (s->nb_streams > 1)
1179                 avio_wb32(pb, mxf->index_entries[i].slice_offset);
1180         }
1181
1182         mxf->last_key_index = key_index - mxf->edit_units_count;
1183         mxf->last_indexed_edit_unit += mxf->edit_units_count;
1184         mxf->edit_units_count = 0;
1185     }
1186 }
1187
1188 static void mxf_write_klv_fill(AVFormatContext *s)
1189 {
1190     unsigned pad = klv_fill_size(avio_tell(s->pb));
1191     if (pad) {
1192         avio_write(s->pb, klv_fill_key, 16);
1193         pad -= 16 + 4;
1194         klv_encode_ber4_length(s->pb, pad);
1195         for (; pad; pad--)
1196             avio_w8(s->pb, 0);
1197         assert(!(avio_tell(s->pb) & (KAG_SIZE-1)));
1198     }
1199 }
1200
1201 static void mxf_write_partition(AVFormatContext *s, int bodysid,
1202                                 int indexsid,
1203                                 const uint8_t *key, int write_metadata)
1204 {
1205     MXFContext *mxf = s->priv_data;
1206     AVIOContext *pb = s->pb;
1207     int64_t header_byte_count_offset;
1208     unsigned index_byte_count = 0;
1209     uint64_t partition_offset = avio_tell(pb);
1210
1211     if (!mxf->edit_unit_byte_count && mxf->edit_units_count)
1212         index_byte_count = 85 + 12+(s->nb_streams+1)*6 +
1213             12+mxf->edit_units_count*(11+mxf->slice_count*4);
1214     else if (mxf->edit_unit_byte_count && indexsid)
1215         index_byte_count = 80;
1216
1217     if (index_byte_count) {
1218         // add encoded ber length
1219         index_byte_count += 16 + klv_ber_length(index_byte_count);
1220         index_byte_count += klv_fill_size(index_byte_count);
1221     }
1222
1223     if (!memcmp(key, body_partition_key, 16)) {
1224         mxf->body_partition_offset =
1225             av_realloc(mxf->body_partition_offset,
1226                        (mxf->body_partitions_count+1)*
1227                        sizeof(*mxf->body_partition_offset));
1228         mxf->body_partition_offset[mxf->body_partitions_count++] = partition_offset;
1229     }
1230
1231     // write klv
1232     avio_write(pb, key, 16);
1233     klv_encode_ber_length(pb, 88 + 16 * mxf->essence_container_count);
1234
1235     // write partition value
1236     avio_wb16(pb, 1); // majorVersion
1237     avio_wb16(pb, 2); // minorVersion
1238     avio_wb32(pb, KAG_SIZE); // KAGSize
1239
1240     avio_wb64(pb, partition_offset); // ThisPartition
1241
1242     if (!memcmp(key, body_partition_key, 16) && mxf->body_partitions_count > 1)
1243         avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-2]); // PreviousPartition
1244     else if (!memcmp(key, footer_partition_key, 16) && mxf->body_partitions_count)
1245         avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-1]); // PreviousPartition
1246     else
1247         avio_wb64(pb, 0);
1248
1249     avio_wb64(pb, mxf->footer_partition_offset); // footerPartition
1250
1251     // set offset
1252     header_byte_count_offset = avio_tell(pb);
1253     avio_wb64(pb, 0); // headerByteCount, update later
1254
1255     // indexTable
1256     avio_wb64(pb, index_byte_count); // indexByteCount
1257     avio_wb32(pb, index_byte_count ? indexsid : 0); // indexSID
1258
1259     // BodyOffset
1260     if (bodysid && mxf->edit_units_count && mxf->body_partitions_count) {
1261         avio_wb64(pb, mxf->body_offset);
1262     } else
1263         avio_wb64(pb, 0);
1264
1265     avio_wb32(pb, bodysid); // bodySID
1266
1267     // operational pattern
1268     avio_write(pb, op1a_ul, 16);
1269
1270     // essence container
1271     mxf_write_essence_container_refs(s);
1272
1273     if (write_metadata) {
1274         // mark the start of the headermetadata and calculate metadata size
1275         int64_t pos, start;
1276         unsigned header_byte_count;
1277
1278         mxf_write_klv_fill(s);
1279         start = avio_tell(s->pb);
1280         mxf_write_primer_pack(s);
1281         mxf_write_header_metadata_sets(s);
1282         pos = avio_tell(s->pb);
1283         header_byte_count = pos - start + klv_fill_size(pos);
1284
1285         // update header_byte_count
1286         avio_seek(pb, header_byte_count_offset, SEEK_SET);
1287         avio_wb64(pb, header_byte_count);
1288         avio_seek(pb, pos, SEEK_SET);
1289     }
1290
1291     avio_flush(pb);
1292 }
1293
1294 static const UID mxf_mpeg2_codec_uls[] = {
1295     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x10,0x00 }, // MP-ML I-Frame
1296     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, // MP-ML Long GOP
1297     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, // 422P-ML I-Frame
1298     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, // 422P-ML Long GOP
1299     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x02,0x00 }, // MP-HL I-Frame
1300     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, // MP-HL Long GOP
1301     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, // 422P-HL I-Frame
1302     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, // 422P-HL Long GOP
1303     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x05,0x02,0x00 }, // MP@H-14 I-Frame
1304     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x05,0x03,0x00 }, // MP@H-14 Long GOP
1305 };
1306
1307 static const UID *mxf_get_mpeg2_codec_ul(AVCodecContext *avctx)
1308 {
1309     int long_gop = avctx->gop_size > 1 || avctx->has_b_frames;
1310
1311     if (avctx->profile == 4) { // Main
1312         if (avctx->level == 8) // Main
1313             return &mxf_mpeg2_codec_uls[0+long_gop];
1314         else if (avctx->level == 4) // High
1315             return &mxf_mpeg2_codec_uls[4+long_gop];
1316         else if (avctx->level == 6) // High 14
1317             return &mxf_mpeg2_codec_uls[8+long_gop];
1318     } else if (avctx->profile == 0) { // 422
1319         if (avctx->level == 5) // Main
1320             return &mxf_mpeg2_codec_uls[2+long_gop];
1321         else if (avctx->level == 2) // High
1322             return &mxf_mpeg2_codec_uls[6+long_gop];
1323     }
1324     return NULL;
1325 }
1326
1327 static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st,
1328                                  AVPacket *pkt, MXFIndexEntry *e)
1329 {
1330     MXFStreamContext *sc = st->priv_data;
1331     uint32_t c = -1;
1332     int i;
1333
1334     for(i = 0; i < pkt->size - 4; i++) {
1335         c = (c<<8) + pkt->data[i];
1336         if (c == 0x1b5) {
1337             if ((pkt->data[i+1] & 0xf0) == 0x10) { // seq ext
1338                 st->codec->profile = pkt->data[i+1] & 0x07;
1339                 st->codec->level   = pkt->data[i+2] >> 4;
1340             } else if (i + 5 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x80) { // pict coding ext
1341                 sc->interlaced = !(pkt->data[i+5] & 0x80); // progressive frame
1342                 if (sc->interlaced)
1343                     sc->field_dominance = 1 + !(pkt->data[i+4] & 0x80); // top field first
1344                 break;
1345             }
1346         } else if (c == 0x1b8) { // gop
1347             if (pkt->data[i+4]>>6 & 0x01) { // closed
1348                 sc->closed_gop = 1;
1349                 if (e->flags & 0x40) // sequence header present
1350                     e->flags |= 0x80; // random access
1351             }
1352         } else if (c == 0x1b3) { // seq
1353             e->flags |= 0x40;
1354             switch ((pkt->data[i+4]>>4) & 0xf) {
1355             case 2:  sc->aspect_ratio = (AVRational){  4,  3}; break;
1356             case 3:  sc->aspect_ratio = (AVRational){ 16,  9}; break;
1357             case 4:  sc->aspect_ratio = (AVRational){221,100}; break;
1358             default:
1359                 av_reduce(&sc->aspect_ratio.num, &sc->aspect_ratio.den,
1360                           st->codec->width, st->codec->height, 1024*1024);
1361             }
1362         } else if (c == 0x100) { // pic
1363             int pict_type = (pkt->data[i+2]>>3) & 0x07;
1364             e->temporal_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
1365             if (pict_type == 2) { // P frame
1366                 e->flags |= 0x22;
1367                 sc->closed_gop = 0; // reset closed gop, don't matter anymore
1368             } else if (pict_type == 3) { // B frame
1369                 if (sc->closed_gop)
1370                     e->flags |= 0x13; // only backward prediction
1371                 else
1372                     e->flags |= 0x33;
1373                 sc->temporal_reordering = -1;
1374             } else if (!pict_type) {
1375                 av_log(s, AV_LOG_ERROR, "error parsing mpeg2 frame\n");
1376                 return 0;
1377             }
1378         }
1379     }
1380     if (s->oformat != &ff_mxf_d10_muxer)
1381         sc->codec_ul = mxf_get_mpeg2_codec_ul(st->codec);
1382     return !!sc->codec_ul;
1383 }
1384
1385 static uint64_t mxf_parse_timestamp(time_t timestamp)
1386 {
1387     struct tm *time = gmtime(&timestamp);
1388     if (!time)
1389         return 0;
1390     return (uint64_t)(time->tm_year+1900) << 48 |
1391            (uint64_t)(time->tm_mon+1)     << 40 |
1392            (uint64_t) time->tm_mday       << 32 |
1393                       time->tm_hour       << 24 |
1394                       time->tm_min        << 16 |
1395                       time->tm_sec        << 8;
1396 }
1397
1398 static void mxf_gen_umid(AVFormatContext *s)
1399 {
1400     MXFContext *mxf = s->priv_data;
1401     uint32_t seed = av_get_random_seed();
1402     uint64_t umid = seed + 0x5294713400000000LL;
1403
1404     AV_WB64(mxf->umid  , umid);
1405     AV_WB64(mxf->umid+8, umid>>8);
1406
1407     mxf->instance_number = seed;
1408 }
1409
1410 static int mxf_write_header(AVFormatContext *s)
1411 {
1412     MXFContext *mxf = s->priv_data;
1413     int i, ret;
1414     uint8_t present[FF_ARRAY_ELEMS(mxf_essence_container_uls)] = {0};
1415     const int *samples_per_frame = NULL;
1416     AVDictionaryEntry *t;
1417     int64_t timestamp = 0;
1418     AVDictionaryEntry *tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
1419
1420     if (!s->nb_streams)
1421         return -1;
1422
1423     for (i = 0; i < s->nb_streams; i++) {
1424         AVStream *st = s->streams[i];
1425         MXFStreamContext *sc = av_mallocz(sizeof(*sc));
1426         if (!sc)
1427             return AVERROR(ENOMEM);
1428         st->priv_data = sc;
1429
1430         if ((i == 0) ^ (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)) {
1431             av_log(s, AV_LOG_ERROR, "there must be exactly one video stream and it must be the first one\n");
1432             return -1;
1433         }
1434
1435         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1436             AVRational rate;
1437             if (fabs(av_q2d(st->codec->time_base) - 1/25.0) < 0.0001) {
1438                 samples_per_frame = PAL_samples_per_frame;
1439                 mxf->time_base = (AVRational){ 1, 25 };
1440                 mxf->timecode_base = 25;
1441             } else if (fabs(av_q2d(st->codec->time_base) - 1/50.0) < 0.0001) {
1442                 samples_per_frame = PAL_50_samples_per_frame;
1443                 mxf->time_base = (AVRational){ 1, 50 };
1444                 mxf->timecode_base = 50;
1445             } else if (fabs(av_q2d(st->codec->time_base) - 1001/30000.0) < 0.0001) {
1446                 samples_per_frame = NTSC_samples_per_frame;
1447                 mxf->time_base = (AVRational){ 1001, 30000 };
1448                 mxf->timecode_base = 30;
1449             } else if (fabs(av_q2d(st->codec->time_base) - 1001/60000.0) < 0.0001) {
1450                 samples_per_frame = NTSC_60_samples_per_frame;
1451                 mxf->time_base = (AVRational){ 1001, 60000 };
1452                 mxf->timecode_base = 60;
1453             } else {
1454                 av_log(s, AV_LOG_ERROR, "unsupported video frame rate\n");
1455                 return -1;
1456             }
1457             rate = (AVRational){mxf->time_base.den, mxf->time_base.num};
1458             avpriv_set_pts_info(st, 64, mxf->time_base.num, mxf->time_base.den);
1459             if (!tcr)
1460                 tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
1461             if (tcr)
1462                 ret = av_timecode_init_from_string(&mxf->tc, rate, tcr->value, s);
1463             else
1464                 ret = av_timecode_init(&mxf->tc, rate, 0, 0, s);
1465             if (ret < 0)
1466                 return ret;
1467             if (s->oformat == &ff_mxf_d10_muxer) {
1468                 if (st->codec->bit_rate == 50000000)
1469                     if (mxf->time_base.den == 25) sc->index = 3;
1470                     else                          sc->index = 5;
1471                 else if (st->codec->bit_rate == 40000000)
1472                     if (mxf->time_base.den == 25) sc->index = 7;
1473                     else                          sc->index = 9;
1474                 else if (st->codec->bit_rate == 30000000)
1475                     if (mxf->time_base.den == 25) sc->index = 11;
1476                     else                          sc->index = 13;
1477                 else {
1478                     av_log(s, AV_LOG_ERROR, "error MXF D-10 only support 30/40/50 mbit/s\n");
1479                     return -1;
1480                 }
1481
1482                 mxf->edit_unit_byte_count = KAG_SIZE; // system element
1483                 mxf->edit_unit_byte_count += 16 + 4 + (uint64_t)st->codec->bit_rate *
1484                     mxf->time_base.num / (8*mxf->time_base.den);
1485                 mxf->edit_unit_byte_count += klv_fill_size(mxf->edit_unit_byte_count);
1486                 mxf->edit_unit_byte_count += 16 + 4 + 4 + samples_per_frame[0]*8*4;
1487                 mxf->edit_unit_byte_count += klv_fill_size(mxf->edit_unit_byte_count);
1488             }
1489         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1490             if (st->codec->sample_rate != 48000) {
1491                 av_log(s, AV_LOG_ERROR, "only 48khz is implemented\n");
1492                 return -1;
1493             }
1494             avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
1495             if (s->oformat == &ff_mxf_d10_muxer) {
1496                 if (st->index != 1) {
1497                     av_log(s, AV_LOG_ERROR, "MXF D-10 only support one audio track\n");
1498                     return -1;
1499                 }
1500                 if (st->codec->codec_id != CODEC_ID_PCM_S16LE &&
1501                     st->codec->codec_id != CODEC_ID_PCM_S24LE) {
1502                     av_log(s, AV_LOG_ERROR, "MXF D-10 only support 16 or 24 bits le audio\n");
1503                 }
1504                 sc->index = ((MXFStreamContext*)s->streams[0]->priv_data)->index + 1;
1505             } else
1506             mxf->slice_count = 1;
1507         }
1508
1509         if (!sc->index) {
1510             sc->index = mxf_get_essence_container_ul_index(st->codec->codec_id);
1511             if (sc->index == -1) {
1512                 av_log(s, AV_LOG_ERROR, "track %d: could not find essence container ul, "
1513                        "codec not currently supported in container\n", i);
1514                 return -1;
1515             }
1516         }
1517
1518         sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
1519
1520         memcpy(sc->track_essence_element_key, mxf_essence_container_uls[sc->index].element_ul, 15);
1521         sc->track_essence_element_key[15] = present[sc->index];
1522         PRINT_KEY(s, "track essence element key", sc->track_essence_element_key);
1523
1524         if (!present[sc->index])
1525             mxf->essence_container_count++;
1526         present[sc->index]++;
1527     }
1528
1529     if (s->oformat == &ff_mxf_d10_muxer) {
1530         mxf->essence_container_count = 1;
1531     }
1532
1533     if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT))
1534         mxf_gen_umid(s);
1535
1536     for (i = 0; i < s->nb_streams; i++) {
1537         MXFStreamContext *sc = s->streams[i]->priv_data;
1538         // update element count
1539         sc->track_essence_element_key[13] = present[sc->index];
1540         sc->order = AV_RB32(sc->track_essence_element_key+12);
1541     }
1542
1543     if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
1544         timestamp = ff_iso8601_to_unix_time(t->value);
1545     if (timestamp)
1546         mxf->timestamp = mxf_parse_timestamp(timestamp);
1547     mxf->duration = -1;
1548
1549     mxf->timecode_track = av_mallocz(sizeof(*mxf->timecode_track));
1550     if (!mxf->timecode_track)
1551         return AVERROR(ENOMEM);
1552     mxf->timecode_track->priv_data = av_mallocz(sizeof(MXFStreamContext));
1553     if (!mxf->timecode_track->priv_data)
1554         return AVERROR(ENOMEM);
1555     mxf->timecode_track->index = -1;
1556
1557     if (!samples_per_frame)
1558         samples_per_frame = PAL_samples_per_frame;
1559
1560     if (ff_audio_interleave_init(s, samples_per_frame, mxf->time_base) < 0)
1561         return -1;
1562
1563     return 0;
1564 }
1565
1566 static const uint8_t system_metadata_pack_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04,0x01,0x01,0x00 };
1567 static const uint8_t system_metadata_package_set_key[] = { 0x06,0x0E,0x2B,0x34,0x02,0x43,0x01,0x01,0x0D,0x01,0x03,0x01,0x04,0x01,0x02,0x01 };
1568
1569 static void mxf_write_system_item(AVFormatContext *s)
1570 {
1571     MXFContext *mxf = s->priv_data;
1572     AVIOContext *pb = s->pb;
1573     unsigned frame;
1574     uint32_t time_code;
1575
1576     frame = mxf->last_indexed_edit_unit + mxf->edit_units_count;
1577
1578     // write system metadata pack
1579     avio_write(pb, system_metadata_pack_key, 16);
1580     klv_encode_ber4_length(pb, 57);
1581     avio_w8(pb, 0x5c); // UL, user date/time stamp, picture and sound item present
1582     avio_w8(pb, 0x04); // content package rate
1583     avio_w8(pb, 0x00); // content package type
1584     avio_wb16(pb, 0x00); // channel handle
1585     avio_wb16(pb, mxf->tc.start + frame); // continuity count
1586     if (mxf->essence_container_count > 1)
1587         avio_write(pb, multiple_desc_ul, 16);
1588     else {
1589         MXFStreamContext *sc = s->streams[0]->priv_data;
1590         avio_write(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
1591     }
1592     avio_w8(pb, 0);
1593     avio_wb64(pb, 0);
1594     avio_wb64(pb, 0); // creation date/time stamp
1595
1596     avio_w8(pb, 0x81); // SMPTE 12M time code
1597     time_code = av_timecode_get_smpte_from_framenum(&mxf->tc, frame);
1598     avio_wb32(pb, time_code);
1599     avio_wb32(pb, 0); // binary group data
1600     avio_wb64(pb, 0);
1601
1602     // write system metadata package set
1603     avio_write(pb, system_metadata_package_set_key, 16);
1604     klv_encode_ber4_length(pb, 35);
1605     avio_w8(pb, 0x83); // UMID
1606     avio_wb16(pb, 0x20);
1607     mxf_write_umid(s, 1);
1608 }
1609
1610 static void mxf_write_d10_video_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt)
1611 {
1612     MXFContext *mxf = s->priv_data;
1613     AVIOContext *pb = s->pb;
1614     int packet_size = (uint64_t)st->codec->bit_rate*mxf->time_base.num /
1615         (8*mxf->time_base.den); // frame size
1616     int pad;
1617
1618     packet_size += 16 + 4;
1619     packet_size += klv_fill_size(packet_size);
1620
1621     klv_encode_ber4_length(pb, pkt->size);
1622     avio_write(pb, pkt->data, pkt->size);
1623
1624     // ensure CBR muxing by padding to correct video frame size
1625     pad = packet_size - pkt->size - 16 - 4;
1626     if (pad > 20) {
1627         avio_write(s->pb, klv_fill_key, 16);
1628         pad -= 16 + 4;
1629         klv_encode_ber4_length(s->pb, pad);
1630         for (; pad; pad--)
1631             avio_w8(s->pb, 0);
1632         assert(!(avio_tell(s->pb) & (KAG_SIZE-1)));
1633     } else {
1634         av_log(s, AV_LOG_WARNING, "cannot fill d-10 video packet\n");
1635         for (; pad > 0; pad--)
1636             avio_w8(s->pb, 0);
1637     }
1638 }
1639
1640 static void mxf_write_d10_audio_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt)
1641 {
1642     MXFContext *mxf = s->priv_data;
1643     AVIOContext *pb = s->pb;
1644     int frame_size = pkt->size / st->codec->block_align;
1645     uint8_t *samples = pkt->data;
1646     uint8_t *end = pkt->data + pkt->size;
1647     int i;
1648
1649     klv_encode_ber4_length(pb, 4 + frame_size*4*8);
1650
1651     avio_w8(pb, (frame_size == 1920 ? 0 : (mxf->edit_units_count-1) % 5 + 1));
1652     avio_wl16(pb, frame_size);
1653     avio_w8(pb, (1<<st->codec->channels)-1);
1654
1655     while (samples < end) {
1656         for (i = 0; i < st->codec->channels; i++) {
1657             uint32_t sample;
1658             if (st->codec->codec_id == CODEC_ID_PCM_S24LE) {
1659                 sample = AV_RL24(samples)<< 4;
1660                 samples += 3;
1661             } else {
1662                 sample = AV_RL16(samples)<<12;
1663                 samples += 2;
1664             }
1665             avio_wl32(pb, sample | i);
1666         }
1667         for (; i < 8; i++)
1668             avio_wl32(pb, i);
1669     }
1670 }
1671
1672 static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
1673 {
1674     MXFContext *mxf = s->priv_data;
1675     AVIOContext *pb = s->pb;
1676     AVStream *st = s->streams[pkt->stream_index];
1677     MXFStreamContext *sc = st->priv_data;
1678     MXFIndexEntry ie = {0};
1679
1680     if (!mxf->edit_unit_byte_count && !(mxf->edit_units_count % EDIT_UNITS_PER_BODY)) {
1681         mxf->index_entries = av_realloc(mxf->index_entries,
1682             (mxf->edit_units_count + EDIT_UNITS_PER_BODY)*sizeof(*mxf->index_entries));
1683         if (!mxf->index_entries) {
1684             av_log(s, AV_LOG_ERROR, "could not allocate index entries\n");
1685             return -1;
1686         }
1687     }
1688
1689     if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO) {
1690         if (!mxf_parse_mpeg2_frame(s, st, pkt, &ie)) {
1691             av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
1692             return -1;
1693         }
1694     }
1695
1696     if (!mxf->header_written) {
1697         if (mxf->edit_unit_byte_count) {
1698             mxf_write_partition(s, 1, 2, header_open_partition_key, 1);
1699             mxf_write_klv_fill(s);
1700             mxf_write_index_table_segment(s);
1701         } else {
1702             mxf_write_partition(s, 0, 0, header_open_partition_key, 1);
1703         }
1704         mxf->header_written = 1;
1705     }
1706
1707     if (st->index == 0) {
1708         if (!mxf->edit_unit_byte_count &&
1709             (!mxf->edit_units_count || mxf->edit_units_count > EDIT_UNITS_PER_BODY) &&
1710             !(ie.flags & 0x33)) { // I frame, Gop start
1711             mxf_write_klv_fill(s);
1712             mxf_write_partition(s, 1, 2, body_partition_key, 0);
1713
1714             mxf_write_klv_fill(s);
1715             mxf_write_index_table_segment(s);
1716         }
1717
1718         mxf_write_klv_fill(s);
1719         mxf_write_system_item(s);
1720
1721         if (!mxf->edit_unit_byte_count) {
1722             mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;
1723             mxf->index_entries[mxf->edit_units_count].flags = ie.flags;
1724             mxf->index_entries[mxf->edit_units_count].temporal_ref = ie.temporal_ref;
1725             mxf->body_offset += KAG_SIZE; // size of system element
1726         }
1727         mxf->edit_units_count++;
1728     } else if (!mxf->edit_unit_byte_count && st->index == 1) {
1729         mxf->index_entries[mxf->edit_units_count-1].slice_offset =
1730             mxf->body_offset - mxf->index_entries[mxf->edit_units_count-1].offset;
1731     }
1732
1733     mxf_write_klv_fill(s);
1734     avio_write(pb, sc->track_essence_element_key, 16); // write key
1735     if (s->oformat == &ff_mxf_d10_muxer) {
1736         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1737             mxf_write_d10_video_packet(s, st, pkt);
1738         else
1739             mxf_write_d10_audio_packet(s, st, pkt);
1740     } else {
1741         klv_encode_ber4_length(pb, pkt->size); // write length
1742         avio_write(pb, pkt->data, pkt->size);
1743         mxf->body_offset += 16+4+pkt->size + klv_fill_size(16+4+pkt->size);
1744     }
1745
1746     avio_flush(pb);
1747
1748     return 0;
1749 }
1750
1751 static void mxf_write_random_index_pack(AVFormatContext *s)
1752 {
1753     MXFContext *mxf = s->priv_data;
1754     AVIOContext *pb = s->pb;
1755     uint64_t pos = avio_tell(pb);
1756     int i;
1757
1758     avio_write(pb, random_index_pack_key, 16);
1759     klv_encode_ber_length(pb, 28 + 12*mxf->body_partitions_count);
1760
1761     if (mxf->edit_unit_byte_count)
1762         avio_wb32(pb, 1); // BodySID of header partition
1763     else
1764         avio_wb32(pb, 0);
1765     avio_wb64(pb, 0); // offset of header partition
1766
1767     for (i = 0; i < mxf->body_partitions_count; i++) {
1768         avio_wb32(pb, 1); // BodySID
1769         avio_wb64(pb, mxf->body_partition_offset[i]);
1770     }
1771
1772     avio_wb32(pb, 0); // BodySID of footer partition
1773     avio_wb64(pb, mxf->footer_partition_offset);
1774
1775     avio_wb32(pb, avio_tell(pb) - pos + 4);
1776 }
1777
1778 static int mxf_write_footer(AVFormatContext *s)
1779 {
1780     MXFContext *mxf = s->priv_data;
1781     AVIOContext *pb = s->pb;
1782
1783     mxf->duration = mxf->last_indexed_edit_unit + mxf->edit_units_count;
1784
1785     mxf_write_klv_fill(s);
1786     mxf->footer_partition_offset = avio_tell(pb);
1787     if (mxf->edit_unit_byte_count) { // no need to repeat index
1788         mxf_write_partition(s, 0, 0, footer_partition_key, 0);
1789     } else {
1790         mxf_write_partition(s, 0, 2, footer_partition_key, 0);
1791
1792         mxf_write_klv_fill(s);
1793         mxf_write_index_table_segment(s);
1794     }
1795
1796     mxf_write_klv_fill(s);
1797     mxf_write_random_index_pack(s);
1798
1799     if (s->pb->seekable) {
1800         avio_seek(pb, 0, SEEK_SET);
1801         if (mxf->edit_unit_byte_count) {
1802             mxf_write_partition(s, 1, 2, header_closed_partition_key, 1);
1803             mxf_write_klv_fill(s);
1804             mxf_write_index_table_segment(s);
1805         } else {
1806             mxf_write_partition(s, 0, 0, header_closed_partition_key, 1);
1807         }
1808     }
1809
1810     avio_flush(pb);
1811
1812     ff_audio_interleave_close(s);
1813
1814     av_freep(&mxf->index_entries);
1815     av_freep(&mxf->body_partition_offset);
1816     av_freep(&mxf->timecode_track->priv_data);
1817     av_freep(&mxf->timecode_track);
1818
1819     mxf_free(s);
1820
1821     return 0;
1822 }
1823
1824 static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1825 {
1826     int i, stream_count = 0;
1827
1828     for (i = 0; i < s->nb_streams; i++)
1829         stream_count += !!s->streams[i]->last_in_packet_buffer;
1830
1831     if (stream_count && (s->nb_streams == stream_count || flush)) {
1832         AVPacketList *pktl = s->packet_buffer;
1833         if (s->nb_streams != stream_count) {
1834             AVPacketList *last = NULL;
1835             // find last packet in edit unit
1836             while (pktl) {
1837                 if (!stream_count || pktl->pkt.stream_index == 0)
1838                     break;
1839                 last = pktl;
1840                 pktl = pktl->next;
1841                 stream_count--;
1842             }
1843             // purge packet queue
1844             while (pktl) {
1845                 AVPacketList *next = pktl->next;
1846
1847                 if(s->streams[pktl->pkt.stream_index]->last_in_packet_buffer == pktl)
1848                     s->streams[pktl->pkt.stream_index]->last_in_packet_buffer= NULL;
1849                 av_free_packet(&pktl->pkt);
1850                 av_freep(&pktl);
1851                 pktl = next;
1852             }
1853             if (last)
1854                 last->next = NULL;
1855             else {
1856                 s->packet_buffer = NULL;
1857                 s->packet_buffer_end= NULL;
1858                 goto out;
1859             }
1860             pktl = s->packet_buffer;
1861         }
1862
1863         *out = pktl->pkt;
1864         //av_log(s, AV_LOG_DEBUG, "out st:%d dts:%lld\n", (*out).stream_index, (*out).dts);
1865         s->packet_buffer = pktl->next;
1866         if(s->streams[pktl->pkt.stream_index]->last_in_packet_buffer == pktl)
1867             s->streams[pktl->pkt.stream_index]->last_in_packet_buffer= NULL;
1868         if(!s->packet_buffer)
1869             s->packet_buffer_end= NULL;
1870         av_freep(&pktl);
1871         return 1;
1872     } else {
1873     out:
1874         av_init_packet(out);
1875         return 0;
1876     }
1877 }
1878
1879 static int mxf_compare_timestamps(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
1880 {
1881     MXFStreamContext *sc  = s->streams[pkt ->stream_index]->priv_data;
1882     MXFStreamContext *sc2 = s->streams[next->stream_index]->priv_data;
1883
1884     return next->dts > pkt->dts ||
1885         (next->dts == pkt->dts && sc->order < sc2->order);
1886 }
1887
1888 static int mxf_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1889 {
1890     return ff_audio_rechunk_interleave(s, out, pkt, flush,
1891                                mxf_interleave_get_packet, mxf_compare_timestamps);
1892 }
1893
1894 AVOutputFormat ff_mxf_muxer = {
1895     .name              = "mxf",
1896     .long_name         = NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1897     .mime_type         = "application/mxf",
1898     .extensions        = "mxf",
1899     .priv_data_size    = sizeof(MXFContext),
1900     .audio_codec       = CODEC_ID_PCM_S16LE,
1901     .video_codec       = CODEC_ID_MPEG2VIDEO,
1902     .write_header      = mxf_write_header,
1903     .write_packet      = mxf_write_packet,
1904     .write_trailer     = mxf_write_footer,
1905     .flags             = AVFMT_NOTIMESTAMPS,
1906     .interleave_packet = mxf_interleave,
1907 };
1908
1909 AVOutputFormat ff_mxf_d10_muxer = {
1910     .name              = "mxf_d10",
1911     .long_name         = NULL_IF_CONFIG_SMALL("Material eXchange Format, D-10 Mapping"),
1912     .mime_type         = "application/mxf",
1913     .priv_data_size    = sizeof(MXFContext),
1914     .audio_codec       = CODEC_ID_PCM_S16LE,
1915     .video_codec       = CODEC_ID_MPEG2VIDEO,
1916     .write_header      = mxf_write_header,
1917     .write_packet      = mxf_write_packet,
1918     .write_trailer     = mxf_write_footer,
1919     .flags             = AVFMT_NOTIMESTAMPS,
1920     .interleave_packet = mxf_interleave,
1921 };