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