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