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