mxf: honor timecode drop flag in mxf muxer if set.
[ffmpeg.git] / libavformat / mxfenc.c
1 /*
2  * MXF muxer
3  * Copyright (c) 2008 GUCAS, Zhentan Feng <spyfeng at gmail dot com>
4  * Copyright (c) 2008 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /*
24  * References
25  * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
26  * SMPTE 377M MXF File Format Specifications
27  * SMPTE 379M MXF Generic Container
28  * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
29  * SMPTE RP210: SMPTE Metadata Dictionary
30  * SMPTE RP224: Registry of SMPTE Universal Labels
31  */
32
33 //#define DEBUG
34
35 #include <math.h>
36 #include <time.h>
37
38 #include "libavutil/opt.h"
39 #include "libavutil/random_seed.h"
40 #include "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;          ///< wether 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 };
1291
1292 static const UID *mxf_get_mpeg2_codec_ul(AVCodecContext *avctx)
1293 {
1294     int long_gop = avctx->gop_size > 1 || avctx->has_b_frames;
1295
1296     if (avctx->profile == 4) { // Main
1297         if (avctx->level == 8) // Main
1298             return &mxf_mpeg2_codec_uls[0+long_gop];
1299         else if (avctx->level == 4) // High
1300             return &mxf_mpeg2_codec_uls[4+long_gop];
1301     } else if (avctx->profile == 0) { // 422
1302         if (avctx->level == 5) // Main
1303             return &mxf_mpeg2_codec_uls[2+long_gop];
1304         else if (avctx->level == 2) // High
1305             return &mxf_mpeg2_codec_uls[6+long_gop];
1306     }
1307     return NULL;
1308 }
1309
1310 static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st,
1311                                  AVPacket *pkt, MXFIndexEntry *e)
1312 {
1313     MXFStreamContext *sc = st->priv_data;
1314     uint32_t c = -1;
1315     int i;
1316
1317     for(i = 0; i < pkt->size - 4; i++) {
1318         c = (c<<8) + pkt->data[i];
1319         if (c == 0x1b5) {
1320             if ((pkt->data[i+1] & 0xf0) == 0x10) { // seq ext
1321                 st->codec->profile = pkt->data[i+1] & 0x07;
1322                 st->codec->level   = pkt->data[i+2] >> 4;
1323             } else if (i + 5 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x80) { // pict coding ext
1324                 sc->interlaced = !(pkt->data[i+5] & 0x80); // progressive frame
1325                 break;
1326             }
1327         } else if (c == 0x1b8) { // gop
1328             if (pkt->data[i+4]>>6 & 0x01) { // closed
1329                 sc->closed_gop = 1;
1330                 if (e->flags & 0x40) // sequence header present
1331                     e->flags |= 0x80; // random access
1332             }
1333         } else if (c == 0x1b3) { // seq
1334             e->flags |= 0x40;
1335             switch ((pkt->data[i+4]>>4) & 0xf) {
1336             case 2:  sc->aspect_ratio = (AVRational){  4,  3}; break;
1337             case 3:  sc->aspect_ratio = (AVRational){ 16,  9}; break;
1338             case 4:  sc->aspect_ratio = (AVRational){221,100}; break;
1339             default:
1340                 av_reduce(&sc->aspect_ratio.num, &sc->aspect_ratio.den,
1341                           st->codec->width, st->codec->height, 1024*1024);
1342             }
1343         } else if (c == 0x100) { // pic
1344             int pict_type = (pkt->data[i+2]>>3) & 0x07;
1345             e->temporal_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
1346             if (pict_type == 2) { // P frame
1347                 e->flags |= 0x22;
1348                 sc->closed_gop = 0; // reset closed gop, don't matter anymore
1349             } else if (pict_type == 3) { // B frame
1350                 if (sc->closed_gop)
1351                     e->flags |= 0x13; // only backward prediction
1352                 else
1353                     e->flags |= 0x33;
1354                 sc->temporal_reordering = -1;
1355             } else if (!pict_type) {
1356                 av_log(s, AV_LOG_ERROR, "error parsing mpeg2 frame\n");
1357                 return 0;
1358             }
1359         }
1360     }
1361     if (s->oformat != &ff_mxf_d10_muxer)
1362         sc->codec_ul = mxf_get_mpeg2_codec_ul(st->codec);
1363     return !!sc->codec_ul;
1364 }
1365
1366 static uint64_t mxf_parse_timestamp(time_t timestamp)
1367 {
1368     struct tm *time = gmtime(&timestamp);
1369     if (!time)
1370         return 0;
1371     return (uint64_t)(time->tm_year+1900) << 48 |
1372            (uint64_t)(time->tm_mon+1)     << 40 |
1373            (uint64_t) time->tm_mday       << 32 |
1374                       time->tm_hour       << 24 |
1375                       time->tm_min        << 16 |
1376                       time->tm_sec        << 8;
1377 }
1378
1379 static void mxf_gen_umid(AVFormatContext *s)
1380 {
1381     MXFContext *mxf = s->priv_data;
1382     uint32_t seed = av_get_random_seed();
1383     uint64_t umid = seed + 0x5294713400000000LL;
1384
1385     AV_WB64(mxf->umid  , umid);
1386     AV_WB64(mxf->umid+8, umid>>8);
1387
1388     mxf->instance_number = seed;
1389 }
1390
1391 static int mxf_write_header(AVFormatContext *s)
1392 {
1393     MXFContext *mxf = s->priv_data;
1394     int i;
1395     uint8_t present[FF_ARRAY_ELEMS(mxf_essence_container_uls)] = {0};
1396     const int *samples_per_frame = NULL;
1397     AVDictionaryEntry *t;
1398     int64_t timestamp = 0;
1399
1400     if (!s->nb_streams)
1401         return -1;
1402
1403     for (i = 0; i < s->nb_streams; i++) {
1404         AVStream *st = s->streams[i];
1405         MXFStreamContext *sc = av_mallocz(sizeof(*sc));
1406         if (!sc)
1407             return AVERROR(ENOMEM);
1408         st->priv_data = sc;
1409
1410         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1411             if (i != 0) {
1412                 av_log(s, AV_LOG_ERROR, "video stream must be first track\n");
1413                 return -1;
1414             }
1415             if (fabs(av_q2d(st->codec->time_base) - 1/25.0) < 0.0001) {
1416                 samples_per_frame = PAL_samples_per_frame;
1417                 mxf->time_base = (AVRational){ 1, 25 };
1418                 mxf->timecode_base = 25;
1419             } else if (fabs(av_q2d(st->codec->time_base) - 1001/30000.0) < 0.0001) {
1420                 samples_per_frame = NTSC_samples_per_frame;
1421                 mxf->time_base = (AVRational){ 1001, 30000 };
1422                 mxf->timecode_base = 30;
1423             } else {
1424                 av_log(s, AV_LOG_ERROR, "unsupported video frame rate\n");
1425                 return -1;
1426             }
1427             av_set_pts_info(st, 64, mxf->time_base.num, mxf->time_base.den);
1428             if (mxf->tc.str) {
1429                 mxf->tc.rate.num = mxf->time_base.den;
1430                 mxf->tc.rate.den = mxf->time_base.num;
1431                 if (ff_init_smtpe_timecode(s, &mxf->tc) < 0)
1432                     return -1;
1433             }
1434             if (s->oformat == &ff_mxf_d10_muxer) {
1435                 if (st->codec->bit_rate == 50000000)
1436                     if (mxf->time_base.den == 25) sc->index = 3;
1437                     else                          sc->index = 5;
1438                 else if (st->codec->bit_rate == 40000000)
1439                     if (mxf->time_base.den == 25) sc->index = 7;
1440                     else                          sc->index = 9;
1441                 else if (st->codec->bit_rate == 30000000)
1442                     if (mxf->time_base.den == 25) sc->index = 11;
1443                     else                          sc->index = 13;
1444                 else {
1445                     av_log(s, AV_LOG_ERROR, "error MXF D-10 only support 30/40/50 mbit/s\n");
1446                     return -1;
1447                 }
1448
1449                 mxf->edit_unit_byte_count = KAG_SIZE; // system element
1450                 mxf->edit_unit_byte_count += 16 + 4 + (uint64_t)st->codec->bit_rate *
1451                     mxf->time_base.num / (8*mxf->time_base.den);
1452                 mxf->edit_unit_byte_count += klv_fill_size(mxf->edit_unit_byte_count);
1453                 mxf->edit_unit_byte_count += 16 + 4 + 4 + samples_per_frame[0]*8*4;
1454                 mxf->edit_unit_byte_count += klv_fill_size(mxf->edit_unit_byte_count);
1455             }
1456         } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1457             if (st->codec->sample_rate != 48000) {
1458                 av_log(s, AV_LOG_ERROR, "only 48khz is implemented\n");
1459                 return -1;
1460             }
1461             av_set_pts_info(st, 64, 1, st->codec->sample_rate);
1462             if (s->oformat == &ff_mxf_d10_muxer) {
1463                 if (st->index != 1) {
1464                     av_log(s, AV_LOG_ERROR, "MXF D-10 only support one audio track\n");
1465                     return -1;
1466                 }
1467                 if (st->codec->codec_id != CODEC_ID_PCM_S16LE &&
1468                     st->codec->codec_id != CODEC_ID_PCM_S24LE) {
1469                     av_log(s, AV_LOG_ERROR, "MXF D-10 only support 16 or 24 bits le audio\n");
1470                 }
1471                 sc->index = ((MXFStreamContext*)s->streams[0]->priv_data)->index + 1;
1472             } else
1473             mxf->slice_count = 1;
1474         }
1475
1476         if (!sc->index) {
1477             sc->index = mxf_get_essence_container_ul_index(st->codec->codec_id);
1478             if (sc->index == -1) {
1479                 av_log(s, AV_LOG_ERROR, "track %d: could not find essence container ul, "
1480                        "codec not currently supported in container\n", i);
1481                 return -1;
1482             }
1483         }
1484
1485         sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
1486
1487         memcpy(sc->track_essence_element_key, mxf_essence_container_uls[sc->index].element_ul, 15);
1488         sc->track_essence_element_key[15] = present[sc->index];
1489         PRINT_KEY(s, "track essence element key", sc->track_essence_element_key);
1490
1491         if (!present[sc->index])
1492             mxf->essence_container_count++;
1493         present[sc->index]++;
1494     }
1495
1496     if (s->oformat == &ff_mxf_d10_muxer) {
1497         mxf->essence_container_count = 1;
1498     }
1499
1500     if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT))
1501         mxf_gen_umid(s);
1502
1503     for (i = 0; i < s->nb_streams; i++) {
1504         MXFStreamContext *sc = s->streams[i]->priv_data;
1505         // update element count
1506         sc->track_essence_element_key[13] = present[sc->index];
1507         sc->order = AV_RB32(sc->track_essence_element_key+12);
1508     }
1509
1510 #if FF_API_TIMESTAMP
1511     if (s->timestamp)
1512         timestamp = s->timestamp;
1513     else
1514 #endif
1515     if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
1516         timestamp = ff_iso8601_to_unix_time(t->value);
1517     if (timestamp)
1518         mxf->timestamp = mxf_parse_timestamp(timestamp);
1519     mxf->duration = -1;
1520
1521     mxf->timecode_track = av_mallocz(sizeof(*mxf->timecode_track));
1522     if (!mxf->timecode_track)
1523         return AVERROR(ENOMEM);
1524     mxf->timecode_track->priv_data = av_mallocz(sizeof(MXFStreamContext));
1525     if (!mxf->timecode_track->priv_data)
1526         return AVERROR(ENOMEM);
1527     mxf->timecode_track->index = -1;
1528
1529     if (!samples_per_frame)
1530         samples_per_frame = PAL_samples_per_frame;
1531
1532     if (ff_audio_interleave_init(s, samples_per_frame, mxf->time_base) < 0)
1533         return -1;
1534
1535     return 0;
1536 }
1537
1538 static const uint8_t system_metadata_pack_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04,0x01,0x01,0x00 };
1539 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 };
1540
1541 static void mxf_write_system_item(AVFormatContext *s)
1542 {
1543     MXFContext *mxf = s->priv_data;
1544     AVIOContext *pb = s->pb;
1545     unsigned frame;
1546     uint32_t time_code;
1547
1548     frame = mxf->tc.start + mxf->last_indexed_edit_unit + mxf->edit_units_count;
1549
1550     // write system metadata pack
1551     avio_write(pb, system_metadata_pack_key, 16);
1552     klv_encode_ber4_length(pb, 57);
1553     avio_w8(pb, 0x5c); // UL, user date/time stamp, picture and sound item present
1554     avio_w8(pb, 0x04); // content package rate
1555     avio_w8(pb, 0x00); // content package type
1556     avio_wb16(pb, 0x00); // channel handle
1557     avio_wb16(pb, frame); // continuity count
1558     if (mxf->essence_container_count > 1)
1559         avio_write(pb, multiple_desc_ul, 16);
1560     else {
1561         MXFStreamContext *sc = s->streams[0]->priv_data;
1562         avio_write(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
1563     }
1564     avio_w8(pb, 0);
1565     avio_wb64(pb, 0);
1566     avio_wb64(pb, 0); // creation date/time stamp
1567
1568     avio_w8(pb, 0x81); // SMPTE 12M time code
1569     time_code = frame;
1570     if (mxf->tc.drop)
1571         time_code = ff_framenum_to_drop_timecode(time_code);
1572     time_code = ff_framenum_to_smtpe_timecode(time_code, mxf->timecode_base,
1573                                               mxf->tc.drop);
1574     avio_wb32(pb, time_code);
1575     avio_wb32(pb, 0); // binary group data
1576     avio_wb64(pb, 0);
1577
1578     // write system metadata package set
1579     avio_write(pb, system_metadata_package_set_key, 16);
1580     klv_encode_ber4_length(pb, 35);
1581     avio_w8(pb, 0x83); // UMID
1582     avio_wb16(pb, 0x20);
1583     mxf_write_umid(s, 1);
1584 }
1585
1586 static void mxf_write_d10_video_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt)
1587 {
1588     MXFContext *mxf = s->priv_data;
1589     AVIOContext *pb = s->pb;
1590     int packet_size = (uint64_t)st->codec->bit_rate*mxf->time_base.num /
1591         (8*mxf->time_base.den); // frame size
1592     int pad;
1593
1594     packet_size += 16 + 4;
1595     packet_size += klv_fill_size(packet_size);
1596
1597     klv_encode_ber4_length(pb, pkt->size);
1598     avio_write(pb, pkt->data, pkt->size);
1599
1600     // ensure CBR muxing by padding to correct video frame size
1601     pad = packet_size - pkt->size - 16 - 4;
1602     if (pad > 20) {
1603         avio_write(s->pb, klv_fill_key, 16);
1604         pad -= 16 + 4;
1605         klv_encode_ber4_length(s->pb, pad);
1606         for (; pad; pad--)
1607             avio_w8(s->pb, 0);
1608         assert(!(avio_tell(s->pb) & (KAG_SIZE-1)));
1609     } else {
1610         av_log(s, AV_LOG_WARNING, "cannot fill d-10 video packet\n");
1611         for (; pad > 0; pad--)
1612             avio_w8(s->pb, 0);
1613     }
1614 }
1615
1616 static void mxf_write_d10_audio_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt)
1617 {
1618     MXFContext *mxf = s->priv_data;
1619     AVIOContext *pb = s->pb;
1620     int frame_size = pkt->size / st->codec->block_align;
1621     uint8_t *samples = pkt->data;
1622     uint8_t *end = pkt->data + pkt->size;
1623     int i;
1624
1625     klv_encode_ber4_length(pb, 4 + frame_size*4*8);
1626
1627     avio_w8(pb, (frame_size == 1920 ? 0 : (mxf->edit_units_count-1) % 5 + 1));
1628     avio_wl16(pb, frame_size);
1629     avio_w8(pb, (1<<st->codec->channels)-1);
1630
1631     while (samples < end) {
1632         for (i = 0; i < st->codec->channels; i++) {
1633             uint32_t sample;
1634             if (st->codec->codec_id == CODEC_ID_PCM_S24LE) {
1635                 sample = AV_RL24(samples)<< 4;
1636                 samples += 3;
1637             } else {
1638                 sample = AV_RL16(samples)<<12;
1639                 samples += 2;
1640             }
1641             avio_wl32(pb, sample | i);
1642         }
1643         for (; i < 8; i++)
1644             avio_wl32(pb, i);
1645     }
1646 }
1647
1648 static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
1649 {
1650     MXFContext *mxf = s->priv_data;
1651     AVIOContext *pb = s->pb;
1652     AVStream *st = s->streams[pkt->stream_index];
1653     MXFStreamContext *sc = st->priv_data;
1654     MXFIndexEntry ie = {0};
1655
1656     if (!mxf->edit_unit_byte_count && !(mxf->edit_units_count % EDIT_UNITS_PER_BODY)) {
1657         mxf->index_entries = av_realloc(mxf->index_entries,
1658             (mxf->edit_units_count + EDIT_UNITS_PER_BODY)*sizeof(*mxf->index_entries));
1659         if (!mxf->index_entries) {
1660             av_log(s, AV_LOG_ERROR, "could not allocate index entries\n");
1661             return -1;
1662         }
1663     }
1664
1665     if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO) {
1666         if (!mxf_parse_mpeg2_frame(s, st, pkt, &ie)) {
1667             av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
1668             return -1;
1669         }
1670     }
1671
1672     if (!mxf->header_written) {
1673         if (mxf->edit_unit_byte_count) {
1674             mxf_write_partition(s, 1, 2, header_open_partition_key, 1);
1675             mxf_write_klv_fill(s);
1676             mxf_write_index_table_segment(s);
1677         } else {
1678             mxf_write_partition(s, 0, 0, header_open_partition_key, 1);
1679         }
1680         mxf->header_written = 1;
1681     }
1682
1683     if (st->index == 0) {
1684         if (!mxf->edit_unit_byte_count &&
1685             (!mxf->edit_units_count || mxf->edit_units_count > EDIT_UNITS_PER_BODY) &&
1686             !(ie.flags & 0x33)) { // I frame, Gop start
1687             mxf_write_klv_fill(s);
1688             mxf_write_partition(s, 1, 2, body_partition_key, 0);
1689
1690             mxf_write_klv_fill(s);
1691             mxf_write_index_table_segment(s);
1692         }
1693
1694         mxf_write_klv_fill(s);
1695         mxf_write_system_item(s);
1696
1697         if (!mxf->edit_unit_byte_count) {
1698             mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;
1699             mxf->index_entries[mxf->edit_units_count].flags = ie.flags;
1700             mxf->index_entries[mxf->edit_units_count].temporal_ref = ie.temporal_ref;
1701             mxf->body_offset += KAG_SIZE; // size of system element
1702         }
1703         mxf->edit_units_count++;
1704     } else if (!mxf->edit_unit_byte_count && st->index == 1) {
1705         mxf->index_entries[mxf->edit_units_count-1].slice_offset =
1706             mxf->body_offset - mxf->index_entries[mxf->edit_units_count-1].offset;
1707     }
1708
1709     mxf_write_klv_fill(s);
1710     avio_write(pb, sc->track_essence_element_key, 16); // write key
1711     if (s->oformat == &ff_mxf_d10_muxer) {
1712         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1713             mxf_write_d10_video_packet(s, st, pkt);
1714         else
1715             mxf_write_d10_audio_packet(s, st, pkt);
1716     } else {
1717         klv_encode_ber4_length(pb, pkt->size); // write length
1718         avio_write(pb, pkt->data, pkt->size);
1719         mxf->body_offset += 16+4+pkt->size + klv_fill_size(16+4+pkt->size);
1720     }
1721
1722     avio_flush(pb);
1723
1724     return 0;
1725 }
1726
1727 static void mxf_write_random_index_pack(AVFormatContext *s)
1728 {
1729     MXFContext *mxf = s->priv_data;
1730     AVIOContext *pb = s->pb;
1731     uint64_t pos = avio_tell(pb);
1732     int i;
1733
1734     avio_write(pb, random_index_pack_key, 16);
1735     klv_encode_ber_length(pb, 28 + 12*mxf->body_partitions_count);
1736
1737     if (mxf->edit_unit_byte_count)
1738         avio_wb32(pb, 1); // BodySID of header partition
1739     else
1740         avio_wb32(pb, 0);
1741     avio_wb64(pb, 0); // offset of header partition
1742
1743     for (i = 0; i < mxf->body_partitions_count; i++) {
1744         avio_wb32(pb, 1); // BodySID
1745         avio_wb64(pb, mxf->body_partition_offset[i]);
1746     }
1747
1748     avio_wb32(pb, 0); // BodySID of footer partition
1749     avio_wb64(pb, mxf->footer_partition_offset);
1750
1751     avio_wb32(pb, avio_tell(pb) - pos + 4);
1752 }
1753
1754 static int mxf_write_footer(AVFormatContext *s)
1755 {
1756     MXFContext *mxf = s->priv_data;
1757     AVIOContext *pb = s->pb;
1758
1759     mxf->duration = mxf->last_indexed_edit_unit + mxf->edit_units_count;
1760
1761     mxf_write_klv_fill(s);
1762     mxf->footer_partition_offset = avio_tell(pb);
1763     if (mxf->edit_unit_byte_count) { // no need to repeat index
1764         mxf_write_partition(s, 0, 0, footer_partition_key, 0);
1765     } else {
1766         mxf_write_partition(s, 0, 2, footer_partition_key, 0);
1767
1768         mxf_write_klv_fill(s);
1769         mxf_write_index_table_segment(s);
1770     }
1771
1772     mxf_write_klv_fill(s);
1773     mxf_write_random_index_pack(s);
1774
1775     if (s->pb->seekable) {
1776         avio_seek(pb, 0, SEEK_SET);
1777         if (mxf->edit_unit_byte_count) {
1778             mxf_write_partition(s, 1, 2, header_closed_partition_key, 1);
1779             mxf_write_klv_fill(s);
1780             mxf_write_index_table_segment(s);
1781         } else {
1782             mxf_write_partition(s, 0, 0, header_closed_partition_key, 1);
1783         }
1784     }
1785
1786     avio_flush(pb);
1787
1788     ff_audio_interleave_close(s);
1789
1790     av_freep(&mxf->index_entries);
1791     av_freep(&mxf->body_partition_offset);
1792     av_freep(&mxf->timecode_track->priv_data);
1793     av_freep(&mxf->timecode_track);
1794
1795     mxf_free(s);
1796
1797     return 0;
1798 }
1799
1800 static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1801 {
1802     int i, stream_count = 0;
1803
1804     for (i = 0; i < s->nb_streams; i++)
1805         stream_count += !!s->streams[i]->last_in_packet_buffer;
1806
1807     if (stream_count && (s->nb_streams == stream_count || flush)) {
1808         AVPacketList *pktl = s->packet_buffer;
1809         if (s->nb_streams != stream_count) {
1810             AVPacketList *last = NULL;
1811             // find last packet in edit unit
1812             while (pktl) {
1813                 if (!stream_count || pktl->pkt.stream_index == 0)
1814                     break;
1815                 last = pktl;
1816                 pktl = pktl->next;
1817                 stream_count--;
1818             }
1819             // purge packet queue
1820             while (pktl) {
1821                 AVPacketList *next = pktl->next;
1822
1823                 if(s->streams[pktl->pkt.stream_index]->last_in_packet_buffer == pktl)
1824                     s->streams[pktl->pkt.stream_index]->last_in_packet_buffer= NULL;
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                 s->packet_buffer_end= NULL;
1834                 goto out;
1835             }
1836             pktl = s->packet_buffer;
1837         }
1838
1839         *out = pktl->pkt;
1840         //av_log(s, AV_LOG_DEBUG, "out st:%d dts:%lld\n", (*out).stream_index, (*out).dts);
1841         s->packet_buffer = pktl->next;
1842         if(s->streams[pktl->pkt.stream_index]->last_in_packet_buffer == pktl)
1843             s->streams[pktl->pkt.stream_index]->last_in_packet_buffer= NULL;
1844         if(!s->packet_buffer)
1845             s->packet_buffer_end= NULL;
1846         av_freep(&pktl);
1847         return 1;
1848     } else {
1849     out:
1850         av_init_packet(out);
1851         return 0;
1852     }
1853 }
1854
1855 static int mxf_compare_timestamps(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
1856 {
1857     MXFStreamContext *sc  = s->streams[pkt ->stream_index]->priv_data;
1858     MXFStreamContext *sc2 = s->streams[next->stream_index]->priv_data;
1859
1860     return next->dts > pkt->dts ||
1861         (next->dts == pkt->dts && sc->order < sc2->order);
1862 }
1863
1864 static int mxf_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1865 {
1866     return ff_audio_rechunk_interleave(s, out, pkt, flush,
1867                                mxf_interleave_get_packet, mxf_compare_timestamps);
1868 }
1869
1870 static const AVClass class = {
1871     .class_name = "mxf",
1872     .item_name  = av_default_item_name,
1873     .version    = LIBAVUTIL_VERSION_INT,
1874     .option     = (const AVOption[]){
1875         {TIMECODE_OPT(MXFContext, AV_OPT_FLAG_ENCODING_PARAM)},
1876         {NULL}
1877     },
1878 };
1879
1880 AVOutputFormat ff_mxf_muxer = {
1881     .name              = "mxf",
1882     .long_name         = NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1883     .mime_type         = "application/mxf",
1884     .extensions        = "mxf",
1885     .priv_data_size    = sizeof(MXFContext),
1886     .audio_codec       = CODEC_ID_PCM_S16LE,
1887     .video_codec       = CODEC_ID_MPEG2VIDEO,
1888     .write_header      = mxf_write_header,
1889     .write_packet      = mxf_write_packet,
1890     .write_trailer     = mxf_write_footer,
1891     .flags             = AVFMT_NOTIMESTAMPS,
1892     .interleave_packet = mxf_interleave,
1893     .priv_class        = &class,
1894 };
1895
1896 AVOutputFormat ff_mxf_d10_muxer = {
1897     .name              = "mxf_d10",
1898     .long_name         = NULL_IF_CONFIG_SMALL("Material eXchange Format, D-10 Mapping"),
1899     .mime_type         = "application/mxf",
1900     .priv_data_size    = sizeof(MXFContext),
1901     .audio_codec       = CODEC_ID_PCM_S16LE,
1902     .video_codec       = CODEC_ID_MPEG2VIDEO,
1903     .write_header      = mxf_write_header,
1904     .write_packet      = mxf_write_packet,
1905     .write_trailer     = mxf_write_footer,
1906     .flags             = AVFMT_NOTIMESTAMPS,
1907     .interleave_packet = mxf_interleave,
1908     .priv_class        = &class,
1909 };