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