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