OSDN Git Service

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