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