]> git.sesse.net Git - ffmpeg/blob - libavformat/mxfenc.c
7a16bf9155b774aa300dec0fed9792354b7c144d
[ffmpeg] / libavformat / mxfenc.c
1 /*
2  * MXF muxer
3  * Copyright (c) 2008 GUCAS, Zhentan Feng <spyfeng at gmail dot com>
4  * Copyright (c) 2008 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /*
24  * signal_standard, color_siting, store_user_comments, sample rate and klv_fill_key version
25  * fixes sponsored by NOA GmbH
26  */
27
28 /*
29  * References
30  * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
31  * SMPTE 377M MXF File Format Specifications
32  * SMPTE 379M MXF Generic Container
33  * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
34  * SMPTE 422M Mapping JPEG 2000 Codestreams into the MXF Generic Container
35  * SMPTE RP210: SMPTE Metadata Dictionary
36  * SMPTE RP224: Registry of SMPTE Universal Labels
37  */
38
39 #include <inttypes.h>
40 #include <math.h>
41 #include <time.h>
42
43 #include "libavutil/opt.h"
44 #include "libavutil/random_seed.h"
45 #include "libavutil/timecode.h"
46 #include "libavutil/avassert.h"
47 #include "libavutil/mastering_display_metadata.h"
48 #include "libavutil/pixdesc.h"
49 #include "libavutil/time_internal.h"
50 #include "libavcodec/bytestream.h"
51 #include "libavcodec/dnxhddata.h"
52 #include "libavcodec/dv_profile.h"
53 #include "libavcodec/h264_ps.h"
54 #include "libavcodec/golomb.h"
55 #include "libavcodec/internal.h"
56 #include "libavcodec/packet_internal.h"
57 #include "avformat.h"
58 #include "avio_internal.h"
59 #include "internal.h"
60 #include "avc.h"
61 #include "mxf.h"
62 #include "config.h"
63
64 extern AVOutputFormat ff_mxf_d10_muxer;
65 extern AVOutputFormat ff_mxf_opatom_muxer;
66
67 #define EDIT_UNITS_PER_BODY 250
68 #define KAG_SIZE 512
69
70 typedef struct MXFIndexEntry {
71     uint64_t offset;
72     unsigned slice_offset; ///< offset of audio slice
73     uint16_t temporal_ref;
74     uint8_t flags;
75 } MXFIndexEntry;
76
77 typedef struct MXFStreamContext {
78     int64_t pkt_cnt;         ///< pkt counter for muxed packets
79     UID track_essence_element_key;
80     int index;               ///< index in mxf_essence_container_uls table
81     const UID *codec_ul;
82     const UID *container_ul;
83     int order;               ///< interleaving order if dts are equal
84     int interlaced;          ///< whether picture is interlaced
85     int field_dominance;     ///< tff=1, bff=2
86     int component_depth;
87     int color_siting;
88     int signal_standard;
89     int h_chroma_sub_sample;
90     int v_chroma_sub_sample;
91     int temporal_reordering;
92     AVRational aspect_ratio; ///< display aspect ratio
93     int closed_gop;          ///< gop is closed, used in mpeg-2 frame parsing
94     int video_bit_rate;
95     int slice_offset;
96     int frame_size;          ///< frame size in bytes
97     int seq_closed_gop;      ///< all gops in sequence are closed, used in mpeg-2 descriptor
98     int max_gop;             ///< maximum gop size, used by mpeg-2 descriptor
99     int b_picture_count;     ///< maximum number of consecutive b pictures, used in mpeg-2 descriptor
100     int low_delay;           ///< low delay, used in mpeg-2 descriptor
101     int avc_intra;
102 } MXFStreamContext;
103
104 typedef struct MXFContainerEssenceEntry {
105     UID container_ul;
106     UID element_ul;
107     UID codec_ul;
108     void (*write_desc)(AVFormatContext *, AVStream *);
109 } MXFContainerEssenceEntry;
110
111 typedef struct MXFPackage {
112     char *name;
113     enum MXFMetadataSetType type;
114     int instance;
115     struct MXFPackage *ref;
116 } MXFPackage;
117
118 enum ULIndex {
119     INDEX_MPEG2 = 0,
120     INDEX_AES3,
121     INDEX_WAV,
122     INDEX_D10_VIDEO,
123     INDEX_D10_AUDIO,
124     INDEX_DV,
125     INDEX_DNXHD,
126     INDEX_JPEG2000,
127     INDEX_H264,
128     INDEX_S436M,
129     INDEX_PRORES,
130 };
131
132 static const struct {
133     enum AVCodecID id;
134     enum ULIndex index;
135 } mxf_essence_mappings[] = {
136     { AV_CODEC_ID_MPEG2VIDEO, INDEX_MPEG2 },
137     { AV_CODEC_ID_PCM_S24LE,  INDEX_AES3 },
138     { AV_CODEC_ID_PCM_S16LE,  INDEX_AES3 },
139     { AV_CODEC_ID_DVVIDEO,    INDEX_DV },
140     { AV_CODEC_ID_DNXHD,      INDEX_DNXHD },
141     { AV_CODEC_ID_JPEG2000,   INDEX_JPEG2000 },
142     { AV_CODEC_ID_H264,       INDEX_H264 },
143     { AV_CODEC_ID_PRORES,     INDEX_PRORES },
144     { AV_CODEC_ID_NONE }
145 };
146
147 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st);
148 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st);
149 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st);
150 static void mxf_write_h264_desc(AVFormatContext *s, AVStream *st);
151 static void mxf_write_cdci_desc(AVFormatContext *s, AVStream *st);
152 static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st);
153 static void mxf_write_s436m_anc_desc(AVFormatContext *s, AVStream *st);
154
155 static const MXFContainerEssenceEntry mxf_essence_container_uls[] = {
156     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 },
157       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
158       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
159       mxf_write_mpegvideo_desc },
160     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x03,0x00 },
161       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x03,0x00 },
162       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
163       mxf_write_aes3_desc },
164     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 },
165       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x01,0x00 },
166       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
167       mxf_write_wav_desc },
168     // D-10 Video
169     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 },
170       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
171       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x01 },
172       mxf_write_cdci_desc },
173     // D-10 Audio
174     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 },
175       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
176       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
177       mxf_write_generic_sound_desc },
178     // DV
179     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x7F,0x01 },
180       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
181       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x00,0x00,0x00 },
182       mxf_write_cdci_desc },
183     // DNxHD
184     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x11,0x01,0x00 },
185       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
186       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x71,0x01,0x00,0x00 },
187       mxf_write_cdci_desc },
188     // JPEG2000
189     { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0c,0x01,0x00 },
190       { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01,0x15,0x01,0x08,0x00 },
191       { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 },
192       mxf_write_cdci_desc },
193     // H.264
194     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x0D,0x01,0x03,0x01,0x02,0x10,0x60,0x01 },
195       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
196       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
197       mxf_write_h264_desc },
198     // S436M ANC
199     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x0D,0x01,0x03,0x01,0x02,0x0e,0x00,0x00 },
200       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x17,0x01,0x02,0x00 },
201       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x01,0x5C,0x00 },
202       mxf_write_s436m_anc_desc },
203     // ProRes
204     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x0d,0x01,0x03,0x01,0x02,0x1c,0x01,0x00 },
205       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01,0x15,0x01,0x17,0x00 },
206       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x03,0x00 },
207       mxf_write_cdci_desc },
208     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
209       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
210       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
211       NULL },
212 };
213
214 static const UID mxf_d10_codec_uls[] = {
215     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x01 }, // D-10 625/50 PAL 50mb/s
216     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x02 }, // D-10 525/50 NTSC 50mb/s
217     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x03 }, // D-10 625/50 PAL 40mb/s
218     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x04 }, // D-10 525/50 NTSC 40mb/s
219     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x05 }, // D-10 625/50 PAL 30mb/s
220     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x06 }, // D-10 525/50 NTSC 30mb/s
221 };
222
223 static const UID mxf_d10_container_uls[] = {
224     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, // D-10 625/50 PAL 50mb/s
225     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x02,0x01 }, // D-10 525/50 NTSC 50mb/s
226     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x03,0x01 }, // D-10 625/50 PAL 40mb/s
227     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x04,0x01 }, // D-10 525/50 NTSC 40mb/s
228     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x05,0x01 }, // D-10 625/50 PAL 30mb/s
229     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x06,0x01 }, // D-10 525/50 NTSC 30mb/s
230 };
231
232 static const uint8_t uuid_base[]            = { 0xAD,0xAB,0x44,0x24,0x2f,0x25,0x4d,0xc7,0x92,0xff,0x29,0xbd };
233 static const uint8_t umid_ul[]              = { 0x06,0x0A,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x01,0x0D,0x00,0x13 };
234
235 /**
236  * complete key for operation pattern, partitions, and primer pack
237  */
238 static const uint8_t op1a_ul[]                     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x01,0x09,0x00 };
239 static const uint8_t opatom_ul[]                   = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x02,0x01,0x10,0x03,0x00,0x00 };
240 static const uint8_t footer_partition_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }; // ClosedComplete
241 static const uint8_t primer_pack_key[]             = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x05,0x01,0x00 };
242 static const uint8_t index_table_segment_key[]     = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 };
243 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
244 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
245 static const uint8_t klv_fill_key[]                = { 0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x10,0x01,0x00,0x00,0x00 };
246 static const uint8_t body_partition_key[]          = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }; // ClosedComplete
247
248 /**
249  * partial key for header metadata
250  */
251 static const uint8_t header_metadata_key[]  = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01 };
252 static const uint8_t multiple_desc_ul[]     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x0D,0x01,0x03,0x01,0x02,0x7F,0x01,0x00 };
253
254 /**
255  * SMPTE RP210 http://www.smpte-ra.org/mdd/index.html
256  *             https://smpte-ra.org/sites/default/files/Labels.xml
257  */
258 static const MXFLocalTagPair mxf_local_tag_batch[] = {
259     // preface set
260     { 0x3C0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x02,0x00,0x00,0x00,0x00}}, /* Instance UID */
261     { 0x3B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x04,0x00,0x00}}, /* Last Modified Date */
262     { 0x3B05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x01,0x05,0x00,0x00,0x00}}, /* Version */
263     { 0x3B07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x01,0x04,0x00,0x00,0x00}}, /* Object Model Version */
264     { 0x3B06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x04,0x00,0x00}}, /* Identifications reference */
265     { 0x3B03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x01,0x00,0x00}}, /* Content Storage reference */
266     { 0x3B09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x03,0x00,0x00,0x00,0x00}}, /* Operational Pattern UL */
267     { 0x3B0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x01,0x00,0x00}}, /* Essence Containers UL batch */
268     { 0x3B0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x02,0x00,0x00}}, /* DM Schemes UL batch */
269     // Identification
270     { 0x3C09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x01,0x00,0x00,0x00}}, /* This Generation UID */
271     { 0x3C01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x02,0x01,0x00,0x00}}, /* Company Name */
272     { 0x3C02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x03,0x01,0x00,0x00}}, /* Product Name */
273     { 0x3C03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x04,0x00,0x00,0x00}}, /* Product Version */
274     { 0x3C04, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x05,0x01,0x00,0x00}}, /* Version String */
275     { 0x3C05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x07,0x00,0x00,0x00}}, /* Product ID */
276     { 0x3C06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x03,0x00,0x00}}, /* Modification Date */
277     { 0x3C07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x0A,0x00,0x00,0x00}}, /* Toolkit Version */
278     { 0x3C08, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x06,0x01,0x00,0x00}}, /* Platform */
279     // Content Storage
280     { 0x1901, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x01,0x00,0x00}}, /* Package strong reference batch */
281     { 0x1902, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x02,0x00,0x00}}, /* Package strong reference batch */
282     // Essence Container Data
283     { 0x2701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x06,0x01,0x00,0x00,0x00}}, /* Linked Package UID */
284     { 0x3F07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x04,0x00,0x00,0x00,0x00}}, /* BodySID */
285     // Package
286     { 0x4401, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x10,0x00,0x00,0x00,0x00}}, /* Package UID */
287     { 0x4405, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x01,0x03,0x00,0x00}}, /* Package Creation Date */
288     { 0x4404, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x05,0x00,0x00}}, /* Package Modified Date */
289     { 0x4402, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x03,0x03,0x02,0x01,0x00,0x00,0x00}}, /* Package Name */
290     { 0x4403, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x05,0x00,0x00}}, /* Tracks Strong reference array */
291     { 0x4701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x03,0x00,0x00}}, /* Descriptor */
292     // Track
293     { 0x4801, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x07,0x01,0x01,0x00,0x00,0x00,0x00}}, /* Track ID */
294     { 0x4804, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x04,0x01,0x03,0x00,0x00,0x00,0x00}}, /* Track Number */
295     { 0x4B01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x30,0x04,0x05,0x00,0x00,0x00,0x00}}, /* Edit Rate */
296     { 0x4B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x03,0x00,0x00}}, /* Origin */
297     { 0x4803, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x04,0x00,0x00}}, /* Sequence reference */
298     // Sequence
299     { 0x0201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x07,0x01,0x00,0x00,0x00,0x00,0x00}}, /* Data Definition UL */
300     { 0x0202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x02,0x01,0x01,0x03,0x00,0x00}}, /* Duration */
301     { 0x1001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x09,0x00,0x00}}, /* Structural Components reference array */
302     // Source Clip
303     { 0x1201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x04,0x00,0x00}}, /* Start position */
304     { 0x1101, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x01,0x00,0x00,0x00}}, /* SourcePackageID */
305     { 0x1102, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x02,0x00,0x00,0x00}}, /* SourceTrackID */
306     // Timecode Component
307     { 0x1501, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x05,0x00,0x00}}, /* Start Time Code */
308     { 0x1502, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x04,0x01,0x01,0x02,0x06,0x00,0x00}}, /* Rounded Time Code Base */
309     { 0x1503, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x04,0x01,0x01,0x05,0x00,0x00,0x00}}, /* Drop Frame */
310     // File Descriptor
311     { 0x3F01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x04,0x06,0x0B,0x00,0x00}}, /* Sub Descriptors reference array */
312     { 0x3006, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x06,0x01,0x01,0x03,0x05,0x00,0x00,0x00}}, /* Linked Track ID */
313     { 0x3001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x00,0x00,0x00,0x00}}, /* SampleRate */
314     { 0x3002, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x02,0x00,0x00,0x00,0x00}}, /* ContainerDuration */
315     { 0x3004, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x01,0x02,0x00,0x00}}, /* Essence Container */
316     // Generic Picture Essence Descriptor
317     { 0x320C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Frame Layout */
318     { 0x320D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x03,0x02,0x05,0x00,0x00,0x00}}, /* Video Line Map */
319     { 0x3203, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x02,0x00,0x00,0x00}}, /* Stored Width */
320     { 0x3202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x01,0x00,0x00,0x00}}, /* Stored Height */
321     { 0x3216, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x03,0x02,0x08,0x00,0x00,0x00}}, /* Stored F2 Offset */
322     { 0x3205, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x08,0x00,0x00,0x00}}, /* Sampled Width */
323     { 0x3204, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x07,0x00,0x00,0x00}}, /* Sampled Height */
324     { 0x3206, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x09,0x00,0x00,0x00}}, /* Sampled X Offset */
325     { 0x3207, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0A,0x00,0x00,0x00}}, /* Sampled Y Offset */
326     { 0x3209, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0C,0x00,0x00,0x00}}, /* Display Width */
327     { 0x3208, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0B,0x00,0x00,0x00}}, /* Display Height */
328     { 0x320A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0D,0x00,0x00,0x00}}, /* Display X offset */
329     { 0x320B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0E,0x00,0x00,0x00}}, /* Presentation Y offset */
330     { 0x3217, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x03,0x02,0x07,0x00,0x00,0x00}}, /* Display F2 offset */
331     { 0x320E, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x01,0x01,0x01,0x00,0x00,0x00}}, /* Aspect Ratio */
332     { 0x3210, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x02,0x01,0x01,0x01,0x02,0x00}}, /* Transfer characteristic */
333     { 0x321A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x02,0x01,0x01,0x03,0x01,0x00}}, /* Coding Equations (color space) */
334     { 0x3219, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x09,0x04,0x01,0x02,0x01,0x01,0x06,0x01,0x00}}, /* Color Primaries */
335     { 0x3213, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x18,0x01,0x02,0x00,0x00,0x00,0x00}}, /* Image Start Offset */
336     { 0x3214, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x18,0x01,0x03,0x00,0x00,0x00,0x00}}, /* Image End Offset */
337     { 0x3201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x06,0x01,0x00,0x00,0x00,0x00}}, /* Picture Essence Coding */
338     { 0x3212, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x03,0x01,0x06,0x00,0x00,0x00}}, /* Field Dominance (Opt) */
339     { 0x3215, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x05,0x01,0x13,0x00,0x00,0x00,0x00}}, /* Signal Standard */
340     // CDCI Picture Essence Descriptor
341     { 0x3301, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x05,0x03,0x0A,0x00,0x00,0x00}}, /* Component Depth */
342     { 0x3302, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x05,0x00,0x00,0x00}}, /* Horizontal Subsampling */
343     { 0x3308, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x05,0x01,0x10,0x00,0x00,0x00}}, /* Vertical Subsampling */
344     { 0x3303, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x06,0x00,0x00,0x00}}, /* Color Siting */
345     { 0x3307, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x18,0x01,0x04,0x00,0x00,0x00,0x00}}, /* Padding Bits */
346     { 0x3304, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x03,0x03,0x00,0x00,0x00}}, /* Black Ref level */
347     { 0x3305, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x03,0x04,0x00,0x00,0x00}}, /* White Ref level */
348     { 0x3306, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x05,0x03,0x05,0x00,0x00,0x00}}, /* Color Range */
349     // Generic Sound Essence Descriptor
350     { 0x3D02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Locked/Unlocked */
351     { 0x3D03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x01,0x01,0x01,0x00,0x00}}, /* Audio sampling rate */
352     { 0x3D04, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x02,0x01,0x01,0x03,0x00,0x00,0x00}}, /* Audio Ref Level */
353     { 0x3D07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x01,0x01,0x04,0x00,0x00,0x00}}, /* ChannelCount */
354     { 0x3D01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x03,0x04,0x00,0x00,0x00}}, /* Quantization bits */
355     { 0x3D06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x02,0x04,0x02,0x00,0x00,0x00,0x00}}, /* Sound Essence Compression */
356     // Index Table Segment
357     { 0x3F0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x05,0x30,0x04,0x06,0x00,0x00,0x00,0x00}}, /* Index Edit Rate */
358     { 0x3F0C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x01,0x03,0x01,0x0A,0x00,0x00}}, /* Index Start Position */
359     { 0x3F0D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x02,0x01,0x01,0x02,0x00,0x00}}, /* Index Duration */
360     { 0x3F05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x06,0x02,0x01,0x00,0x00,0x00,0x00}}, /* Edit Unit Byte Count */
361     { 0x3F06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x05,0x00,0x00,0x00,0x00}}, /* IndexSID */
362     { 0x3F08, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x04,0x04,0x01,0x01,0x00,0x00,0x00}}, /* Slice Count */
363     { 0x3F09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x01,0x06,0x00,0x00,0x00}}, /* Delta Entry Array */
364     { 0x3F0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x02,0x05,0x00,0x00,0x00}}, /* Index Entry Array */
365     // MPEG video Descriptor
366     { 0x8000, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x0B,0x00,0x00}}, /* BitRate */
367     { 0x8003, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x05,0x00,0x00}}, /* LowDelay */
368     { 0x8004, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x06,0x00,0x00}}, /* ClosedGOP */
369     { 0x8006, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x08,0x00,0x00}}, /* MaxGOP */
370     { 0x8007, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x0A,0x00,0x00}}, /* ProfileAndLevel */
371     { 0x8008, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x09,0x00,0x00}}, /* BPictureCount */
372     // Wave Audio Essence Descriptor
373     { 0x3D09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x03,0x05,0x00,0x00,0x00}}, /* Average Bytes Per Second */
374     { 0x3D0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x02,0x01,0x00,0x00,0x00}}, /* Block Align */
375     // mxf_user_comments_local_tag
376     { 0x4406, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x02,0x01,0x02,0x0C,0x00,0x00,0x00}}, /* User Comments */
377     { 0x5001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x02,0x01,0x02,0x09,0x01,0x00,0x00}}, /* Name */
378     { 0x5003, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x02,0x01,0x02,0x0A,0x01,0x00,0x00}}, /* Value */
379     // mxf_avc_subdescriptor_local_tags
380     { 0x8100, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x09,0x06,0x01,0x01,0x04,0x06,0x10,0x00,0x00}}, /* SubDescriptors */
381     { 0x8200, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x0E,0x04,0x01,0x06,0x06,0x01,0x0E,0x00,0x00}}, /* AVC Decoding Delay */
382     { 0x8201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x0E,0x04,0x01,0x06,0x06,0x01,0x0A,0x00,0x00}}, /* AVC Profile */
383     { 0x8202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x0E,0x04,0x01,0x06,0x06,0x01,0x0D,0x00,0x00}}, /* AVC Level */
384     // ff_mxf_mastering_display_local_tags
385     { 0x8301, FF_MXF_MasteringDisplayPrimaries },
386     { 0x8302, FF_MXF_MasteringDisplayWhitePointChromaticity },
387     { 0x8303, FF_MXF_MasteringDisplayMaximumLuminance },
388     { 0x8304, FF_MXF_MasteringDisplayMinimumLuminance },
389 };
390
391 #define MXF_NUM_TAGS FF_ARRAY_ELEMS(mxf_local_tag_batch)
392
393 typedef struct MXFContext {
394     AVClass *av_class;
395     int64_t footer_partition_offset;
396     int essence_container_count;
397     AVRational time_base;
398     int header_written;
399     MXFIndexEntry *index_entries;
400     unsigned edit_units_count;
401     uint64_t timestamp;   ///< timestamp, as year(16),month(8),day(8),hour(8),minutes(8),msec/4(8)
402     uint8_t slice_count;  ///< index slice count minus 1 (1 if no audio, 0 otherwise)
403     int last_indexed_edit_unit;
404     uint64_t *body_partition_offset;
405     unsigned body_partitions_count;
406     int last_key_index;  ///< index of last key frame
407     uint64_t duration;
408     AVTimecode tc;       ///< timecode context
409     AVStream *timecode_track;
410     int timecode_base;       ///< rounded time code base (25 or 30)
411     int edit_unit_byte_count; ///< fixed edit unit byte count
412     int content_package_rate; ///< content package rate in system element, see SMPTE 326M
413     uint64_t body_offset;
414     uint32_t instance_number;
415     uint8_t umid[16];        ///< unique material identifier
416     int channel_count;
417     int signal_standard;
418     uint32_t tagged_value_count;
419     AVRational audio_edit_rate;
420     int store_user_comments;
421     int track_instance_count; // used to generate MXFTrack uuids
422     int cbr_index;           ///< use a constant bitrate index
423     uint8_t unused_tags[MXF_NUM_TAGS];  ///< local tags that we know will not be used
424 } MXFContext;
425
426 static void mxf_write_uuid(AVIOContext *pb, enum MXFMetadataSetType type, int value)
427 {
428     avio_write(pb, uuid_base, 12);
429     avio_wb16(pb, type);
430     avio_wb16(pb, value);
431 }
432
433 static void mxf_write_umid(AVFormatContext *s, int type)
434 {
435     MXFContext *mxf = s->priv_data;
436     avio_write(s->pb, umid_ul, 13);
437     avio_wb24(s->pb, mxf->instance_number);
438     avio_write(s->pb, mxf->umid, 15);
439     avio_w8(s->pb, type);
440 }
441
442 static void mxf_write_refs_count(AVIOContext *pb, int ref_count)
443 {
444     avio_wb32(pb, ref_count);
445     avio_wb32(pb, 16);
446 }
447
448 static int klv_ber_length(uint64_t len)
449 {
450     if (len < 128)
451         return 1;
452     else
453         return (av_log2(len) >> 3) + 2;
454 }
455
456 static int klv_encode_ber_length(AVIOContext *pb, uint64_t len)
457 {
458     // Determine the best BER size
459     int size = klv_ber_length(len);
460     if (size == 1) {
461         //short form
462         avio_w8(pb, len);
463         return 1;
464     }
465
466     size --;
467     // long form
468     avio_w8(pb, 0x80 + size);
469     while(size) {
470         size--;
471         avio_w8(pb, len >> 8 * size & 0xff);
472     }
473     return 0;
474 }
475
476 static void klv_encode_ber4_length(AVIOContext *pb, int len)
477 {
478     avio_w8(pb, 0x80 + 3);
479     avio_wb24(pb, len);
480 }
481
482 static void klv_encode_ber9_length(AVIOContext *pb, uint64_t len)
483 {
484     avio_w8(pb, 0x80 + 8);
485     avio_wb64(pb, len);
486 }
487
488 /*
489  * Get essence container ul index
490  */
491 static int mxf_get_essence_container_ul_index(enum AVCodecID id)
492 {
493     int i;
494     for (i = 0; mxf_essence_mappings[i].id; i++)
495         if (mxf_essence_mappings[i].id == id)
496             return mxf_essence_mappings[i].index;
497     return -1;
498 }
499
500 static const MXFLocalTagPair* mxf_lookup_local_tag(int tag)
501 {
502     for (int i = 0; i < MXF_NUM_TAGS; i++) {
503         if (mxf_local_tag_batch[i].local_tag == tag) {
504             return &mxf_local_tag_batch[i];
505         }
506     }
507
508     // this assert can only be hit during development
509     av_assert0(0 && "you forgot to add your new tag to mxf_local_tag_batch");
510 }
511
512 static void mxf_mark_tag_unused(MXFContext *mxf, int tag)
513 {
514     const MXFLocalTagPair *pair = mxf_lookup_local_tag(tag);
515     mxf->unused_tags[pair - mxf_local_tag_batch] = 1;
516 }
517
518 static void mxf_write_primer_pack(AVFormatContext *s)
519 {
520     MXFContext *mxf = s->priv_data;
521     AVIOContext *pb = s->pb;
522     int local_tag_number = MXF_NUM_TAGS, i;
523     int will_have_avc_tags = 0, will_have_mastering_tags = 0;
524
525     for (i = 0; i < s->nb_streams; i++) {
526         MXFStreamContext *sc = s->streams[i]->priv_data;
527         if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_H264 && !sc->avc_intra) {
528             will_have_avc_tags = 1;
529         }
530         if (av_stream_get_side_data(s->streams[i], AV_PKT_DATA_MASTERING_DISPLAY_METADATA, NULL)) {
531             will_have_mastering_tags = 1;
532         }
533     }
534
535     if (!mxf->store_user_comments) {
536         mxf_mark_tag_unused(mxf, 0x4406);
537         mxf_mark_tag_unused(mxf, 0x5001);
538         mxf_mark_tag_unused(mxf, 0x5003);
539     }
540
541     if (!will_have_avc_tags) {
542         mxf_mark_tag_unused(mxf, 0x8100);
543         mxf_mark_tag_unused(mxf, 0x8200);
544         mxf_mark_tag_unused(mxf, 0x8201);
545         mxf_mark_tag_unused(mxf, 0x8202);
546     }
547
548     if (!will_have_mastering_tags) {
549         mxf_mark_tag_unused(mxf, 0x8301);
550         mxf_mark_tag_unused(mxf, 0x8302);
551         mxf_mark_tag_unused(mxf, 0x8303);
552         mxf_mark_tag_unused(mxf, 0x8304);
553     }
554
555     for (i = 0; i < MXF_NUM_TAGS; i++) {
556         if (mxf->unused_tags[i]) {
557             local_tag_number--;
558         }
559     }
560
561     avio_write(pb, primer_pack_key, 16);
562     klv_encode_ber_length(pb, local_tag_number * 18 + 8);
563
564     avio_wb32(pb, local_tag_number); // local_tag num
565     avio_wb32(pb, 18); // item size, always 18 according to the specs
566
567     for (i = 0; i < MXF_NUM_TAGS; i++) {
568         if (mxf->unused_tags[i] == 0) {
569             avio_wb16(pb, mxf_local_tag_batch[i].local_tag);
570             avio_write(pb, mxf_local_tag_batch[i].uid, 16);
571         }
572     }
573 }
574
575 static void mxf_write_local_tag(AVFormatContext *s, int size, int tag)
576 {
577     MXFContext *mxf = s->priv_data;
578     AVIOContext *pb = s->pb;
579     const MXFLocalTagPair *pair = mxf_lookup_local_tag(tag);
580
581     // make sure the tag was not declared unnecessary upfront
582     av_assert0(mxf->unused_tags[pair - mxf_local_tag_batch] == 0);
583
584     avio_wb16(pb, tag);
585     avio_wb16(pb, size);
586 }
587
588 static void mxf_write_metadata_key(AVIOContext *pb, unsigned int value)
589 {
590     avio_write(pb, header_metadata_key, 13);
591     avio_wb24(pb, value);
592 }
593
594 static const MXFCodecUL *mxf_get_codec_ul_by_id(const MXFCodecUL *uls, int id)
595 {
596     while (uls->uid[0]) {
597         if (id == uls->id)
598             break;
599         uls++;
600     }
601     return uls;
602 }
603
604 //one EC -> one descriptor. N ECs -> MultipleDescriptor + N descriptors
605 #define DESCRIPTOR_COUNT(essence_container_count) \
606     (essence_container_count > 1 ? essence_container_count + 1 : essence_container_count)
607
608 static void mxf_write_essence_container_refs(AVFormatContext *s)
609 {
610     MXFContext *c = s->priv_data;
611     AVIOContext *pb = s->pb;
612     int i;
613
614     mxf_write_refs_count(pb, DESCRIPTOR_COUNT(c->essence_container_count));
615     av_log(s,AV_LOG_DEBUG, "essence container count:%d\n", c->essence_container_count);
616     for (i = 0; i < s->nb_streams; i++) {
617         MXFStreamContext *sc = s->streams[i]->priv_data;
618         // check first track of essence container type and only write it once
619         if (sc->track_essence_element_key[15] != 0)
620             continue;
621         avio_write(pb, *sc->container_ul, 16);
622         if (c->essence_container_count == 1)
623             break;
624     }
625
626     if (c->essence_container_count > 1)
627         avio_write(pb, multiple_desc_ul, 16);
628 }
629
630 static void mxf_write_preface(AVFormatContext *s)
631 {
632     MXFContext *mxf = s->priv_data;
633     AVIOContext *pb = s->pb;
634
635     mxf_write_metadata_key(pb, 0x012f00);
636     PRINT_KEY(s, "preface key", pb->buf_ptr - 16);
637     klv_encode_ber_length(pb, 138 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count));
638
639     // write preface set uid
640     mxf_write_local_tag(s, 16, 0x3C0A);
641     mxf_write_uuid(pb, Preface, 0);
642     PRINT_KEY(s, "preface uid", pb->buf_ptr - 16);
643
644     // last modified date
645     mxf_write_local_tag(s, 8, 0x3B02);
646     avio_wb64(pb, mxf->timestamp);
647
648     // write version
649     mxf_write_local_tag(s, 2, 0x3B05);
650     avio_wb16(pb, 259); // v1.3
651
652     // Object Model Version
653     mxf_write_local_tag(s, 4, 0x3B07);
654     avio_wb32(pb, 1);
655
656     // write identification_refs
657     mxf_write_local_tag(s, 16 + 8, 0x3B06);
658     mxf_write_refs_count(pb, 1);
659     mxf_write_uuid(pb, Identification, 0);
660
661     // write content_storage_refs
662     mxf_write_local_tag(s, 16, 0x3B03);
663     mxf_write_uuid(pb, ContentStorage, 0);
664
665     // operational pattern
666     mxf_write_local_tag(s, 16, 0x3B09);
667     if (s->oformat == &ff_mxf_opatom_muxer)
668         avio_write(pb, opatom_ul, 16);
669     else
670         avio_write(pb, op1a_ul, 16);
671
672     // write essence_container_refs
673     mxf_write_local_tag(s, 8 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count), 0x3B0A);
674     mxf_write_essence_container_refs(s);
675
676     // write dm_scheme_refs
677     mxf_write_local_tag(s, 8, 0x3B0B);
678     avio_wb64(pb, 0);
679 }
680
681 /*
682  * Returns the length of the UTF-16 string, in 16-bit characters, that would result
683  * from decoding the utf-8 string.
684  */
685 static uint64_t mxf_utf16len(const char *utf8_str)
686 {
687     const uint8_t *q = utf8_str;
688     uint64_t size = 0;
689     while (*q) {
690         uint32_t ch;
691         GET_UTF8(ch, *q++, goto invalid;)
692         if (ch < 0x10000)
693             size++;
694         else
695             size += 2;
696         continue;
697 invalid:
698         av_log(NULL, AV_LOG_ERROR, "Invalid UTF8 sequence in mxf_utf16len\n\n");
699     }
700     size += 1;
701     return size;
702 }
703
704 /*
705  * Returns the calculated length a local tag containing an utf-8 string as utf-16
706  */
707 static int mxf_utf16_local_tag_length(const char *utf8_str)
708 {
709     uint64_t size;
710
711     if (!utf8_str)
712         return 0;
713
714     size = mxf_utf16len(utf8_str);
715     if (size >= UINT16_MAX/2) {
716         av_log(NULL, AV_LOG_ERROR, "utf16 local tag size %"PRIx64" invalid (too large), ignoring\n", size);
717         return 0;
718     }
719
720     return 4 + size * 2;
721 }
722
723 /*
724  * Write a local tag containing an utf-8 string as utf-16
725  */
726 static void mxf_write_local_tag_utf16(AVFormatContext *s, int tag, const char *value)
727 {
728     AVIOContext *pb = s->pb;
729     uint64_t size = mxf_utf16len(value);
730
731     if (size >= UINT16_MAX/2) {
732         av_log(NULL, AV_LOG_ERROR, "utf16 local tag size %"PRIx64" invalid (too large), ignoring\n", size);
733         return;
734     }
735
736     mxf_write_local_tag(s, size*2, tag);
737     avio_put_str16be(pb, value);
738 }
739
740 static void store_version(AVFormatContext *s){
741     AVIOContext *pb = s->pb;
742
743     if (s->flags & AVFMT_FLAG_BITEXACT) {
744         avio_wb16(pb, 0); // major
745         avio_wb16(pb, 0); // minor
746         avio_wb16(pb, 0); // tertiary
747     } else {
748         avio_wb16(pb, LIBAVFORMAT_VERSION_MAJOR); // major
749         avio_wb16(pb, LIBAVFORMAT_VERSION_MINOR); // minor
750         avio_wb16(pb, LIBAVFORMAT_VERSION_MICRO); // tertiary
751     }
752     avio_wb16(pb, 0); // patch
753     avio_wb16(pb, 0); // release
754 }
755
756 #define PLATFORM_IDENT "Lavf " AV_STRINGIFY((OS_NAME))
757 static void mxf_write_identification(AVFormatContext *s)
758 {
759     MXFContext *mxf = s->priv_data;
760     AVIOContext *pb = s->pb;
761     AVDictionaryEntry *com_entry = av_dict_get(s->metadata, "company_name", NULL, 0);
762     AVDictionaryEntry *product_entry = av_dict_get(s->metadata, "product_name", NULL, 0);
763     AVDictionaryEntry *version_entry = av_dict_get(s->metadata, "product_version", NULL, 0);
764     const char *company = com_entry ? com_entry->value : "FFmpeg";
765     const char *product = product_entry ? product_entry->value : s->oformat != &ff_mxf_opatom_muxer ? "OP1a Muxer" : "OPAtom Muxer";
766     const char *platform = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : PLATFORM_IDENT;
767     const char *version = version_entry ? version_entry->value :
768                               s->flags & AVFMT_FLAG_BITEXACT ? "0.0.0" :
769                                   AV_STRINGIFY(LIBAVFORMAT_VERSION);
770     int length;
771
772     mxf_write_metadata_key(pb, 0x013000);
773     PRINT_KEY(s, "identification key", pb->buf_ptr - 16);
774
775     length = 100 +mxf_utf16_local_tag_length(company) +
776                   mxf_utf16_local_tag_length(product) +
777                   mxf_utf16_local_tag_length(platform) +
778                   mxf_utf16_local_tag_length(version);
779     klv_encode_ber_length(pb, length);
780
781     // write uid
782     mxf_write_local_tag(s, 16, 0x3C0A);
783     mxf_write_uuid(pb, Identification, 0);
784     PRINT_KEY(s, "identification uid", pb->buf_ptr - 16);
785
786     // write generation uid
787     mxf_write_local_tag(s, 16, 0x3C09);
788     mxf_write_uuid(pb, Identification, 1);
789     mxf_write_local_tag_utf16(s, 0x3C01, company); // Company Name
790     mxf_write_local_tag_utf16(s, 0x3C02, product); // Product Name
791
792     mxf_write_local_tag(s, 10, 0x3C03); // Product Version
793     store_version(s);
794
795     mxf_write_local_tag_utf16(s, 0x3C04, version); // Version String
796     mxf_write_local_tag_utf16(s, 0x3C08, platform); // Platform
797
798     // write product uid
799     mxf_write_local_tag(s, 16, 0x3C05);
800     mxf_write_uuid(pb, Identification, 2);
801
802     // modification date
803     mxf_write_local_tag(s, 8, 0x3C06);
804     avio_wb64(pb, mxf->timestamp);
805
806     mxf_write_local_tag(s, 10, 0x3C07); // Toolkit Version
807     store_version(s);
808 }
809
810 static void mxf_write_content_storage(AVFormatContext *s, MXFPackage *packages, int package_count)
811 {
812     AVIOContext *pb = s->pb;
813     int i;
814
815     mxf_write_metadata_key(pb, 0x011800);
816     PRINT_KEY(s, "content storage key", pb->buf_ptr - 16);
817     klv_encode_ber_length(pb, 60 + (16 * package_count));
818
819     // write uid
820     mxf_write_local_tag(s, 16, 0x3C0A);
821     mxf_write_uuid(pb, ContentStorage, 0);
822     PRINT_KEY(s, "content storage uid", pb->buf_ptr - 16);
823
824     // write package reference
825     mxf_write_local_tag(s, 16 * package_count + 8, 0x1901);
826     mxf_write_refs_count(pb, package_count);
827     for (i = 0; i < package_count; i++) {
828         mxf_write_uuid(pb, packages[i].type, packages[i].instance);
829     }
830
831     // write essence container data
832     mxf_write_local_tag(s, 8 + 16, 0x1902);
833     mxf_write_refs_count(pb, 1);
834     mxf_write_uuid(pb, EssenceContainerData, 0);
835 }
836
837 static void mxf_write_track(AVFormatContext *s, AVStream *st, MXFPackage *package)
838 {
839     MXFContext *mxf = s->priv_data;
840     AVIOContext *pb = s->pb;
841     MXFStreamContext *sc = st->priv_data;
842
843     mxf_write_metadata_key(pb, 0x013b00);
844     PRINT_KEY(s, "track key", pb->buf_ptr - 16);
845     klv_encode_ber_length(pb, 80);
846
847     // write track uid
848     mxf_write_local_tag(s, 16, 0x3C0A);
849     mxf_write_uuid(pb, Track, mxf->track_instance_count);
850     PRINT_KEY(s, "track uid", pb->buf_ptr - 16);
851
852     // write track id
853     mxf_write_local_tag(s, 4, 0x4801);
854     avio_wb32(pb, st->index+2);
855
856     // write track number
857     mxf_write_local_tag(s, 4, 0x4804);
858     if (package->type == MaterialPackage)
859         avio_wb32(pb, 0); // track number of material package is 0
860     else
861         avio_write(pb, sc->track_essence_element_key + 12, 4);
862
863     // write edit rate
864     mxf_write_local_tag(s, 8, 0x4B01);
865
866     if (st == mxf->timecode_track && s->oformat == &ff_mxf_opatom_muxer) {
867         avio_wb32(pb, mxf->tc.rate.num);
868         avio_wb32(pb, mxf->tc.rate.den);
869     } else {
870         avio_wb32(pb, mxf->time_base.den);
871         avio_wb32(pb, mxf->time_base.num);
872     }
873
874     // write origin
875     mxf_write_local_tag(s, 8, 0x4B02);
876     avio_wb64(pb, 0);
877
878     // write sequence refs
879     mxf_write_local_tag(s, 16, 0x4803);
880     mxf_write_uuid(pb, Sequence, mxf->track_instance_count);
881 }
882
883 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 };
884
885 static void mxf_write_common_fields(AVFormatContext *s, AVStream *st)
886 {
887     MXFContext *mxf = s->priv_data;
888     AVIOContext *pb = s->pb;
889
890     // find data define uls
891     mxf_write_local_tag(s, 16, 0x0201);
892     if (st == mxf->timecode_track)
893         avio_write(pb, smpte_12m_timecode_track_data_ul, 16);
894     else {
895         const MXFCodecUL *data_def_ul = mxf_get_codec_ul_by_id(ff_mxf_data_definition_uls, st->codecpar->codec_type);
896         avio_write(pb, data_def_ul->uid, 16);
897     }
898
899     // write duration
900     mxf_write_local_tag(s, 8, 0x0202);
901
902     if (st != mxf->timecode_track && s->oformat == &ff_mxf_opatom_muxer && st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
903         avio_wb64(pb, mxf->body_offset / mxf->edit_unit_byte_count);
904     } else {
905         avio_wb64(pb, mxf->duration);
906     }
907 }
908
909 static void mxf_write_sequence(AVFormatContext *s, AVStream *st, MXFPackage *package)
910 {
911     MXFContext *mxf = s->priv_data;
912     AVIOContext *pb = s->pb;
913     enum MXFMetadataSetType component;
914
915     mxf_write_metadata_key(pb, 0x010f00);
916     PRINT_KEY(s, "sequence key", pb->buf_ptr - 16);
917     klv_encode_ber_length(pb, 80);
918
919     mxf_write_local_tag(s, 16, 0x3C0A);
920     mxf_write_uuid(pb, Sequence, mxf->track_instance_count);
921
922     PRINT_KEY(s, "sequence uid", pb->buf_ptr - 16);
923     mxf_write_common_fields(s, st);
924
925     // write structural component
926     mxf_write_local_tag(s, 16 + 8, 0x1001);
927     mxf_write_refs_count(pb, 1);
928     if (st == mxf->timecode_track)
929         component = TimecodeComponent;
930     else
931         component = SourceClip;
932
933     mxf_write_uuid(pb, component, mxf->track_instance_count);
934 }
935
936 static void mxf_write_timecode_component(AVFormatContext *s, AVStream *st, MXFPackage *package)
937 {
938     MXFContext *mxf = s->priv_data;
939     AVIOContext *pb = s->pb;
940
941     mxf_write_metadata_key(pb, 0x011400);
942     klv_encode_ber_length(pb, 75);
943
944     // UID
945     mxf_write_local_tag(s, 16, 0x3C0A);
946     mxf_write_uuid(pb, TimecodeComponent, mxf->track_instance_count);
947
948     mxf_write_common_fields(s, st);
949
950     // Start Time Code
951     mxf_write_local_tag(s, 8, 0x1501);
952     avio_wb64(pb, mxf->tc.start);
953
954     // Rounded Time Code Base
955     mxf_write_local_tag(s, 2, 0x1502);
956     avio_wb16(pb, mxf->timecode_base);
957
958     // Drop Frame
959     mxf_write_local_tag(s, 1, 0x1503);
960     avio_w8(pb, !!(mxf->tc.flags & AV_TIMECODE_FLAG_DROPFRAME));
961 }
962
963 static void mxf_write_structural_component(AVFormatContext *s, AVStream *st, MXFPackage *package)
964 {
965     MXFContext *mxf = s->priv_data;
966     AVIOContext *pb = s->pb;
967     int i;
968
969     mxf_write_metadata_key(pb, 0x011100);
970     PRINT_KEY(s, "sturctural component key", pb->buf_ptr - 16);
971     klv_encode_ber_length(pb, 108);
972
973     // write uid
974     mxf_write_local_tag(s, 16, 0x3C0A);
975     mxf_write_uuid(pb, SourceClip, mxf->track_instance_count);
976
977     PRINT_KEY(s, "structural component uid", pb->buf_ptr - 16);
978     mxf_write_common_fields(s, st);
979
980     // write start_position
981     mxf_write_local_tag(s, 8, 0x1201);
982     avio_wb64(pb, 0);
983
984     // write source package uid, end of the reference
985     mxf_write_local_tag(s, 32, 0x1101);
986     if (!package->ref) {
987         for (i = 0; i < 4; i++)
988             avio_wb64(pb, 0);
989     } else
990         mxf_write_umid(s, package->ref->instance);
991
992     // write source track id
993     mxf_write_local_tag(s, 4, 0x1102);
994     if (package->type == SourcePackage && !package->ref)
995         avio_wb32(pb, 0);
996     else
997         avio_wb32(pb, st->index+2);
998 }
999
1000 static void mxf_write_tape_descriptor(AVFormatContext *s)
1001 {
1002     AVIOContext *pb = s->pb;
1003
1004     mxf_write_metadata_key(pb, 0x012e00);
1005     PRINT_KEY(s, "tape descriptor key", pb->buf_ptr - 16);
1006     klv_encode_ber_length(pb, 20);
1007     mxf_write_local_tag(s, 16, 0x3C0A);
1008     mxf_write_uuid(pb, TapeDescriptor, 0);
1009     PRINT_KEY(s, "tape_desc uid", pb->buf_ptr - 16);
1010 }
1011
1012
1013 static void mxf_write_multi_descriptor(AVFormatContext *s)
1014 {
1015     MXFContext *mxf = s->priv_data;
1016     AVIOContext *pb = s->pb;
1017     const uint8_t *ul;
1018     int i;
1019
1020     mxf_write_metadata_key(pb, 0x014400);
1021     PRINT_KEY(s, "multiple descriptor key", pb->buf_ptr - 16);
1022     klv_encode_ber_length(pb, 64 + 16LL * s->nb_streams);
1023
1024     mxf_write_local_tag(s, 16, 0x3C0A);
1025     mxf_write_uuid(pb, MultipleDescriptor, 0);
1026     PRINT_KEY(s, "multi_desc uid", pb->buf_ptr - 16);
1027
1028     // write sample rate
1029     mxf_write_local_tag(s, 8, 0x3001);
1030     avio_wb32(pb, mxf->time_base.den);
1031     avio_wb32(pb, mxf->time_base.num);
1032
1033     // write essence container ul
1034     mxf_write_local_tag(s, 16, 0x3004);
1035     if (mxf->essence_container_count > 1)
1036         ul = multiple_desc_ul;
1037     else {
1038         MXFStreamContext *sc = s->streams[0]->priv_data;
1039         ul = *sc->container_ul;
1040     }
1041     avio_write(pb, ul, 16);
1042
1043     // write sub descriptor refs
1044     mxf_write_local_tag(s, s->nb_streams * 16 + 8, 0x3F01);
1045     mxf_write_refs_count(pb, s->nb_streams);
1046     for (i = 0; i < s->nb_streams; i++)
1047         mxf_write_uuid(pb, SubDescriptor, i);
1048 }
1049
1050 static int64_t mxf_write_generic_desc(AVFormatContext *s, AVStream *st, const UID key)
1051 {
1052     MXFContext *mxf = s->priv_data;
1053     MXFStreamContext *sc = st->priv_data;
1054     AVIOContext *pb = s->pb;
1055     int64_t pos;
1056
1057     avio_write(pb, key, 16);
1058     klv_encode_ber4_length(pb, 0);
1059     pos = avio_tell(pb);
1060
1061     mxf_write_local_tag(s, 16, 0x3C0A);
1062     mxf_write_uuid(pb, SubDescriptor, st->index);
1063
1064     mxf_write_local_tag(s, 4, 0x3006);
1065     avio_wb32(pb, st->index+2);
1066
1067     mxf_write_local_tag(s, 8, 0x3001);
1068     if (s->oformat == &ff_mxf_d10_muxer) {
1069         avio_wb32(pb, mxf->time_base.den);
1070         avio_wb32(pb, mxf->time_base.num);
1071     } else {
1072         if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE ||
1073             st->codecpar->codec_id == AV_CODEC_ID_PCM_S24LE) {
1074             avio_wb32(pb, st->codecpar->sample_rate);
1075             avio_wb32(pb, 1);
1076         } else {
1077             avio_wb32(pb, mxf->time_base.den);
1078             avio_wb32(pb, mxf->time_base.num);
1079         }
1080     }
1081
1082     mxf_write_local_tag(s, 16, 0x3004);
1083     avio_write(pb, *sc->container_ul, 16);
1084
1085     return pos;
1086 }
1087
1088 static const UID mxf_s436m_anc_descriptor_key = { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5c,0x00 };
1089 static const UID mxf_mpegvideo_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 };
1090 static const UID mxf_wav_descriptor_key       = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 };
1091 static const UID mxf_aes3_descriptor_key      = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 };
1092 static const UID mxf_cdci_descriptor_key      = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x28,0x00 };
1093 static const UID mxf_generic_sound_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x42,0x00 };
1094
1095 static const UID mxf_avc_subdescriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x6E,0x00 };
1096
1097 static inline uint16_t rescale_mastering_chroma(AVRational q)
1098 {
1099     return av_clip_uint16(av_rescale(q.num, FF_MXF_MASTERING_CHROMA_DEN, q.den));
1100 }
1101
1102 static inline uint32_t rescale_mastering_luma(AVRational q)
1103 {
1104     return av_rescale(q.num, FF_MXF_MASTERING_LUMA_DEN, q.den);
1105 }
1106
1107 static int64_t mxf_write_cdci_common(AVFormatContext *s, AVStream *st, const UID key)
1108 {
1109     MXFStreamContext *sc = st->priv_data;
1110     AVIOContext *pb = s->pb;
1111     int stored_width = 0;
1112     int stored_height = (st->codecpar->height+15)/16*16;
1113     int display_height;
1114     int f1, f2;
1115     const MXFCodecUL *color_primaries_ul;
1116     const MXFCodecUL *color_trc_ul;
1117     const MXFCodecUL *color_space_ul;
1118     int64_t pos = mxf_write_generic_desc(s, st, key);
1119     uint8_t *side_data;
1120
1121     color_primaries_ul = mxf_get_codec_ul_by_id(ff_mxf_color_primaries_uls, st->codecpar->color_primaries);
1122     color_trc_ul       = mxf_get_codec_ul_by_id(ff_mxf_color_trc_uls, st->codecpar->color_trc);
1123     color_space_ul     = mxf_get_codec_ul_by_id(ff_mxf_color_space_uls, st->codecpar->color_space);
1124
1125     if (st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO) {
1126         if (st->codecpar->height == 1080)
1127             stored_width = 1920;
1128         else if (st->codecpar->height == 720)
1129             stored_width = 1280;
1130     }
1131     if (!stored_width)
1132         stored_width = (st->codecpar->width+15)/16*16;
1133
1134     mxf_write_local_tag(s, 4, 0x3203);
1135     avio_wb32(pb, stored_width);
1136
1137     mxf_write_local_tag(s, 4, 0x3202);
1138     avio_wb32(pb, stored_height>>sc->interlaced);
1139
1140     if (s->oformat == &ff_mxf_d10_muxer) {
1141         //Stored F2 Offset
1142         mxf_write_local_tag(s, 4, 0x3216);
1143         avio_wb32(pb, 0);
1144
1145         //Image Start Offset
1146         mxf_write_local_tag(s, 4, 0x3213);
1147         avio_wb32(pb, 0);
1148
1149         //Image End Offset
1150         mxf_write_local_tag(s, 4, 0x3214);
1151         avio_wb32(pb, 0);
1152     }
1153
1154     //Sampled width
1155     mxf_write_local_tag(s, 4, 0x3205);
1156     avio_wb32(pb, stored_width);
1157
1158     //Samples height
1159     mxf_write_local_tag(s, 4, 0x3204);
1160     avio_wb32(pb, st->codecpar->height>>sc->interlaced);
1161
1162     //Sampled X Offset
1163     mxf_write_local_tag(s, 4, 0x3206);
1164     avio_wb32(pb, 0);
1165
1166     //Sampled Y Offset
1167     mxf_write_local_tag(s, 4, 0x3207);
1168     avio_wb32(pb, 0);
1169
1170     mxf_write_local_tag(s, 4, 0x3209);
1171     avio_wb32(pb, stored_width);
1172
1173     if (st->codecpar->height == 608) // PAL + VBI
1174         display_height = 576;
1175     else if (st->codecpar->height == 512)  // NTSC + VBI
1176         display_height = 486;
1177     else
1178         display_height = st->codecpar->height;
1179
1180     mxf_write_local_tag(s, 4, 0x3208);
1181     avio_wb32(pb, display_height>>sc->interlaced);
1182
1183     // display X offset
1184     mxf_write_local_tag(s, 4, 0x320A);
1185     avio_wb32(pb, 0);
1186
1187     // display Y offset
1188     mxf_write_local_tag(s, 4, 0x320B);
1189     avio_wb32(pb, (st->codecpar->height - display_height)>>sc->interlaced);
1190
1191     if (sc->interlaced) {
1192         //Display F2 Offset
1193         mxf_write_local_tag(s, 4, 0x3217);
1194         avio_wb32(pb, -((st->codecpar->height - display_height)&1));
1195     }
1196
1197     // component depth
1198     mxf_write_local_tag(s, 4, 0x3301);
1199     avio_wb32(pb, sc->component_depth);
1200
1201     // horizontal subsampling
1202     mxf_write_local_tag(s, 4, 0x3302);
1203     avio_wb32(pb, sc->h_chroma_sub_sample);
1204
1205     // vertical subsampling
1206     mxf_write_local_tag(s, 4, 0x3308);
1207     avio_wb32(pb, sc->v_chroma_sub_sample);
1208
1209     // color siting
1210     mxf_write_local_tag(s, 1, 0x3303);
1211     avio_w8(pb, sc->color_siting);
1212
1213     // Padding Bits
1214     mxf_write_local_tag(s, 2, 0x3307);
1215     avio_wb16(pb, 0);
1216
1217     if (st->codecpar->color_range != AVCOL_RANGE_UNSPECIFIED) {
1218         int black = 0,
1219             white = (1<<sc->component_depth) - 1,
1220             color = (1<<sc->component_depth);
1221         if (st->codecpar->color_range == AVCOL_RANGE_MPEG) {
1222             black = 1   << (sc->component_depth - 4);
1223             white = 235 << (sc->component_depth - 8);
1224             color = (14 << (sc->component_depth - 4)) + 1;
1225         }
1226         mxf_write_local_tag(s, 4, 0x3304);
1227         avio_wb32(pb, black);
1228         mxf_write_local_tag(s, 4, 0x3305);
1229         avio_wb32(pb, white);
1230         mxf_write_local_tag(s, 4, 0x3306);
1231         avio_wb32(pb, color);
1232     }
1233
1234     if (sc->signal_standard) {
1235         mxf_write_local_tag(s, 1, 0x3215);
1236         avio_w8(pb, sc->signal_standard);
1237     }
1238
1239     // frame layout
1240     mxf_write_local_tag(s, 1, 0x320C);
1241     avio_w8(pb, sc->interlaced);
1242
1243     // video line map
1244     switch (st->codecpar->height) {
1245     case  576: f1 = 23; f2 = st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO ? 335 : 336; break;
1246     case  608: f1 =  7; f2 = 320; break;
1247     case  480: f1 = 20; f2 = st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO ? 285 : 283; break;
1248     case  512: f1 =  7; f2 = 270; break;
1249     case  720: f1 = 26; f2 =   0; break; // progressive
1250     case 1080: f1 = 21; f2 = 584; break;
1251     default:   f1 =  0; f2 =   0; break;
1252     }
1253
1254     if (!sc->interlaced && f2) {
1255         f2  = 0;
1256         f1 *= 2;
1257     }
1258
1259
1260     mxf_write_local_tag(s, 16, 0x320D);
1261     avio_wb32(pb, 2);
1262     avio_wb32(pb, 4);
1263     avio_wb32(pb, f1);
1264     avio_wb32(pb, f2);
1265
1266     mxf_write_local_tag(s, 8, 0x320E);
1267     avio_wb32(pb, sc->aspect_ratio.num);
1268     avio_wb32(pb, sc->aspect_ratio.den);
1269
1270     if (color_primaries_ul->uid[0]) {
1271         mxf_write_local_tag(s, 16, 0x3219);
1272         avio_write(pb, color_primaries_ul->uid, 16);
1273     };
1274
1275     if (color_trc_ul->uid[0]) {
1276         mxf_write_local_tag(s, 16, 0x3210);
1277         avio_write(pb, color_trc_ul->uid, 16);
1278     };
1279
1280     if (color_space_ul->uid[0]) {
1281         mxf_write_local_tag(s, 16, 0x321A);
1282         avio_write(pb, color_space_ul->uid, 16);
1283     };
1284
1285     mxf_write_local_tag(s, 16, 0x3201);
1286     avio_write(pb, *sc->codec_ul, 16);
1287
1288     // Mastering Display metadata
1289     side_data = av_stream_get_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA, NULL);
1290     if (side_data) {
1291         const AVMasteringDisplayMetadata *metadata = (const AVMasteringDisplayMetadata*)side_data;
1292         if (metadata->has_primaries) {
1293             mxf_write_local_tag(s, 12, 0x8301);
1294             avio_wb16(pb, rescale_mastering_chroma(metadata->display_primaries[0][0]));
1295             avio_wb16(pb, rescale_mastering_chroma(metadata->display_primaries[0][1]));
1296             avio_wb16(pb, rescale_mastering_chroma(metadata->display_primaries[1][0]));
1297             avio_wb16(pb, rescale_mastering_chroma(metadata->display_primaries[1][1]));
1298             avio_wb16(pb, rescale_mastering_chroma(metadata->display_primaries[2][0]));
1299             avio_wb16(pb, rescale_mastering_chroma(metadata->display_primaries[2][1]));
1300             mxf_write_local_tag(s, 4, 0x8302);
1301             avio_wb16(pb, rescale_mastering_chroma(metadata->white_point[0]));
1302             avio_wb16(pb, rescale_mastering_chroma(metadata->white_point[1]));
1303         } else {
1304             av_log(NULL, AV_LOG_VERBOSE, "Not writing mastering display primaries. Missing data.\n");
1305         }
1306         if (metadata->has_luminance) {
1307             mxf_write_local_tag(s, 4, 0x8303);
1308             avio_wb32(pb, rescale_mastering_luma(metadata->max_luminance));
1309             mxf_write_local_tag(s, 4, 0x8304);
1310             avio_wb32(pb, rescale_mastering_luma(metadata->min_luminance));
1311         } else {
1312             av_log(NULL, AV_LOG_VERBOSE, "Not writing mastering display luminances. Missing data.\n");
1313         }
1314     }
1315
1316     if (sc->interlaced && sc->field_dominance) {
1317         mxf_write_local_tag(s, 1, 0x3212);
1318         avio_w8(pb, sc->field_dominance);
1319     }
1320
1321     if (st->codecpar->codec_id == AV_CODEC_ID_H264 && !sc->avc_intra) {
1322         // write avc sub descriptor ref
1323         mxf_write_local_tag(s, 8 + 16, 0x8100);
1324         mxf_write_refs_count(pb, 1);
1325         mxf_write_uuid(pb, AVCSubDescriptor, 0);
1326     }
1327
1328     return pos;
1329 }
1330
1331 static void mxf_update_klv_size(AVIOContext *pb, int64_t pos)
1332 {
1333     int64_t cur_pos = avio_tell(pb);
1334     int size = cur_pos - pos;
1335     avio_seek(pb, pos - 4, SEEK_SET);
1336     klv_encode_ber4_length(pb, size);
1337     avio_seek(pb, cur_pos, SEEK_SET);
1338 }
1339
1340 static void mxf_write_avc_subdesc(AVFormatContext *s, AVStream *st)
1341 {
1342     AVIOContext *pb = s->pb;
1343     int64_t pos;
1344
1345     avio_write(pb, mxf_avc_subdescriptor_key, 16);
1346     klv_encode_ber4_length(pb, 0);
1347     pos = avio_tell(pb);
1348
1349     mxf_write_local_tag(s, 16, 0x3C0A);
1350     mxf_write_uuid(pb, AVCSubDescriptor, 0);
1351
1352     mxf_write_local_tag(s, 1, 0x8200);
1353     avio_w8(pb, 0xFF); // AVC Decoding Delay, unknown
1354
1355     mxf_write_local_tag(s, 1, 0x8201);
1356     avio_w8(pb, st->codecpar->profile); // AVC Profile
1357
1358     mxf_write_local_tag(s, 1, 0x8202);
1359     avio_w8(pb, st->codecpar->level); // AVC Level
1360
1361     mxf_update_klv_size(s->pb, pos);
1362 }
1363
1364 static void mxf_write_cdci_desc(AVFormatContext *s, AVStream *st)
1365 {
1366     int64_t pos = mxf_write_cdci_common(s, st, mxf_cdci_descriptor_key);
1367     mxf_update_klv_size(s->pb, pos);
1368
1369     if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
1370         mxf_write_avc_subdesc(s, st);
1371     }
1372 }
1373
1374 static void mxf_write_h264_desc(AVFormatContext *s, AVStream *st)
1375 {
1376     MXFStreamContext *sc = st->priv_data;
1377     if (sc->avc_intra) {
1378         mxf_write_mpegvideo_desc(s, st);
1379     } else {
1380         int64_t pos = mxf_write_cdci_common(s, st, mxf_cdci_descriptor_key);
1381         mxf_update_klv_size(s->pb, pos);
1382         mxf_write_avc_subdesc(s, st);
1383     }
1384 }
1385
1386 static void mxf_write_s436m_anc_desc(AVFormatContext *s, AVStream *st)
1387 {
1388     int64_t pos = mxf_write_generic_desc(s, st, mxf_s436m_anc_descriptor_key);
1389     mxf_update_klv_size(s->pb, pos);
1390 }
1391
1392 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st)
1393 {
1394     AVIOContext *pb = s->pb;
1395     MXFStreamContext *sc = st->priv_data;
1396     int profile_and_level = (st->codecpar->profile<<4) | st->codecpar->level;
1397     int64_t pos = mxf_write_cdci_common(s, st, mxf_mpegvideo_descriptor_key);
1398
1399     if (st->codecpar->codec_id != AV_CODEC_ID_H264) {
1400         // bit rate
1401         mxf_write_local_tag(s, 4, 0x8000);
1402         avio_wb32(pb, sc->video_bit_rate);
1403
1404         // profile and level
1405         mxf_write_local_tag(s, 1, 0x8007);
1406         if (!st->codecpar->profile)
1407             profile_and_level |= 0x80; // escape bit
1408         avio_w8(pb, profile_and_level);
1409
1410         // low delay
1411         mxf_write_local_tag(s, 1, 0x8003);
1412         avio_w8(pb, sc->low_delay);
1413
1414         // closed gop
1415         mxf_write_local_tag(s, 1, 0x8004);
1416         avio_w8(pb, sc->seq_closed_gop);
1417
1418         // max gop
1419         mxf_write_local_tag(s, 2, 0x8006);
1420         avio_wb16(pb, sc->max_gop);
1421
1422         // b picture count
1423         mxf_write_local_tag(s, 2, 0x8008);
1424         avio_wb16(pb, sc->b_picture_count);
1425     }
1426
1427     mxf_update_klv_size(pb, pos);
1428 }
1429
1430 static int64_t mxf_write_generic_sound_common(AVFormatContext *s, AVStream *st, const UID key)
1431 {
1432     AVIOContext *pb = s->pb;
1433     MXFContext *mxf = s->priv_data;
1434     int show_warnings = !mxf->footer_partition_offset;
1435     int64_t pos = mxf_write_generic_desc(s, st, key);
1436
1437     if (s->oformat == &ff_mxf_opatom_muxer) {
1438         mxf_write_local_tag(s, 8, 0x3002);
1439         avio_wb64(pb, mxf->body_offset / mxf->edit_unit_byte_count);
1440     }
1441
1442     // audio locked
1443     mxf_write_local_tag(s, 1, 0x3D02);
1444     avio_w8(pb, 1);
1445
1446     // write audio sampling rate
1447     mxf_write_local_tag(s, 8, 0x3D03);
1448     avio_wb32(pb, st->codecpar->sample_rate);
1449     avio_wb32(pb, 1);
1450
1451     if (s->oformat == &ff_mxf_d10_muxer) {
1452         mxf_write_local_tag(s, 1, 0x3D04);
1453         avio_w8(pb, 0);
1454     }
1455
1456     mxf_write_local_tag(s, 4, 0x3D07);
1457     if (mxf->channel_count == -1) {
1458         if (show_warnings && (s->oformat == &ff_mxf_d10_muxer) && (st->codecpar->channels != 4) && (st->codecpar->channels != 8))
1459             av_log(s, AV_LOG_WARNING, "the number of audio channels shall be 4 or 8 : the output will not comply to MXF D-10 specs, use -d10_channelcount to fix this\n");
1460         avio_wb32(pb, st->codecpar->channels);
1461     } else if (s->oformat == &ff_mxf_d10_muxer) {
1462         if (show_warnings && (mxf->channel_count < st->codecpar->channels))
1463             av_log(s, AV_LOG_WARNING, "d10_channelcount < actual number of audio channels : some channels will be discarded\n");
1464         if (show_warnings && (mxf->channel_count != 4) && (mxf->channel_count != 8))
1465             av_log(s, AV_LOG_WARNING, "d10_channelcount shall be set to 4 or 8 : the output will not comply to MXF D-10 specs\n");
1466         avio_wb32(pb, mxf->channel_count);
1467     } else {
1468         avio_wb32(pb, st->codecpar->channels);
1469     }
1470
1471     mxf_write_local_tag(s, 4, 0x3D01);
1472     avio_wb32(pb, av_get_bits_per_sample(st->codecpar->codec_id));
1473
1474     return pos;
1475 }
1476
1477 static int64_t mxf_write_wav_common(AVFormatContext *s, AVStream *st, const UID key)
1478 {
1479     AVIOContext *pb = s->pb;
1480     int64_t pos = mxf_write_generic_sound_common(s, st, key);
1481
1482     mxf_write_local_tag(s, 2, 0x3D0A);
1483     avio_wb16(pb, st->codecpar->block_align);
1484
1485     // avg bytes per sec
1486     mxf_write_local_tag(s, 4, 0x3D09);
1487     avio_wb32(pb, st->codecpar->block_align*st->codecpar->sample_rate);
1488
1489     return pos;
1490 }
1491
1492 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st)
1493 {
1494     int64_t pos = mxf_write_wav_common(s, st, mxf_wav_descriptor_key);
1495     mxf_update_klv_size(s->pb, pos);
1496 }
1497
1498 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st)
1499 {
1500     int64_t pos = mxf_write_wav_common(s, st, mxf_aes3_descriptor_key);
1501     mxf_update_klv_size(s->pb, pos);
1502 }
1503
1504 static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st)
1505 {
1506     int64_t pos = mxf_write_generic_sound_common(s, st, mxf_generic_sound_descriptor_key);
1507     mxf_update_klv_size(s->pb, pos);
1508 }
1509
1510 static const uint8_t mxf_indirect_value_utf16le[] = { 0x4c,0x00,0x02,0x10,0x01,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 };
1511
1512 static int mxf_write_tagged_value(AVFormatContext *s, const char* name, const char* value)
1513 {
1514     MXFContext *mxf = s->priv_data;
1515     AVIOContext *pb = s->pb;
1516     int name_size = mxf_utf16_local_tag_length(name);
1517     int indirect_value_size = 13 + mxf_utf16_local_tag_length(value);
1518
1519     if (!name_size || indirect_value_size == 13)
1520         return 1;
1521
1522     mxf_write_metadata_key(pb, 0x013f00);
1523     klv_encode_ber_length(pb, 24 + name_size + indirect_value_size);
1524
1525     // write instance UID
1526     mxf_write_local_tag(s, 16, 0x3C0A);
1527     mxf_write_uuid(pb, TaggedValue, mxf->tagged_value_count);
1528
1529     // write name
1530     mxf_write_local_tag_utf16(s, 0x5001, name); // Name
1531
1532     // write indirect value
1533     mxf_write_local_tag(s, indirect_value_size, 0x5003);
1534     avio_write(pb, mxf_indirect_value_utf16le, 17);
1535     avio_put_str16le(pb, value);
1536
1537     mxf->tagged_value_count++;
1538     return 0;
1539 }
1540
1541 static int mxf_write_user_comments(AVFormatContext *s, const AVDictionary *m)
1542 {
1543     MXFContext *mxf = s->priv_data;
1544     AVDictionaryEntry *t = NULL;
1545     int count = 0;
1546
1547     while ((t = av_dict_get(m, "comment_", t, AV_DICT_IGNORE_SUFFIX))) {
1548         if (mxf->tagged_value_count >= UINT16_MAX) {
1549             av_log(s, AV_LOG_ERROR, "too many tagged values, ignoring remaining\n");
1550             return count;
1551         }
1552
1553         if (mxf_write_tagged_value(s, t->key + 8, t->value) == 0)
1554             count++;
1555     }
1556     return count;
1557 }
1558
1559 static void mxf_write_package(AVFormatContext *s, MXFPackage *package)
1560 {
1561     MXFContext *mxf = s->priv_data;
1562     AVIOContext *pb = s->pb;
1563     int i, track_count = s->nb_streams+1;
1564     int name_size = mxf_utf16_local_tag_length(package->name);
1565     int user_comment_count = 0;
1566
1567     if (package->type == MaterialPackage) {
1568         if (mxf->store_user_comments)
1569             user_comment_count = mxf_write_user_comments(s, s->metadata);
1570         mxf_write_metadata_key(pb, 0x013600);
1571         PRINT_KEY(s, "Material Package key", pb->buf_ptr - 16);
1572         klv_encode_ber_length(pb, 92 + name_size + (16*track_count) + (16*user_comment_count) + 12LL*mxf->store_user_comments);
1573     } else {
1574         mxf_write_metadata_key(pb, 0x013700);
1575         PRINT_KEY(s, "Source Package key", pb->buf_ptr - 16);
1576         klv_encode_ber_length(pb, 112 + name_size + (16*track_count) + 12LL*mxf->store_user_comments); // 20 bytes length for descriptor reference
1577     }
1578
1579     // write uid
1580     mxf_write_local_tag(s, 16, 0x3C0A);
1581     mxf_write_uuid(pb, package->type, package->instance);
1582     av_log(s, AV_LOG_DEBUG, "package type:%d\n", package->type);
1583     PRINT_KEY(s, "package uid", pb->buf_ptr - 16);
1584
1585     // write package umid
1586     mxf_write_local_tag(s, 32, 0x4401);
1587     mxf_write_umid(s, package->instance);
1588     PRINT_KEY(s, "package umid second part", pb->buf_ptr - 16);
1589
1590     // package name
1591     if (name_size)
1592         mxf_write_local_tag_utf16(s, 0x4402, package->name);
1593
1594     // package creation date
1595     mxf_write_local_tag(s, 8, 0x4405);
1596     avio_wb64(pb, mxf->timestamp);
1597
1598     // package modified date
1599     mxf_write_local_tag(s, 8, 0x4404);
1600     avio_wb64(pb, mxf->timestamp);
1601
1602     // write track refs
1603     mxf_write_local_tag(s, track_count*16 + 8, 0x4403);
1604     mxf_write_refs_count(pb, track_count);
1605     // these are the uuids of the tracks the will be written in mxf_write_track
1606     for (i = 0; i < track_count; i++)
1607         mxf_write_uuid(pb, Track,  mxf->track_instance_count + i);
1608
1609     // write user comment refs
1610     if (mxf->store_user_comments) {
1611         mxf_write_local_tag(s, user_comment_count*16 + 8, 0x4406);
1612         mxf_write_refs_count(pb, user_comment_count);
1613         for (i = 0; i < user_comment_count; i++)
1614             mxf_write_uuid(pb, TaggedValue, mxf->tagged_value_count - user_comment_count + i);
1615     }
1616
1617     // write multiple descriptor reference
1618     if (package->type == SourcePackage && package->instance == 1) {
1619         mxf_write_local_tag(s, 16, 0x4701);
1620         if (s->nb_streams > 1) {
1621             mxf_write_uuid(pb, MultipleDescriptor, 0);
1622             mxf_write_multi_descriptor(s);
1623         } else
1624             mxf_write_uuid(pb, SubDescriptor, 0);
1625     } else if (package->type == SourcePackage && package->instance == 2) {
1626         mxf_write_local_tag(s, 16, 0x4701);
1627         mxf_write_uuid(pb, TapeDescriptor, 0);
1628         mxf_write_tape_descriptor(s);
1629     }
1630
1631     /*
1632      * for every 1 track in a package there is 1 sequence and 1 component.
1633      * all 3 of these elements share the same instance number for generating
1634      * there instance uuids. mxf->track_instance_count stores this value.
1635      * mxf->track_instance_count is incremented after a group of all 3 of
1636      * these elements are written.
1637      */
1638
1639     // write timecode track
1640     mxf_write_track(s, mxf->timecode_track, package);
1641     mxf_write_sequence(s, mxf->timecode_track, package);
1642     mxf_write_timecode_component(s, mxf->timecode_track, package);
1643     mxf->track_instance_count++;
1644
1645     for (i = 0; i < s->nb_streams; i++) {
1646         AVStream *st = s->streams[i];
1647         mxf_write_track(s, st, package);
1648         mxf_write_sequence(s, st, package);
1649         mxf_write_structural_component(s, st, package);
1650         mxf->track_instance_count++;
1651
1652         if (package->type == SourcePackage && package->instance == 1) {
1653             MXFStreamContext *sc = st->priv_data;
1654             mxf_essence_container_uls[sc->index].write_desc(s, st);
1655         }
1656     }
1657 }
1658
1659 static int mxf_write_essence_container_data(AVFormatContext *s)
1660 {
1661     AVIOContext *pb = s->pb;
1662
1663     mxf_write_metadata_key(pb, 0x012300);
1664     klv_encode_ber_length(pb, 72);
1665
1666     mxf_write_local_tag(s, 16, 0x3C0A); // Instance UID
1667     mxf_write_uuid(pb, EssenceContainerData, 0);
1668
1669     mxf_write_local_tag(s, 32, 0x2701); // Linked Package UID
1670     mxf_write_umid(s, 1);
1671
1672     mxf_write_local_tag(s, 4, 0x3F07); // BodySID
1673     avio_wb32(pb, 1);
1674
1675     mxf_write_local_tag(s, 4, 0x3F06); // IndexSID
1676     avio_wb32(pb, 2);
1677
1678     return 0;
1679 }
1680
1681 static int mxf_write_header_metadata_sets(AVFormatContext *s)
1682 {
1683     MXFContext *mxf = s->priv_data;
1684     AVDictionaryEntry *entry = NULL;
1685     AVStream *st = NULL;
1686     int i;
1687     MXFPackage packages[3] = {{0}};
1688     int package_count = 2;
1689     packages[0].type = MaterialPackage;
1690     packages[1].type = SourcePackage;
1691     packages[1].instance = 1;
1692     packages[0].ref = &packages[1];
1693
1694
1695     if (entry = av_dict_get(s->metadata, "material_package_name", NULL, 0))
1696        packages[0].name = entry->value;
1697
1698     if (entry = av_dict_get(s->metadata, "file_package_name", NULL, 0)) {
1699         packages[1].name = entry->value;
1700     } else {
1701         /* check if any of the streams contain a file_package_name */
1702         for (i = 0; i < s->nb_streams; i++) {
1703             st = s->streams[i];
1704             if (entry = av_dict_get(st->metadata, "file_package_name", NULL, 0)) {
1705                 packages[1].name = entry->value;
1706                 break;
1707             }
1708         }
1709     }
1710
1711     entry = av_dict_get(s->metadata, "reel_name", NULL, 0);
1712     if (entry) {
1713         packages[2].name = entry->value;
1714         packages[2].type = SourcePackage;
1715         packages[2].instance = 2;
1716         packages[1].ref = &packages[2];
1717         package_count = 3;
1718     }
1719
1720     mxf_write_preface(s);
1721     mxf_write_identification(s);
1722     mxf_write_content_storage(s, packages, package_count);
1723     mxf->track_instance_count = 0;
1724     for (i = 0; i < package_count; i++)
1725         mxf_write_package(s, &packages[i]);
1726     mxf_write_essence_container_data(s);
1727     return 0;
1728 }
1729
1730 static unsigned klv_fill_size(uint64_t size)
1731 {
1732     unsigned pad = KAG_SIZE - (size & (KAG_SIZE-1));
1733     if (pad < 20) // smallest fill item possible
1734         return pad + KAG_SIZE;
1735     else
1736         return pad & (KAG_SIZE-1);
1737 }
1738
1739 static void mxf_write_index_table_segment(AVFormatContext *s)
1740 {
1741     MXFContext *mxf = s->priv_data;
1742     AVIOContext *pb = s->pb;
1743     int i, j, temporal_reordering = 0;
1744     int key_index = mxf->last_key_index;
1745     int prev_non_b_picture = 0;
1746     int audio_frame_size = 0;
1747     int64_t pos;
1748
1749     av_log(s, AV_LOG_DEBUG, "edit units count %d\n", mxf->edit_units_count);
1750
1751     if (!mxf->edit_units_count && !mxf->edit_unit_byte_count)
1752         return;
1753
1754     avio_write(pb, index_table_segment_key, 16);
1755
1756     klv_encode_ber4_length(pb, 0);
1757     pos = avio_tell(pb);
1758
1759     // instance id
1760     mxf_write_local_tag(s, 16, 0x3C0A);
1761     mxf_write_uuid(pb, IndexTableSegment, 0);
1762
1763     // index edit rate
1764     mxf_write_local_tag(s, 8, 0x3F0B);
1765     avio_wb32(pb, mxf->time_base.den);
1766     avio_wb32(pb, mxf->time_base.num);
1767
1768     // index start position
1769     mxf_write_local_tag(s, 8, 0x3F0C);
1770     avio_wb64(pb, mxf->last_indexed_edit_unit);
1771
1772     // index duration
1773     mxf_write_local_tag(s, 8, 0x3F0D);
1774     if (mxf->edit_unit_byte_count)
1775         avio_wb64(pb, 0); // index table covers whole container
1776     else
1777         avio_wb64(pb, mxf->edit_units_count);
1778
1779     // edit unit byte count
1780     mxf_write_local_tag(s, 4, 0x3F05);
1781     avio_wb32(pb, mxf->edit_unit_byte_count);
1782
1783     // index sid
1784     mxf_write_local_tag(s, 4, 0x3F06);
1785     avio_wb32(pb, 2);
1786
1787     // body sid
1788     mxf_write_local_tag(s, 4, 0x3F07);
1789     avio_wb32(pb, 1);
1790
1791     // real slice count - 1
1792     mxf_write_local_tag(s, 1, 0x3F08);
1793     avio_w8(pb, !mxf->edit_unit_byte_count); // only one slice for CBR
1794
1795     // delta entry array
1796     mxf_write_local_tag(s, 8 + (s->nb_streams+1)*6, 0x3F09);
1797     avio_wb32(pb, s->nb_streams+1); // num of entries
1798     avio_wb32(pb, 6);               // size of one entry
1799     // write system item delta entry
1800     avio_w8(pb, 0);
1801     avio_w8(pb, 0); // slice entry
1802     avio_wb32(pb, 0); // element delta
1803     // write each stream delta entry
1804     for (i = 0; i < s->nb_streams; i++) {
1805         AVStream *st = s->streams[i];
1806         MXFStreamContext *sc = st->priv_data;
1807         avio_w8(pb, sc->temporal_reordering);
1808         if (sc->temporal_reordering)
1809             temporal_reordering = 1;
1810         if (mxf->edit_unit_byte_count) {
1811             avio_w8(pb, 0); // slice number
1812             avio_wb32(pb, sc->slice_offset);
1813         } else if (i == 0) { // video track
1814             avio_w8(pb, 0); // slice number
1815             avio_wb32(pb, KAG_SIZE); // system item size including klv fill
1816         } else { // audio or data track
1817             if (!audio_frame_size) {
1818                 audio_frame_size = sc->frame_size;
1819                 audio_frame_size += klv_fill_size(audio_frame_size);
1820             }
1821             avio_w8(pb, 1);
1822             avio_wb32(pb, (i-1)*audio_frame_size); // element delta
1823         }
1824     }
1825
1826     if (!mxf->edit_unit_byte_count) {
1827         MXFStreamContext *sc = s->streams[0]->priv_data;
1828         mxf_write_local_tag(s, 8 + mxf->edit_units_count*15, 0x3F0A);
1829         avio_wb32(pb, mxf->edit_units_count);  // num of entries
1830         avio_wb32(pb, 15);  // size of one entry
1831
1832         for (i = 0; i < mxf->edit_units_count; i++) {
1833             int temporal_offset = 0;
1834
1835             if (!(mxf->index_entries[i].flags & 0x33)) { // I-frame
1836                 sc->max_gop = FFMAX(sc->max_gop, i - mxf->last_key_index);
1837                 mxf->last_key_index = key_index;
1838                 key_index = i;
1839             }
1840
1841             if (temporal_reordering) {
1842                 int pic_num_in_gop = i - key_index;
1843                 if (pic_num_in_gop != mxf->index_entries[i].temporal_ref) {
1844                     for (j = key_index; j < mxf->edit_units_count; j++) {
1845                         if (pic_num_in_gop == mxf->index_entries[j].temporal_ref)
1846                             break;
1847                     }
1848                     if (j == mxf->edit_units_count)
1849                         av_log(s, AV_LOG_WARNING, "missing frames\n");
1850                     temporal_offset = j - key_index - pic_num_in_gop;
1851                 }
1852             }
1853             avio_w8(pb, temporal_offset);
1854
1855             if ((mxf->index_entries[i].flags & 0x30) == 0x30) { // back and forward prediction
1856                 sc->b_picture_count = FFMAX(sc->b_picture_count, i - prev_non_b_picture);
1857                 avio_w8(pb, mxf->last_key_index - i);
1858             } else {
1859                 avio_w8(pb, key_index - i); // key frame offset
1860                 if ((mxf->index_entries[i].flags & 0x20) == 0x20) // only forward
1861                     mxf->last_key_index = key_index;
1862                 prev_non_b_picture = i;
1863             }
1864
1865             if (!(mxf->index_entries[i].flags & 0x33) && // I-frame
1866                 mxf->index_entries[i].flags & 0x40 && !temporal_offset)
1867                 mxf->index_entries[i].flags |= 0x80; // random access
1868             avio_w8(pb, mxf->index_entries[i].flags);
1869             // stream offset
1870             avio_wb64(pb, mxf->index_entries[i].offset);
1871             if (s->nb_streams > 1)
1872                 avio_wb32(pb, mxf->index_entries[i].slice_offset);
1873             else
1874                 avio_wb32(pb, 0);
1875         }
1876
1877         mxf->last_key_index = key_index - mxf->edit_units_count;
1878         mxf->last_indexed_edit_unit += mxf->edit_units_count;
1879         mxf->edit_units_count = 0;
1880     }
1881
1882     mxf_update_klv_size(pb, pos);
1883 }
1884
1885 static void mxf_write_klv_fill(AVFormatContext *s)
1886 {
1887     unsigned pad = klv_fill_size(avio_tell(s->pb));
1888     if (pad) {
1889         avio_write(s->pb, klv_fill_key, 16);
1890         pad -= 16 + 4;
1891         klv_encode_ber4_length(s->pb, pad);
1892         ffio_fill(s->pb, 0, pad);
1893         av_assert1(!(avio_tell(s->pb) & (KAG_SIZE-1)));
1894     }
1895 }
1896
1897 static int mxf_write_partition(AVFormatContext *s, int bodysid,
1898                                 int indexsid,
1899                                 const uint8_t *key, int write_metadata)
1900 {
1901     MXFContext *mxf = s->priv_data;
1902     AVIOContext *pb = s->pb;
1903     int64_t header_byte_count_offset;
1904     unsigned index_byte_count = 0;
1905     uint64_t partition_offset = avio_tell(pb);
1906     int err;
1907
1908     if (!mxf->edit_unit_byte_count && mxf->edit_units_count)
1909         index_byte_count = 85 + 12+(s->nb_streams+1)*6 +
1910             12+mxf->edit_units_count*15;
1911     else if (mxf->edit_unit_byte_count && indexsid)
1912         index_byte_count = 80;
1913
1914     if (index_byte_count) {
1915         index_byte_count += 16 + 4; // add encoded ber4 length
1916         index_byte_count += klv_fill_size(index_byte_count);
1917     }
1918
1919     if (key && !memcmp(key, body_partition_key, 16)) {
1920         if ((err = av_reallocp_array(&mxf->body_partition_offset, mxf->body_partitions_count + 1,
1921                                      sizeof(*mxf->body_partition_offset))) < 0) {
1922             mxf->body_partitions_count = 0;
1923             return err;
1924         }
1925         mxf->body_partition_offset[mxf->body_partitions_count++] = partition_offset;
1926     }
1927
1928     // write klv
1929     if (key)
1930         avio_write(pb, key, 16);
1931     else
1932         avio_write(pb, body_partition_key, 16);
1933
1934     klv_encode_ber4_length(pb, 88 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count));
1935
1936     // write partition value
1937     avio_wb16(pb, 1); // majorVersion
1938     avio_wb16(pb, 3); // minorVersion
1939     avio_wb32(pb, KAG_SIZE); // KAGSize
1940
1941     avio_wb64(pb, partition_offset); // ThisPartition
1942
1943     if (key && !memcmp(key, body_partition_key, 16) && mxf->body_partitions_count > 1)
1944         avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-2]); // PreviousPartition
1945     else if (key && !memcmp(key, footer_partition_key, 16) && mxf->body_partitions_count)
1946         avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-1]); // PreviousPartition
1947     else
1948         avio_wb64(pb, 0);
1949
1950     avio_wb64(pb, mxf->footer_partition_offset); // footerPartition
1951
1952     // set offset
1953     header_byte_count_offset = avio_tell(pb);
1954     avio_wb64(pb, 0); // headerByteCount, update later
1955
1956     // indexTable
1957     avio_wb64(pb, index_byte_count); // indexByteCount
1958     avio_wb32(pb, index_byte_count ? indexsid : 0); // indexSID
1959
1960     // BodyOffset
1961     if (bodysid && mxf->edit_units_count && mxf->body_partitions_count && s->oformat != &ff_mxf_opatom_muxer)
1962         avio_wb64(pb, mxf->body_offset);
1963     else
1964         avio_wb64(pb, 0);
1965
1966     avio_wb32(pb, bodysid); // bodySID
1967
1968     // operational pattern
1969     if (s->oformat == &ff_mxf_opatom_muxer)
1970         avio_write(pb, opatom_ul, 16);
1971     else
1972         avio_write(pb, op1a_ul, 16);
1973
1974     // essence container
1975     mxf_write_essence_container_refs(s);
1976
1977     if (write_metadata) {
1978         // mark the start of the headermetadata and calculate metadata size
1979         int64_t pos, start;
1980         unsigned header_byte_count;
1981
1982         mxf_write_klv_fill(s);
1983         start = avio_tell(s->pb);
1984         mxf_write_primer_pack(s);
1985         mxf_write_klv_fill(s);
1986         mxf_write_header_metadata_sets(s);
1987         pos = avio_tell(s->pb);
1988         header_byte_count = pos - start + klv_fill_size(pos);
1989
1990         // update header_byte_count
1991         avio_seek(pb, header_byte_count_offset, SEEK_SET);
1992         avio_wb64(pb, header_byte_count);
1993         avio_seek(pb, pos, SEEK_SET);
1994     }
1995
1996     if(key)
1997         avio_write_marker(pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
1998
1999     return 0;
2000 }
2001
2002 static const struct {
2003     int profile;
2004     UID codec_ul;
2005 } mxf_prores_codec_uls[] = {
2006     { FF_PROFILE_PRORES_PROXY,    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x01,0x00 } },
2007     { FF_PROFILE_PRORES_LT,       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x02,0x00 } },
2008     { FF_PROFILE_PRORES_STANDARD, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x03,0x00 } },
2009     { FF_PROFILE_PRORES_HQ,       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x04,0x00 } },
2010     { FF_PROFILE_PRORES_4444,     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x05,0x00 } },
2011     { FF_PROFILE_PRORES_XQ,       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x06,0x00 } },
2012 };
2013
2014 static int mxf_parse_prores_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
2015 {
2016     MXFContext *mxf = s->priv_data;
2017     MXFStreamContext *sc = st->priv_data;
2018     int i, profile;
2019
2020     if (mxf->header_written)
2021         return 1;
2022
2023     profile = st->codecpar->profile;
2024     for (i = 0; i < FF_ARRAY_ELEMS(mxf_prores_codec_uls); i++) {
2025         if (profile == mxf_prores_codec_uls[i].profile) {
2026             sc->codec_ul = &mxf_prores_codec_uls[i].codec_ul;
2027             break;
2028         }
2029     }
2030     if (i == FF_ARRAY_ELEMS(mxf_prores_codec_uls))
2031         return 0;
2032
2033     sc->frame_size = pkt->size;
2034
2035     return 1;
2036 }
2037
2038 static const struct {
2039     int cid;
2040     UID codec_ul;
2041 } mxf_dnxhd_codec_uls[] = {
2042     { 1235, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x01,0x00,0x00 } }, // 1080p 10bit HIGH
2043     { 1237, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x03,0x00,0x00 } }, // 1080p 8bit MED
2044     { 1238, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x04,0x00,0x00 } }, // 1080p 8bit HIGH
2045     { 1241, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x07,0x00,0x00 } }, // 1080i 10bit HIGH
2046     { 1242, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x08,0x00,0x00 } }, // 1080i 8bit MED
2047     { 1243, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x09,0x00,0x00 } }, // 1080i 8bit HIGH
2048     { 1244, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x0a,0x00,0x00 } }, // 1080i 8bit TR
2049     { 1250, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x10,0x00,0x00 } }, // 720p 10bit
2050     { 1251, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x11,0x00,0x00 } }, // 720p 8bit HIGH
2051     { 1252, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x12,0x00,0x00 } }, // 720p 8bit MED
2052     { 1253, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x13,0x00,0x00 } }, // 720p 8bit LOW
2053     { 1256, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x16,0x00,0x00 } }, // 1080p 10bit 444
2054     { 1258, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x18,0x00,0x00 } }, // 720p 8bit TR
2055     { 1259, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x19,0x00,0x00 } }, // 1080p 8bit TR
2056     { 1260, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x1a,0x00,0x00 } }, // 1080i 8bit TR MBAFF
2057     { 1270, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x24,0x00,0x00 } }, // DNXHR 444
2058     { 1271, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x25,0x00,0x00 } }, // DNXHR HQX
2059     { 1272, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x26,0x00,0x00 } }, // DNXHR HQ
2060     { 1273, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x27,0x00,0x00 } }, // DNXHR SQ
2061     { 1274, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x28,0x00,0x00 } }, // DNXHR LB
2062 };
2063
2064 static int mxf_parse_dnxhd_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
2065 {
2066     MXFContext *mxf = s->priv_data;
2067     MXFStreamContext *sc = st->priv_data;
2068     int i, cid, frame_size = 0;
2069
2070     if (mxf->header_written)
2071         return 1;
2072
2073     if (pkt->size < 43)
2074         return 0;
2075
2076     cid = AV_RB32(pkt->data + 0x28);
2077     for (i = 0; i < FF_ARRAY_ELEMS(mxf_dnxhd_codec_uls); i++) {
2078         if (cid == mxf_dnxhd_codec_uls[i].cid) {
2079             sc->codec_ul = &mxf_dnxhd_codec_uls[i].codec_ul;
2080             break;
2081         }
2082     }
2083     if (i == FF_ARRAY_ELEMS(mxf_dnxhd_codec_uls))
2084         return 0;
2085
2086     sc->component_depth = 0;
2087     switch (pkt->data[0x21] >> 5) {
2088     case 1: sc->component_depth = 8; break;
2089     case 2: sc->component_depth = 10; break;
2090     case 3: sc->component_depth = 12; break;
2091     }
2092     if (!sc->component_depth)
2093         return 0;
2094
2095     if ((frame_size = avpriv_dnxhd_get_frame_size(cid)) == DNXHD_VARIABLE) {
2096         frame_size = avpriv_dnxhd_get_hr_frame_size(cid, st->codecpar->width, st->codecpar->height);
2097     }
2098     if (frame_size < 0)
2099         return 0;
2100
2101     if ((sc->interlaced = avpriv_dnxhd_get_interlaced(cid)) < 0)
2102         return 0;
2103
2104     if (cid >= 1270) { // RI raster
2105         av_reduce(&sc->aspect_ratio.num, &sc->aspect_ratio.den,
2106                   st->codecpar->width, st->codecpar->height,
2107                   INT_MAX);
2108     } else {
2109         sc->aspect_ratio = (AVRational){ 16, 9 };
2110     }
2111
2112     sc->frame_size = pkt->size;
2113
2114     return 1;
2115 }
2116
2117 static const struct {
2118     const UID container_ul;
2119     const UID codec_ul;
2120 } mxf_dv_uls[] = {
2121     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x01,0x01 }, // IEC DV25 525/60
2122       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x01,0x01,0x00 } },
2123     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x02,0x01 }, // IEC DV25 626/50
2124       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x01,0x02,0x00 } },
2125     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x40,0x01 }, // DV25 525/60
2126       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x01,0x00 }, },
2127     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, // DV25 625/50
2128       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x02,0x00 }, },
2129     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x50,0x01 }, // DV50 525/60
2130       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x03,0x00 }, },
2131     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x51,0x01 }, // DV50 625/50
2132       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x04,0x00 }, },
2133     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x60,0x01 }, // DV100 1080/60
2134       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x05,0x00 }, },
2135     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x61,0x01 }, // DV100 1080/50
2136       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x06,0x00 }, },
2137     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x62,0x01 }, // DV100 720/60
2138       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x07,0x00 }, },
2139     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x63,0x01 }, // DV100 720/50
2140       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x08,0x00 }, },
2141 };
2142
2143 static int mxf_parse_dv_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
2144 {
2145     MXFContext *mxf = s->priv_data;
2146     MXFStreamContext *sc = st->priv_data;
2147     uint8_t *vs_pack, *vsc_pack;
2148     int apt, ul_index, stype, pal;
2149
2150     if (mxf->header_written)
2151         return 1;
2152
2153     // Check for minimal frame size
2154     if (pkt->size < 120000)
2155         return -1;
2156
2157     apt      = pkt->data[4] & 0x7;
2158     vs_pack  = pkt->data + 80*5 + 48;
2159     vsc_pack = pkt->data + 80*5 + 53;
2160     stype    = vs_pack[3] & 0x1f;
2161     pal      = (vs_pack[3] >> 5) & 0x1;
2162
2163     if ((vsc_pack[2] & 0x07) == 0x02) {
2164         sc->aspect_ratio = (AVRational){ 16, 9 };
2165     } else {
2166         sc->aspect_ratio = (AVRational){ 4, 3 };
2167     }
2168
2169     sc->interlaced = (vsc_pack[3] >> 4) & 0x01;
2170     // TODO: fix dv encoder to set proper FF/FS value in VSC pack
2171     // and set field dominance accordingly
2172     // av_log(s, AV_LOG_DEBUG, "DV vsc pack ff/ss = %x\n", vsc_pack[2] >> 6);
2173
2174     switch (stype) {
2175     case 0x18: // DV100 720p
2176         ul_index = 8+pal;
2177         if (sc->interlaced) {
2178             av_log(s, AV_LOG_ERROR, "source marked as interlaced but codec profile is progressive\n");
2179             sc->interlaced = 0;
2180         }
2181         break;
2182     case 0x14: // DV100 1080i
2183         ul_index = 6+pal;
2184         break;
2185     case 0x04: // DV50
2186         ul_index = 4+pal;
2187         break;
2188     default: // DV25
2189         if (!apt) { // IEC
2190             ul_index = 0+pal;
2191         } else {
2192             ul_index = 2+pal;
2193         }
2194     }
2195
2196     sc->container_ul = &mxf_dv_uls[ul_index].container_ul;
2197     sc->codec_ul = &mxf_dv_uls[ul_index].codec_ul;
2198
2199     sc->frame_size = pkt->size;
2200
2201     return 1;
2202 }
2203
2204 static const struct {
2205     UID uid;
2206     int frame_size;
2207     int profile;
2208     uint8_t interlaced;
2209     int intra_only; // 1 or 0 when there are separate UIDs for Long GOP and Intra, -1 when Intra/LGOP detection can be ignored
2210 } mxf_h264_codec_uls[] = {
2211     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x11,0x01 },      0,  66, 0, -1 }, // AVC Baseline
2212     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x20,0x01 },      0,  77, 0, -1 }, // AVC Main
2213     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x30,0x01 },      0,  88, 0, -1 }, // AVC Extended
2214     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x40,0x01 },      0, 100, 0, -1 }, // AVC High
2215     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x50,0x01 },      0, 110, 0,  0 }, // AVC High 10
2216     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x60,0x01 },      0, 122, 0,  0 }, // AVC High 422
2217     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x70,0x01 },      0, 244, 0,  0 }, // AVC High 444
2218     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x20,0x01 },      0, 110, 0,  1 }, // AVC High 10 Intra
2219     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x01 }, 232960, 110, 1,  1 }, // AVC High 10 Intra RP2027 Class 50 1080/59.94i
2220     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x02 }, 281088, 110, 1,  1 }, // AVC High 10 Intra RP2027 Class 50 1080/50i
2221     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x03 }, 232960, 110, 0,  1 }, // AVC High 10 Intra RP2027 Class 50 1080/29.97p
2222     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x04 }, 281088, 110, 0,  1 }, // AVC High 10 Intra RP2027 Class 50 1080/25p
2223     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x08 }, 116736, 110, 0,  1 }, // AVC High 10 Intra RP2027 Class 50 720/59.94p
2224     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x09 }, 140800, 110, 0,  1 }, // AVC High 10 Intra RP2027 Class 50 720/50p
2225     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x30,0x01 },      0, 122, 0,  1 }, // AVC High 422 Intra
2226     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x01 }, 472576, 122, 1,  1 }, // AVC High 422 Intra RP2027 Class 100 1080/59.94i
2227     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x02 }, 568832, 122, 1,  1 }, // AVC High 422 Intra RP2027 Class 100 1080/50i
2228     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x03 }, 472576, 122, 0,  1 }, // AVC High 422 Intra RP2027 Class 100 1080/29.97p
2229     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x04 }, 568832, 122, 0,  1 }, // AVC High 422 Intra RP2027 Class 100 1080/25p
2230     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x08 }, 236544, 122, 0,  1 }, // AVC High 422 Intra RP2027 Class 100 720/59.94p
2231     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x31,0x09 }, 284672, 122, 0,  1 }, // AVC High 422 Intra RP2027 Class 100 720/50p
2232     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x01,0x32,0x40,0x01 },      0, 244, 0,  1 }, // AVC High 444 Intra
2233     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x01,0x32,0x50,0x01 },      0,  44, 0, -1 }, // AVC CAVLC 444
2234 };
2235
2236 static int mxf_parse_h264_frame(AVFormatContext *s, AVStream *st,
2237                                 AVPacket *pkt, MXFIndexEntry *e)
2238 {
2239     MXFContext *mxf = s->priv_data;
2240     MXFStreamContext *sc = st->priv_data;
2241     H264SPS seq, *const sps = &seq;
2242     GetBitContext gb;
2243     const uint8_t *buf = pkt->data;
2244     const uint8_t *buf_end = pkt->data + pkt->size;
2245     const uint8_t *nal_end;
2246     const UID *codec_ul = NULL;
2247     uint32_t state = -1;
2248     int extra_size = 512; // support AVC Intra files without SPS/PPS header
2249     int i, frame_size, slice_type, has_sps = 0, intra_only = 0, ret;
2250
2251     for (;;) {
2252         buf = avpriv_find_start_code(buf, buf_end, &state);
2253         if (buf >= buf_end)
2254             break;
2255
2256         switch (state & 0x1f) {
2257         case H264_NAL_SPS:
2258             e->flags |= 0x40;
2259
2260             if (mxf->header_written)
2261                 break;
2262
2263             nal_end = ff_avc_find_startcode(buf, buf_end);
2264             ret = ff_avc_decode_sps(sps, buf, nal_end - buf);
2265             if (ret < 0) {
2266                 av_log(s, AV_LOG_ERROR, "error parsing sps\n");
2267                 return 0;
2268             }
2269             has_sps = 1;
2270
2271             sc->aspect_ratio.num = st->codecpar->width * sps->sar.num;
2272             sc->aspect_ratio.den = st->codecpar->height * sps->sar.den;
2273             av_reduce(&sc->aspect_ratio.num, &sc->aspect_ratio.den,
2274                       sc->aspect_ratio.num, sc->aspect_ratio.den, 1024*1024);
2275             intra_only = (sps->constraint_set_flags >> 3) & 1;
2276             sc->interlaced = !sps->frame_mbs_only_flag;
2277             sc->component_depth = sps->bit_depth_luma;
2278
2279             buf = nal_end;
2280             break;
2281         case H264_NAL_PPS:
2282             if (e->flags & 0x40) { // sequence header present
2283                 e->flags |= 0x80; // random access
2284                 extra_size = 0;
2285             }
2286             break;
2287         case H264_NAL_IDR_SLICE:
2288             e->flags |= 0x04; // IDR Picture
2289             buf = buf_end;
2290             break;
2291         case H264_NAL_SLICE:
2292             init_get_bits8(&gb, buf, buf_end - buf);
2293             get_ue_golomb_long(&gb); // skip first_mb_in_slice
2294             slice_type = get_ue_golomb_31(&gb);
2295             switch (slice_type % 5) {
2296             case 0:
2297                 e->flags |= 0x20; // P Picture
2298                 e->flags |= 0x06; // P Picture
2299                 break;
2300             case 1:
2301                 e->flags |= 0x30; // B Picture
2302                 e->flags |= 0x03; // non-referenced B Picture
2303                 break;
2304             }
2305             buf = buf_end;
2306             break;
2307         default:
2308             break;
2309         }
2310     }
2311
2312     if (mxf->header_written)
2313         return 1;
2314
2315     if (!has_sps)
2316         sc->interlaced = st->codecpar->field_order != AV_FIELD_PROGRESSIVE ? 1 : 0;
2317     frame_size = pkt->size + extra_size;
2318
2319     for (i = 0; i < FF_ARRAY_ELEMS(mxf_h264_codec_uls); i++) {
2320         if (frame_size == mxf_h264_codec_uls[i].frame_size && sc->interlaced == mxf_h264_codec_uls[i].interlaced) {
2321             codec_ul = &mxf_h264_codec_uls[i].uid;
2322             sc->component_depth = 10; // AVC Intra is always 10 Bit
2323             sc->aspect_ratio = (AVRational){ 16, 9 }; // 16:9 is mandatory for broadcast HD
2324             st->codecpar->profile = mxf_h264_codec_uls[i].profile;
2325             sc->avc_intra = 1;
2326             mxf->cbr_index = 1;
2327             sc->frame_size = pkt->size;
2328             if (sc->interlaced)
2329                 sc->field_dominance = 1; // top field first is mandatory for AVC Intra
2330             break;
2331         } else if (has_sps && mxf_h264_codec_uls[i].frame_size == 0 &&
2332                    mxf_h264_codec_uls[i].profile == sps->profile_idc &&
2333                    (mxf_h264_codec_uls[i].intra_only < 0 ||
2334                     mxf_h264_codec_uls[i].intra_only == intra_only)) {
2335             codec_ul = &mxf_h264_codec_uls[i].uid;
2336             st->codecpar->profile = sps->profile_idc;
2337             st->codecpar->level = sps->level_idc;
2338             // continue to check for avc intra
2339         }
2340     }
2341
2342     if (!codec_ul) {
2343         av_log(s, AV_LOG_ERROR, "h264 profile not supported\n");
2344         return 0;
2345     }
2346     sc->codec_ul = codec_ul;
2347
2348     return 1;
2349 }
2350
2351 static const UID mxf_mpeg2_codec_uls[] = {
2352     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x10,0x00 }, // MP-ML I-Frame
2353     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, // MP-ML Long GOP
2354     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, // 422P-ML I-Frame
2355     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, // 422P-ML Long GOP
2356     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x02,0x00 }, // MP-HL I-Frame
2357     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, // MP-HL Long GOP
2358     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, // 422P-HL I-Frame
2359     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, // 422P-HL Long GOP
2360     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x05,0x02,0x00 }, // MP@H-14 I-Frame
2361     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x05,0x03,0x00 }, // MP@H-14 Long GOP
2362 };
2363
2364 static const UID *mxf_get_mpeg2_codec_ul(AVCodecParameters *par)
2365 {
2366     int long_gop = 1;
2367
2368     if (par->profile == 4) { // Main
2369         if (par->level == 8) // Main
2370             return &mxf_mpeg2_codec_uls[0+long_gop];
2371         else if (par->level == 4) // High
2372             return &mxf_mpeg2_codec_uls[4+long_gop];
2373         else if (par->level == 6) // High 14
2374             return &mxf_mpeg2_codec_uls[8+long_gop];
2375     } else if (par->profile == 0) { // 422
2376         if (par->level == 5) // Main
2377             return &mxf_mpeg2_codec_uls[2+long_gop];
2378         else if (par->level == 2) // High
2379             return &mxf_mpeg2_codec_uls[6+long_gop];
2380     }
2381     return NULL;
2382 }
2383
2384 static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st,
2385                                  AVPacket *pkt, MXFIndexEntry *e)
2386 {
2387     MXFStreamContext *sc = st->priv_data;
2388     uint32_t c = -1;
2389     int i;
2390
2391     for(i = 0; i < pkt->size - 4; i++) {
2392         c = (c<<8) + pkt->data[i];
2393         if (c == 0x1b5) {
2394             if ((pkt->data[i+1] & 0xf0) == 0x10) { // seq ext
2395                 st->codecpar->profile = pkt->data[i+1] & 0x07;
2396                 st->codecpar->level   = pkt->data[i+2] >> 4;
2397                 sc->low_delay = pkt->data[i+6] >> 7;
2398             } else if (i + 5 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x80) { // pict coding ext
2399                 sc->interlaced = !(pkt->data[i+5] & 0x80); // progressive frame
2400                 if (sc->interlaced)
2401                     sc->field_dominance = 1 + !(pkt->data[i+4] & 0x80); // top field first
2402                 break;
2403             }
2404         } else if (c == 0x1b8) { // gop
2405             if (pkt->data[i+4]>>6 & 0x01) { // closed
2406                 if (sc->seq_closed_gop == -1)
2407                     sc->seq_closed_gop = 1;
2408                 sc->closed_gop = 1;
2409                 if (e->flags & 0x40) // sequence header present
2410                     e->flags |= 0x80; // random access
2411             } else {
2412                 sc->seq_closed_gop = 0;
2413                 sc->closed_gop = 0;
2414             }
2415         } else if (c == 0x1b3) { // seq
2416             e->flags |= 0x40;
2417             switch ((pkt->data[i+4]>>4) & 0xf) {
2418             case 2:  sc->aspect_ratio = (AVRational){  4,  3}; break;
2419             case 3:  sc->aspect_ratio = (AVRational){ 16,  9}; break;
2420             case 4:  sc->aspect_ratio = (AVRational){221,100}; break;
2421             default:
2422                 av_reduce(&sc->aspect_ratio.num, &sc->aspect_ratio.den,
2423                           st->codecpar->width, st->codecpar->height, 1024*1024);
2424             }
2425         } else if (c == 0x100) { // pic
2426             int pict_type = (pkt->data[i+2]>>3) & 0x07;
2427             e->temporal_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
2428             if (pict_type == 2) { // P-frame
2429                 e->flags |= 0x22;
2430                 sc->closed_gop = 0; // reset closed GOP, don't matter anymore
2431             } else if (pict_type == 3) { // B-frame
2432                 if (sc->closed_gop)
2433                     e->flags |= 0x13; // only backward prediction
2434                 else
2435                     e->flags |= 0x33;
2436                 sc->temporal_reordering = -1;
2437             } else if (!pict_type) {
2438                 av_log(s, AV_LOG_ERROR, "error parsing mpeg2 frame\n");
2439                 return 0;
2440             }
2441         }
2442     }
2443     if (s->oformat != &ff_mxf_d10_muxer) {
2444         const UID *codec_ul = mxf_get_mpeg2_codec_ul(st->codecpar);
2445         if (!codec_ul)
2446             return 0;
2447         sc->codec_ul = codec_ul;
2448     }
2449     return 1;
2450 }
2451
2452 static uint64_t mxf_parse_timestamp(int64_t timestamp64)
2453 {
2454     time_t timestamp = timestamp64 / 1000000;
2455     struct tm tmbuf;
2456     struct tm *time = gmtime_r(&timestamp, &tmbuf);
2457     if (!time)
2458         return 0;
2459     return (uint64_t)(time->tm_year+1900) << 48 |
2460            (uint64_t)(time->tm_mon+1)     << 40 |
2461            (uint64_t) time->tm_mday       << 32 |
2462                       time->tm_hour       << 24 |
2463                       time->tm_min        << 16 |
2464                       time->tm_sec        << 8  |
2465                       (timestamp64 % 1000000) / 4000;
2466 }
2467
2468 static void mxf_gen_umid(AVFormatContext *s)
2469 {
2470     MXFContext *mxf = s->priv_data;
2471     uint32_t seed = av_get_random_seed();
2472     uint64_t umid = seed + 0x5294713400000000LL;
2473
2474     AV_WB64(mxf->umid  , umid);
2475     AV_WB64(mxf->umid+8, umid>>8);
2476
2477     mxf->instance_number = seed & 0xFFFFFF;
2478 }
2479
2480 static int mxf_init_timecode(AVFormatContext *s, AVStream *st, AVRational tbc)
2481 {
2482     MXFContext *mxf = s->priv_data;
2483     AVDictionaryEntry *tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
2484
2485     if (!ff_mxf_get_content_package_rate(tbc)) {
2486         if (s->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL) {
2487             av_log(s, AV_LOG_ERROR, "Unsupported frame rate %d/%d. Set -strict option to 'unofficial' or lower in order to allow it!\n", tbc.den, tbc.num);
2488             return AVERROR(EINVAL);
2489         } else {
2490             av_log(s, AV_LOG_WARNING, "Unofficial frame rate %d/%d.\n", tbc.den, tbc.num);
2491         }
2492     }
2493
2494     mxf->timecode_base = (tbc.den + tbc.num/2) / tbc.num;
2495     if (!tcr)
2496         tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
2497
2498     if (tcr)
2499         return av_timecode_init_from_string(&mxf->tc, av_inv_q(tbc), tcr->value, s);
2500     else
2501         return av_timecode_init(&mxf->tc, av_inv_q(tbc), 0, 0, s);
2502 }
2503
2504 static int mxf_write_header(AVFormatContext *s)
2505 {
2506     MXFContext *mxf = s->priv_data;
2507     int i, ret;
2508     uint8_t present[FF_ARRAY_ELEMS(mxf_essence_container_uls)] = {0};
2509     int64_t timestamp = 0;
2510
2511     if (!s->nb_streams)
2512         return -1;
2513
2514     if (s->oformat == &ff_mxf_opatom_muxer && s->nb_streams !=1) {
2515         av_log(s, AV_LOG_ERROR, "there must be exactly one stream for mxf opatom\n");
2516         return -1;
2517     }
2518
2519     if (!av_dict_get(s->metadata, "comment_", NULL, AV_DICT_IGNORE_SUFFIX))
2520         mxf->store_user_comments = 0;
2521
2522     for (i = 0; i < s->nb_streams; i++) {
2523         AVStream *st = s->streams[i];
2524         MXFStreamContext *sc = av_mallocz(sizeof(*sc));
2525         if (!sc)
2526             return AVERROR(ENOMEM);
2527         st->priv_data = sc;
2528         sc->index = -1;
2529
2530         if (((i == 0) ^ (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)) && s->oformat != &ff_mxf_opatom_muxer) {
2531             av_log(s, AV_LOG_ERROR, "there must be exactly one video stream and it must be the first one\n");
2532             return -1;
2533         }
2534
2535         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2536             const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(st->codecpar->format);
2537             // TODO: should be avg_frame_rate
2538             AVRational tbc = st->time_base;
2539             // Default component depth to 8
2540             sc->component_depth = 8;
2541             sc->h_chroma_sub_sample = 2;
2542             sc->v_chroma_sub_sample = 2;
2543             sc->color_siting = 0xFF;
2544
2545             if (st->codecpar->sample_aspect_ratio.num && st->codecpar->sample_aspect_ratio.den) {
2546                 sc->aspect_ratio = av_mul_q(st->codecpar->sample_aspect_ratio,
2547                                             av_make_q(st->codecpar->width, st->codecpar->height));
2548             }
2549
2550             if (pix_desc) {
2551                 sc->component_depth     = pix_desc->comp[0].depth;
2552                 sc->h_chroma_sub_sample = 1 << pix_desc->log2_chroma_w;
2553                 sc->v_chroma_sub_sample = 1 << pix_desc->log2_chroma_h;
2554             }
2555             switch (ff_choose_chroma_location(s, st)) {
2556             case AVCHROMA_LOC_TOPLEFT: sc->color_siting = 0; break;
2557             case AVCHROMA_LOC_LEFT:    sc->color_siting = 6; break;
2558             case AVCHROMA_LOC_TOP:     sc->color_siting = 1; break;
2559             case AVCHROMA_LOC_CENTER:  sc->color_siting = 3; break;
2560             }
2561
2562             mxf->content_package_rate = ff_mxf_get_content_package_rate(tbc);
2563             mxf->time_base = tbc;
2564             avpriv_set_pts_info(st, 64, mxf->time_base.num, mxf->time_base.den);
2565             if((ret = mxf_init_timecode(s, st, tbc)) < 0)
2566                 return ret;
2567
2568             if (st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
2569                 sc->seq_closed_gop = -1; // unknown yet
2570             }
2571
2572             sc->video_bit_rate = st->codecpar->bit_rate;
2573
2574             if (s->oformat == &ff_mxf_d10_muxer ||
2575                 st->codecpar->codec_id == AV_CODEC_ID_DNXHD ||
2576                 st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO)
2577                 mxf->cbr_index = 1;
2578
2579             if (s->oformat == &ff_mxf_d10_muxer) {
2580                 int ntsc = mxf->time_base.den != 25;
2581                 int ul_index;
2582
2583                 if (st->codecpar->codec_id != AV_CODEC_ID_MPEG2VIDEO) {
2584                     av_log(s, AV_LOG_ERROR, "error MXF D-10 only support MPEG-2 Video\n");
2585                     return AVERROR(EINVAL);
2586                 }
2587                 if ((sc->video_bit_rate == 50000000) && (mxf->time_base.den == 25)) {
2588                     ul_index = 0;
2589                 } else if ((sc->video_bit_rate == 49999840 || sc->video_bit_rate == 50000000) && ntsc) {
2590                     ul_index = 1;
2591                 } else if (sc->video_bit_rate == 40000000) {
2592                     ul_index = 2+ntsc;
2593                 } else if (sc->video_bit_rate == 30000000) {
2594                     ul_index = 4+ntsc;
2595                 } else {
2596                     av_log(s, AV_LOG_ERROR, "error MXF D-10 only support 30/40/50 mbit/s\n");
2597                     return -1;
2598                 }
2599
2600                 sc->codec_ul = &mxf_d10_codec_uls[ul_index];
2601                 sc->container_ul = &mxf_d10_container_uls[ul_index];
2602                 sc->index = INDEX_D10_VIDEO;
2603                 sc->signal_standard = 1;
2604                 sc->color_siting = 0;
2605                 sc->frame_size = (int64_t)sc->video_bit_rate *
2606                     mxf->time_base.num / (8*mxf->time_base.den);
2607             }
2608             if (mxf->signal_standard >= 0)
2609                 sc->signal_standard = mxf->signal_standard;
2610         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2611             char bsf_arg[32];
2612             if (st->codecpar->sample_rate != 48000) {
2613                 av_log(s, AV_LOG_ERROR, "only 48khz is implemented\n");
2614                 return -1;
2615             }
2616             avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
2617             if (s->oformat == &ff_mxf_d10_muxer) {
2618                 if (st->index != 1) {
2619                     av_log(s, AV_LOG_ERROR, "MXF D-10 only support one audio track\n");
2620                     return -1;
2621                 }
2622                 if (st->codecpar->codec_id != AV_CODEC_ID_PCM_S16LE &&
2623                     st->codecpar->codec_id != AV_CODEC_ID_PCM_S24LE) {
2624                     av_log(s, AV_LOG_ERROR, "MXF D-10 only support 16 or 24 bits le audio\n");
2625                 }
2626                 sc->index = INDEX_D10_AUDIO;
2627                 sc->container_ul = ((MXFStreamContext*)s->streams[0]->priv_data)->container_ul;
2628                 sc->frame_size = 4 + 8 * av_rescale_rnd(st->codecpar->sample_rate, mxf->time_base.num, mxf->time_base.den, AV_ROUND_UP) * 4;
2629             } else if (s->oformat == &ff_mxf_opatom_muxer) {
2630                 AVRational tbc = av_inv_q(mxf->audio_edit_rate);
2631
2632                 if (st->codecpar->codec_id != AV_CODEC_ID_PCM_S16LE &&
2633                     st->codecpar->codec_id != AV_CODEC_ID_PCM_S24LE) {
2634                     av_log(s, AV_LOG_ERROR, "Only pcm_s16le and pcm_s24le audio codecs are implemented\n");
2635                     return AVERROR_PATCHWELCOME;
2636                 }
2637                 if (st->codecpar->channels != 1) {
2638                     av_log(s, AV_LOG_ERROR, "MXF OPAtom only supports single channel audio\n");
2639                     return AVERROR(EINVAL);
2640                 }
2641
2642                 mxf->time_base = st->time_base;
2643                 if((ret = mxf_init_timecode(s, st, tbc)) < 0)
2644                     return ret;
2645
2646                 mxf->edit_unit_byte_count = (av_get_bits_per_sample(st->codecpar->codec_id) * st->codecpar->channels) >> 3;
2647                 sc->index = INDEX_WAV;
2648             } else {
2649                 mxf->slice_count = 1;
2650                 sc->frame_size = st->codecpar->channels *
2651                                  av_rescale_rnd(st->codecpar->sample_rate, mxf->time_base.num, mxf->time_base.den, AV_ROUND_UP) *
2652                                  av_get_bits_per_sample(st->codecpar->codec_id) / 8;
2653             }
2654             snprintf(bsf_arg, sizeof(bsf_arg), "r=%d/%d", mxf->tc.rate.num, mxf->tc.rate.den);
2655             ret = ff_stream_add_bitstream_filter(st, "pcm_rechunk", bsf_arg);
2656             if (ret < 0)
2657                 return ret;
2658         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
2659             AVDictionaryEntry *e = av_dict_get(st->metadata, "data_type", NULL, 0);
2660             if (e && !strcmp(e->value, "vbi_vanc_smpte_436M")) {
2661                 sc->index = INDEX_S436M;
2662             } else {
2663                 av_log(s, AV_LOG_ERROR, "track %d: unsupported data type\n", i);
2664                 return -1;
2665             }
2666             if (st->index != s->nb_streams - 1) {
2667                 av_log(s, AV_LOG_ERROR, "data track must be placed last\n");
2668                 return -1;
2669             }
2670         }
2671
2672         if (sc->index == -1) {
2673             sc->index = mxf_get_essence_container_ul_index(st->codecpar->codec_id);
2674             if (sc->index == -1) {
2675                 av_log(s, AV_LOG_ERROR, "track %d: could not find essence container ul, "
2676                        "codec not currently supported in container\n", i);
2677                 return -1;
2678             }
2679         }
2680
2681         if (!sc->codec_ul)
2682             sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
2683         if (!sc->container_ul)
2684             sc->container_ul = &mxf_essence_container_uls[sc->index].container_ul;
2685
2686         memcpy(sc->track_essence_element_key, mxf_essence_container_uls[sc->index].element_ul, 15);
2687         sc->track_essence_element_key[15] = present[sc->index];
2688         PRINT_KEY(s, "track essence element key", sc->track_essence_element_key);
2689
2690         if (!present[sc->index])
2691             mxf->essence_container_count++;
2692         present[sc->index]++;
2693     }
2694
2695     if (s->oformat == &ff_mxf_d10_muxer || s->oformat == &ff_mxf_opatom_muxer) {
2696         mxf->essence_container_count = 1;
2697     }
2698
2699     if (!(s->flags & AVFMT_FLAG_BITEXACT))
2700         mxf_gen_umid(s);
2701
2702     for (i = 0; i < s->nb_streams; i++) {
2703         MXFStreamContext *sc = s->streams[i]->priv_data;
2704         // update element count
2705         sc->track_essence_element_key[13] = present[sc->index];
2706         if (!memcmp(sc->track_essence_element_key, mxf_essence_container_uls[INDEX_DV].element_ul, 13)) // DV
2707             sc->order = (0x15 << 24) | AV_RB32(sc->track_essence_element_key+13);
2708         else
2709             sc->order = AV_RB32(sc->track_essence_element_key+12);
2710     }
2711
2712     if (ff_parse_creation_time_metadata(s, &timestamp, 0) > 0)
2713         mxf->timestamp = mxf_parse_timestamp(timestamp);
2714     mxf->duration = -1;
2715
2716     mxf->timecode_track = av_mallocz(sizeof(*mxf->timecode_track));
2717     if (!mxf->timecode_track)
2718         return AVERROR(ENOMEM);
2719     mxf->timecode_track->priv_data = av_mallocz(sizeof(MXFStreamContext));
2720     if (!mxf->timecode_track->priv_data)
2721         return AVERROR(ENOMEM);
2722     mxf->timecode_track->index = -1;
2723
2724     return 0;
2725 }
2726
2727 static const uint8_t system_metadata_pack_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04,0x01,0x01,0x00 };
2728 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 };
2729
2730 static void mxf_write_system_item(AVFormatContext *s)
2731 {
2732     MXFContext *mxf = s->priv_data;
2733     AVIOContext *pb = s->pb;
2734     unsigned frame;
2735     uint32_t time_code;
2736     int i, system_item_bitmap = 0x58; // UL, user date/time stamp, picture present
2737
2738     frame = mxf->last_indexed_edit_unit + mxf->edit_units_count;
2739
2740     // write system metadata pack
2741     avio_write(pb, system_metadata_pack_key, 16);
2742     klv_encode_ber4_length(pb, 57);
2743
2744     for (i = 0; i < s->nb_streams; i++) {
2745         if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
2746             system_item_bitmap |= 0x4;
2747         else if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_DATA)
2748             system_item_bitmap |= 0x2;
2749     }
2750     avio_w8(pb, system_item_bitmap);
2751     avio_w8(pb, mxf->content_package_rate); // content package rate
2752     avio_w8(pb, 0x00); // content package type
2753     avio_wb16(pb, 0x00); // channel handle
2754     avio_wb16(pb, frame & 0xFFFF); // continuity count, supposed to overflow
2755     if (mxf->essence_container_count > 1)
2756         avio_write(pb, multiple_desc_ul, 16);
2757     else {
2758         MXFStreamContext *sc = s->streams[0]->priv_data;
2759         avio_write(pb, *sc->container_ul, 16);
2760     }
2761     avio_w8(pb, 0);
2762     avio_wb64(pb, 0);
2763     avio_wb64(pb, 0); // creation date/time stamp
2764
2765     avio_w8(pb, 0x81); // SMPTE 12M time code
2766     time_code = av_timecode_get_smpte_from_framenum(&mxf->tc, frame);
2767     avio_wb32(pb, time_code);
2768     avio_wb32(pb, 0); // binary group data
2769     avio_wb64(pb, 0);
2770
2771     // write system metadata package set
2772     avio_write(pb, system_metadata_package_set_key, 16);
2773     klv_encode_ber4_length(pb, 35);
2774     avio_w8(pb, 0x83); // UMID
2775     avio_wb16(pb, 0x20);
2776     mxf_write_umid(s, 1);
2777 }
2778
2779 static void mxf_write_d10_audio_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt)
2780 {
2781     MXFContext *mxf = s->priv_data;
2782     AVIOContext *pb = s->pb;
2783     int frame_size = pkt->size / st->codecpar->block_align;
2784     uint8_t *samples = pkt->data;
2785     uint8_t *end = pkt->data + pkt->size;
2786     int i;
2787
2788     klv_encode_ber4_length(pb, 4 + frame_size*4*8);
2789
2790     avio_w8(pb, (frame_size == 1920 ? 0 : (mxf->edit_units_count-1) % 5 + 1));
2791     avio_wl16(pb, frame_size);
2792     avio_w8(pb, (1<<st->codecpar->channels)-1);
2793
2794     while (samples < end) {
2795         for (i = 0; i < st->codecpar->channels; i++) {
2796             uint32_t sample;
2797             if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S24LE) {
2798                 sample = AV_RL24(samples)<< 4;
2799                 samples += 3;
2800             } else {
2801                 sample = AV_RL16(samples)<<12;
2802                 samples += 2;
2803             }
2804             avio_wl32(pb, sample | i);
2805         }
2806         for (; i < 8; i++)
2807             avio_wl32(pb, i);
2808     }
2809 }
2810
2811 static int mxf_write_opatom_body_partition(AVFormatContext *s)
2812 {
2813     MXFContext *mxf = s->priv_data;
2814     AVIOContext *pb = s->pb;
2815     AVStream *st = s->streams[0];
2816     MXFStreamContext *sc = st->priv_data;
2817     const uint8_t *key = NULL;
2818
2819     int err;
2820
2821     if (!mxf->header_written)
2822         key = body_partition_key;
2823
2824     if ((err = mxf_write_partition(s, 1, 0, key, 0)) < 0)
2825         return err;
2826     mxf_write_klv_fill(s);
2827     avio_write(pb, sc->track_essence_element_key, 16);
2828     klv_encode_ber9_length(pb, mxf->body_offset);
2829     return 0;
2830 }
2831
2832 static int mxf_write_opatom_packet(AVFormatContext *s, AVPacket *pkt, MXFIndexEntry *ie)
2833 {
2834     MXFContext *mxf = s->priv_data;
2835     AVIOContext *pb = s->pb;
2836
2837     int err;
2838
2839     if (!mxf->header_written) {
2840         if ((err = mxf_write_partition(s, 0, 0, header_open_partition_key, 1)) < 0)
2841             return err;
2842         mxf_write_klv_fill(s);
2843
2844         if ((err = mxf_write_opatom_body_partition(s)) < 0)
2845             return err;
2846         mxf->header_written = 1;
2847     }
2848
2849     if (!mxf->edit_unit_byte_count) {
2850         mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;
2851         mxf->index_entries[mxf->edit_units_count].flags = ie->flags;
2852         mxf->index_entries[mxf->edit_units_count].temporal_ref = ie->temporal_ref;
2853     }
2854     mxf->edit_units_count++;
2855     avio_write(pb, pkt->data, pkt->size);
2856     mxf->body_offset += pkt->size;
2857
2858     return 0;
2859 }
2860
2861 static void mxf_compute_edit_unit_byte_count(AVFormatContext *s)
2862 {
2863     MXFContext *mxf = s->priv_data;
2864     int i;
2865
2866     if (s->oformat == &ff_mxf_opatom_muxer) {
2867         MXFStreamContext *sc = s->streams[0]->priv_data;
2868         mxf->edit_unit_byte_count = sc->frame_size;
2869         return;
2870     }
2871
2872     mxf->edit_unit_byte_count = KAG_SIZE; // system element
2873     for (i = 0; i < s->nb_streams; i++) {
2874         AVStream *st = s->streams[i];
2875         MXFStreamContext *sc = st->priv_data;
2876         sc->slice_offset = mxf->edit_unit_byte_count;
2877         mxf->edit_unit_byte_count += 16 + 4 + sc->frame_size;
2878         mxf->edit_unit_byte_count += klv_fill_size(mxf->edit_unit_byte_count);
2879     }
2880 }
2881
2882 static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
2883 {
2884     MXFContext *mxf = s->priv_data;
2885     AVIOContext *pb = s->pb;
2886     AVStream *st = s->streams[pkt->stream_index];
2887     MXFStreamContext *sc = st->priv_data;
2888     MXFIndexEntry ie = {0};
2889     int err;
2890
2891     if (!mxf->header_written && pkt->stream_index != 0 &&
2892         s->oformat != &ff_mxf_opatom_muxer) {
2893         av_log(s, AV_LOG_ERROR, "Received non-video packet before "
2894                                 "header has been written\n");
2895         return AVERROR_INVALIDDATA;
2896     }
2897
2898     if (!mxf->cbr_index && !mxf->edit_unit_byte_count && !(mxf->edit_units_count % EDIT_UNITS_PER_BODY)) {
2899         if ((err = av_reallocp_array(&mxf->index_entries, mxf->edit_units_count
2900                                      + EDIT_UNITS_PER_BODY, sizeof(*mxf->index_entries))) < 0) {
2901             mxf->edit_units_count = 0;
2902             av_log(s, AV_LOG_ERROR, "could not allocate index entries\n");
2903             return err;
2904         }
2905     }
2906
2907     if (st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
2908         if (!mxf_parse_mpeg2_frame(s, st, pkt, &ie)) {
2909             av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
2910             return -1;
2911         }
2912     } else if (st->codecpar->codec_id == AV_CODEC_ID_DNXHD) {
2913         if (!mxf_parse_dnxhd_frame(s, st, pkt)) {
2914             av_log(s, AV_LOG_ERROR, "could not get dnxhd profile\n");
2915             return -1;
2916         }
2917     } else if (st->codecpar->codec_id == AV_CODEC_ID_PRORES) {
2918         if (!mxf_parse_prores_frame(s, st, pkt)) {
2919             av_log(s, AV_LOG_ERROR, "could not get prores profile\n");
2920             return -1;
2921         }
2922     } else if (st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO) {
2923         if (!mxf_parse_dv_frame(s, st, pkt)) {
2924             av_log(s, AV_LOG_ERROR, "could not get dv profile\n");
2925             return -1;
2926         }
2927     } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
2928         if (!mxf_parse_h264_frame(s, st, pkt, &ie)) {
2929             av_log(s, AV_LOG_ERROR, "could not get h264 profile\n");
2930             return -1;
2931         }
2932     }
2933
2934     if (mxf->cbr_index) {
2935         if (pkt->size != sc->frame_size && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2936             av_log(s, AV_LOG_ERROR, "track %d: frame size does not match index unit size, %d != %d\n",
2937                    st->index, pkt->size, sc->frame_size);
2938             return -1;
2939         }
2940         if (!mxf->header_written)
2941             mxf_compute_edit_unit_byte_count(s);
2942     }
2943
2944     if (s->oformat == &ff_mxf_opatom_muxer)
2945         return mxf_write_opatom_packet(s, pkt, &ie);
2946
2947     if (!mxf->header_written) {
2948         if (mxf->edit_unit_byte_count) {
2949             if ((err = mxf_write_partition(s, 1, 2, header_open_partition_key, 1)) < 0)
2950                 return err;
2951             mxf_write_klv_fill(s);
2952             mxf_write_index_table_segment(s);
2953         } else {
2954             if ((err = mxf_write_partition(s, 0, 0, header_open_partition_key, 1)) < 0)
2955                 return err;
2956         }
2957         mxf->header_written = 1;
2958     }
2959
2960     if (st->index == 0) {
2961         if (!mxf->edit_unit_byte_count &&
2962             (!mxf->edit_units_count || mxf->edit_units_count > EDIT_UNITS_PER_BODY) &&
2963             !(ie.flags & 0x33)) { // I-frame, GOP start
2964             mxf_write_klv_fill(s);
2965             if ((err = mxf_write_partition(s, 1, 2, body_partition_key, 0)) < 0)
2966                 return err;
2967             mxf_write_klv_fill(s);
2968             mxf_write_index_table_segment(s);
2969         }
2970
2971         mxf_write_klv_fill(s);
2972         mxf_write_system_item(s);
2973
2974         if (!mxf->edit_unit_byte_count) {
2975             mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;
2976             mxf->index_entries[mxf->edit_units_count].flags = ie.flags;
2977             mxf->index_entries[mxf->edit_units_count].temporal_ref = ie.temporal_ref;
2978             mxf->body_offset += KAG_SIZE; // size of system element
2979         }
2980         mxf->edit_units_count++;
2981     } else if (!mxf->edit_unit_byte_count && st->index == 1) {
2982         if (!mxf->edit_units_count) {
2983             av_log(s, AV_LOG_ERROR, "No packets in first stream\n");
2984             return AVERROR_PATCHWELCOME;
2985         }
2986         mxf->index_entries[mxf->edit_units_count-1].slice_offset =
2987             mxf->body_offset - mxf->index_entries[mxf->edit_units_count-1].offset;
2988     }
2989
2990     mxf_write_klv_fill(s);
2991     avio_write(pb, sc->track_essence_element_key, 16); // write key
2992     if (s->oformat == &ff_mxf_d10_muxer &&
2993         st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2994         mxf_write_d10_audio_packet(s, st, pkt);
2995     } else {
2996         klv_encode_ber4_length(pb, pkt->size); // write length
2997         avio_write(pb, pkt->data, pkt->size);
2998         mxf->body_offset += 16+4+pkt->size + klv_fill_size(16+4+pkt->size);
2999     }
3000
3001     return 0;
3002 }
3003
3004 static void mxf_write_random_index_pack(AVFormatContext *s)
3005 {
3006     MXFContext *mxf = s->priv_data;
3007     AVIOContext *pb = s->pb;
3008     uint64_t pos = avio_tell(pb);
3009     int i;
3010
3011     avio_write(pb, ff_mxf_random_index_pack_key, 16);
3012     klv_encode_ber_length(pb, 28 + 12LL*mxf->body_partitions_count);
3013
3014     if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer)
3015         avio_wb32(pb, 1); // BodySID of header partition
3016     else
3017         avio_wb32(pb, 0);
3018     avio_wb64(pb, 0); // offset of header partition
3019
3020     for (i = 0; i < mxf->body_partitions_count; i++) {
3021         avio_wb32(pb, 1); // BodySID
3022         avio_wb64(pb, mxf->body_partition_offset[i]);
3023     }
3024
3025     avio_wb32(pb, 0); // BodySID of footer partition
3026     avio_wb64(pb, mxf->footer_partition_offset);
3027
3028     avio_wb32(pb, avio_tell(pb) - pos + 4);
3029 }
3030
3031 static int mxf_write_footer(AVFormatContext *s)
3032 {
3033     MXFContext *mxf = s->priv_data;
3034     AVIOContext *pb = s->pb;
3035     int i, err;
3036
3037     if (!mxf->header_written ||
3038         (s->oformat == &ff_mxf_opatom_muxer && !mxf->body_partition_offset)) {
3039         /* reason could be invalid options/not supported codec/out of memory */
3040         return AVERROR_UNKNOWN;
3041     }
3042
3043     mxf->duration = mxf->last_indexed_edit_unit + mxf->edit_units_count;
3044
3045     mxf_write_klv_fill(s);
3046     mxf->footer_partition_offset = avio_tell(pb);
3047     if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer) { // no need to repeat index
3048         if ((err = mxf_write_partition(s, 0, 0, footer_partition_key, 0)) < 0)
3049             return err;
3050     } else {
3051         if ((err = mxf_write_partition(s, 0, 2, footer_partition_key, 0)) < 0)
3052             return err;
3053         mxf_write_klv_fill(s);
3054         mxf_write_index_table_segment(s);
3055     }
3056
3057     mxf_write_klv_fill(s);
3058     mxf_write_random_index_pack(s);
3059
3060     if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
3061         if (s->oformat == &ff_mxf_opatom_muxer) {
3062             /* rewrite body partition to update lengths */
3063             avio_seek(pb, mxf->body_partition_offset[0], SEEK_SET);
3064             if ((err = mxf_write_opatom_body_partition(s)) < 0)
3065                 return err;
3066         }
3067
3068         avio_seek(pb, 0, SEEK_SET);
3069         if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer) {
3070             if ((err = mxf_write_partition(s, 1, 2, header_closed_partition_key, 1)) < 0)
3071                 return err;
3072             mxf_write_klv_fill(s);
3073             mxf_write_index_table_segment(s);
3074         } else {
3075             if ((err = mxf_write_partition(s, 0, 0, header_closed_partition_key, 1)) < 0)
3076                 return err;
3077         }
3078         // update footer partition offset
3079         for (i = 0; i < mxf->body_partitions_count; i++) {
3080             avio_seek(pb, mxf->body_partition_offset[i]+44, SEEK_SET);
3081             avio_wb64(pb, mxf->footer_partition_offset);
3082         }
3083     }
3084
3085     return 0;
3086 }
3087
3088 static void mxf_deinit(AVFormatContext *s)
3089 {
3090     MXFContext *mxf = s->priv_data;
3091
3092     av_freep(&mxf->index_entries);
3093     av_freep(&mxf->body_partition_offset);
3094     if (mxf->timecode_track) {
3095         av_freep(&mxf->timecode_track->priv_data);
3096         av_freep(&mxf->timecode_track);
3097     }
3098 }
3099
3100 static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
3101 {
3102     int i, stream_count = 0;
3103
3104     for (i = 0; i < s->nb_streams; i++)
3105         stream_count += !!s->streams[i]->internal->last_in_packet_buffer;
3106
3107     if (stream_count && (s->nb_streams == stream_count || flush)) {
3108         PacketList *pktl = s->internal->packet_buffer;
3109         if (s->nb_streams != stream_count) {
3110             PacketList *last = NULL;
3111             // find last packet in edit unit
3112             while (pktl) {
3113                 if (!stream_count || pktl->pkt.stream_index == 0)
3114                     break;
3115                 // update last packet in packet buffer
3116                 if (s->streams[pktl->pkt.stream_index]->internal->last_in_packet_buffer != pktl)
3117                     s->streams[pktl->pkt.stream_index]->internal->last_in_packet_buffer = pktl;
3118                 last = pktl;
3119                 pktl = pktl->next;
3120                 stream_count--;
3121             }
3122             // purge packet queue
3123             while (pktl) {
3124                 PacketList *next = pktl->next;
3125                 av_packet_unref(&pktl->pkt);
3126                 av_freep(&pktl);
3127                 pktl = next;
3128             }
3129             if (last)
3130                 last->next = NULL;
3131             else {
3132                 s->internal->packet_buffer = NULL;
3133                 s->internal->packet_buffer_end= NULL;
3134                 goto out;
3135             }
3136             pktl = s->internal->packet_buffer;
3137         }
3138
3139         *out = pktl->pkt;
3140         av_log(s, AV_LOG_TRACE, "out st:%d dts:%"PRId64"\n", (*out).stream_index, (*out).dts);
3141         s->internal->packet_buffer = pktl->next;
3142         if(s->streams[pktl->pkt.stream_index]->internal->last_in_packet_buffer == pktl)
3143             s->streams[pktl->pkt.stream_index]->internal->last_in_packet_buffer= NULL;
3144         if(!s->internal->packet_buffer)
3145             s->internal->packet_buffer_end= NULL;
3146         av_freep(&pktl);
3147         return 1;
3148     } else {
3149     out:
3150         return 0;
3151     }
3152 }
3153
3154 static int mxf_compare_timestamps(AVFormatContext *s, const AVPacket *next,
3155                                                       const AVPacket *pkt)
3156 {
3157     MXFStreamContext *sc  = s->streams[pkt ->stream_index]->priv_data;
3158     MXFStreamContext *sc2 = s->streams[next->stream_index]->priv_data;
3159
3160     return next->dts > pkt->dts ||
3161         (next->dts == pkt->dts && sc->order < sc2->order);
3162 }
3163
3164 static int mxf_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
3165 {
3166     int ret;
3167     if (pkt) {
3168         MXFStreamContext *sc = s->streams[pkt->stream_index]->priv_data;
3169         pkt->pts = pkt->dts = sc->pkt_cnt++;
3170         if ((ret = ff_interleave_add_packet(s, pkt, mxf_compare_timestamps)) < 0)
3171             return ret;
3172     }
3173     return mxf_interleave_get_packet(s, out, NULL, flush);
3174 }
3175
3176 #define MXF_COMMON_OPTIONS \
3177     { "signal_standard", "Force/set Signal Standard",\
3178       offsetof(MXFContext, signal_standard), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3179     { "bt601", "ITU-R BT.601 and BT.656, also SMPTE 125M (525 and 625 line interlaced)",\
3180       0, AV_OPT_TYPE_CONST, {.i64 = 1}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3181     { "bt1358", "ITU-R BT.1358 and ITU-R BT.799-3, also SMPTE 293M (525 and 625 line progressive)",\
3182       0, AV_OPT_TYPE_CONST, {.i64 = 2}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3183     { "smpte347m", "SMPTE 347M (540 Mbps mappings)",\
3184       0, AV_OPT_TYPE_CONST, {.i64 = 3}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3185     { "smpte274m", "SMPTE 274M (1125 line)",\
3186       0, AV_OPT_TYPE_CONST, {.i64 = 4}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3187     { "smpte296m", "SMPTE 296M (750 line progressive)",\
3188       0, AV_OPT_TYPE_CONST, {.i64 = 5}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3189     { "smpte349m", "SMPTE 349M (1485 Mbps mappings)",\
3190       0, AV_OPT_TYPE_CONST, {.i64 = 6}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3191     { "smpte428", "SMPTE 428-1 DCDM",\
3192       0, AV_OPT_TYPE_CONST, {.i64 = 7}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},
3193
3194
3195
3196 static const AVOption mxf_options[] = {
3197     MXF_COMMON_OPTIONS
3198     { "store_user_comments", "",
3199       offsetof(MXFContext, store_user_comments), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
3200     { NULL },
3201 };
3202
3203 static const AVClass mxf_muxer_class = {
3204     .class_name     = "MXF muxer",
3205     .item_name      = av_default_item_name,
3206     .option         = mxf_options,
3207     .version        = LIBAVUTIL_VERSION_INT,
3208 };
3209
3210 static const AVOption d10_options[] = {
3211     { "d10_channelcount", "Force/set channelcount in generic sound essence descriptor",
3212       offsetof(MXFContext, channel_count), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 8, AV_OPT_FLAG_ENCODING_PARAM},
3213     MXF_COMMON_OPTIONS
3214     { "store_user_comments", "",
3215       offsetof(MXFContext, store_user_comments), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
3216     { NULL },
3217 };
3218
3219 static const AVClass mxf_d10_muxer_class = {
3220     .class_name     = "MXF-D10 muxer",
3221     .item_name      = av_default_item_name,
3222     .option         = d10_options,
3223     .version        = LIBAVUTIL_VERSION_INT,
3224 };
3225
3226 static const AVOption opatom_options[] = {
3227     { "mxf_audio_edit_rate", "Audio edit rate for timecode",
3228         offsetof(MXFContext, audio_edit_rate), AV_OPT_TYPE_RATIONAL, {.dbl=25}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
3229     MXF_COMMON_OPTIONS
3230     { "store_user_comments", "",
3231       offsetof(MXFContext, store_user_comments), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
3232     { NULL },
3233 };
3234
3235 static const AVClass mxf_opatom_muxer_class = {
3236     .class_name     = "MXF-OPAtom muxer",
3237     .item_name      = av_default_item_name,
3238     .option         = opatom_options,
3239     .version        = LIBAVUTIL_VERSION_INT,
3240 };
3241
3242 AVOutputFormat ff_mxf_muxer = {
3243     .name              = "mxf",
3244     .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format)"),
3245     .mime_type         = "application/mxf",
3246     .extensions        = "mxf",
3247     .priv_data_size    = sizeof(MXFContext),
3248     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
3249     .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
3250     .write_header      = mxf_write_header,
3251     .write_packet      = mxf_write_packet,
3252     .write_trailer     = mxf_write_footer,
3253     .deinit            = mxf_deinit,
3254     .flags             = AVFMT_NOTIMESTAMPS,
3255     .interleave_packet = mxf_interleave,
3256     .priv_class        = &mxf_muxer_class,
3257 };
3258
3259 AVOutputFormat ff_mxf_d10_muxer = {
3260     .name              = "mxf_d10",
3261     .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format) D-10 Mapping"),
3262     .mime_type         = "application/mxf",
3263     .priv_data_size    = sizeof(MXFContext),
3264     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
3265     .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
3266     .write_header      = mxf_write_header,
3267     .write_packet      = mxf_write_packet,
3268     .write_trailer     = mxf_write_footer,
3269     .deinit            = mxf_deinit,
3270     .flags             = AVFMT_NOTIMESTAMPS,
3271     .interleave_packet = mxf_interleave,
3272     .priv_class        = &mxf_d10_muxer_class,
3273 };
3274
3275 AVOutputFormat ff_mxf_opatom_muxer = {
3276     .name              = "mxf_opatom",
3277     .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format) Operational Pattern Atom"),
3278     .mime_type         = "application/mxf",
3279     .extensions        = "mxf",
3280     .priv_data_size    = sizeof(MXFContext),
3281     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
3282     .video_codec       = AV_CODEC_ID_DNXHD,
3283     .write_header      = mxf_write_header,
3284     .write_packet      = mxf_write_packet,
3285     .write_trailer     = mxf_write_footer,
3286     .deinit            = mxf_deinit,
3287     .flags             = AVFMT_NOTIMESTAMPS,
3288     .interleave_packet = mxf_interleave,
3289     .priv_class        = &mxf_opatom_muxer_class,
3290 };