• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 ST2019-4 (2009 or later) Mapping VC-3 Coding Units into the MXF Generic Container
36  * SMPTE RP210: SMPTE Metadata Dictionary
37  * SMPTE RP224: Registry of SMPTE Universal Labels
38  */
39 
40 #include <inttypes.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/golomb.h"
51 #include "libavcodec/h264.h"
52 #include "libavcodec/packet_internal.h"
53 #include "libavcodec/startcode.h"
54 #include "avformat.h"
55 #include "avio_internal.h"
56 #include "internal.h"
57 #include "avc.h"
58 #include "mux.h"
59 #include "mxf.h"
60 #include "config.h"
61 #include "version.h"
62 
63 extern const AVOutputFormat ff_mxf_d10_muxer;
64 extern const AVOutputFormat ff_mxf_opatom_muxer;
65 
66 #define EDIT_UNITS_PER_BODY 250
67 #define KAG_SIZE 512
68 
69 typedef struct MXFIndexEntry {
70     uint64_t offset;
71     unsigned slice_offset; ///< offset of audio slice
72     uint16_t temporal_ref;
73     uint8_t flags;
74 } MXFIndexEntry;
75 
76 typedef struct MXFStreamContext {
77     int64_t pkt_cnt;         ///< pkt counter for muxed packets
78     UID track_essence_element_key;
79     int index;               ///< index in mxf_essence_container_uls table
80     const UID *codec_ul;
81     const UID *container_ul;
82     int order;               ///< interleaving order if dts are equal
83     int interlaced;          ///< whether picture is interlaced
84     int field_dominance;     ///< tff=1, bff=2
85     int component_depth;
86     int color_siting;
87     int signal_standard;
88     int h_chroma_sub_sample;
89     int v_chroma_sub_sample;
90     int temporal_reordering;
91     AVRational aspect_ratio; ///< display aspect ratio
92     int closed_gop;          ///< gop is closed, used in mpeg-2 frame parsing
93     int video_bit_rate;
94     int slice_offset;
95     int frame_size;          ///< frame size in bytes
96     int seq_closed_gop;      ///< all gops in sequence are closed, used in mpeg-2 descriptor
97     int max_gop;             ///< maximum gop size, used by mpeg-2 descriptor
98     int b_picture_count;     ///< maximum number of consecutive b pictures, used in mpeg-2 descriptor
99     int low_delay;           ///< low delay, used in mpeg-2 descriptor
100     int avc_intra;
101 } MXFStreamContext;
102 
103 typedef struct MXFContainerEssenceEntry {
104     UID container_ul;
105     UID element_ul;
106     UID codec_ul;
107     void (*write_desc)(AVFormatContext *, AVStream *);
108 } MXFContainerEssenceEntry;
109 
110 typedef struct MXFPackage {
111     char *name;
112     enum MXFMetadataSetType type;
113     int instance;
114     struct MXFPackage *ref;
115 } MXFPackage;
116 
117 enum ULIndex {
118     INDEX_MPEG2 = 0,
119     INDEX_AES3,
120     INDEX_WAV,
121     INDEX_D10_VIDEO,
122     INDEX_D10_AUDIO,
123     INDEX_DV,
124     INDEX_DNXHD,
125     INDEX_JPEG2000,
126     INDEX_H264,
127     INDEX_S436M,
128     INDEX_PRORES,
129 };
130 
131 static const struct {
132     enum AVCodecID id;
133     enum ULIndex index;
134 } mxf_essence_mappings[] = {
135     { AV_CODEC_ID_MPEG2VIDEO, INDEX_MPEG2 },
136     { AV_CODEC_ID_PCM_S24LE,  INDEX_AES3 },
137     { AV_CODEC_ID_PCM_S16LE,  INDEX_AES3 },
138     { AV_CODEC_ID_DVVIDEO,    INDEX_DV },
139     { AV_CODEC_ID_DNXHD,      INDEX_DNXHD },
140     { AV_CODEC_ID_JPEG2000,   INDEX_JPEG2000 },
141     { AV_CODEC_ID_H264,       INDEX_H264 },
142     { AV_CODEC_ID_PRORES,     INDEX_PRORES },
143     { AV_CODEC_ID_NONE }
144 };
145 
146 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st);
147 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st);
148 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st);
149 static void mxf_write_h264_desc(AVFormatContext *s, AVStream *st);
150 static void mxf_write_cdci_desc(AVFormatContext *s, AVStream *st);
151 static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st);
152 static void mxf_write_s436m_anc_desc(AVFormatContext *s, AVStream *st);
153 
154 static const MXFContainerEssenceEntry mxf_essence_container_uls[] = {
155     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 },
156       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
157       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
158       mxf_write_mpegvideo_desc },
159     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x03,0x00 },
160       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x03,0x00 },
161       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
162       mxf_write_aes3_desc },
163     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 },
164       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x01,0x00 },
165       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
166       mxf_write_wav_desc },
167     // D-10 Video
168     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 },
169       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x05,0x01,0x01,0x00 },
170       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x01 },
171       mxf_write_cdci_desc },
172     // D-10 Audio
173     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 },
174       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x06,0x01,0x10,0x00 },
175       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
176       mxf_write_generic_sound_desc },
177     // DV
178     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x7F,0x01 },
179       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x18,0x01,0x01,0x00 },
180       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x00,0x00,0x00 },
181       mxf_write_cdci_desc },
182     // DNxHD
183     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x0D,0x01,0x03,0x01,0x02,0x11,0x01,0x00 },
184       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x0C,0x00 },
185       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x71,0x01,0x00,0x00 },
186       mxf_write_cdci_desc },
187     // JPEG2000
188     { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0c,0x01,0x00 },
189       { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01,0x15,0x01,0x08,0x00 },
190       { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 },
191       mxf_write_cdci_desc },
192     // H.264
193     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x0D,0x01,0x03,0x01,0x02,0x10,0x60,0x01 },
194       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
195       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
196       mxf_write_h264_desc },
197     // S436M ANC
198     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x0D,0x01,0x03,0x01,0x02,0x0e,0x00,0x00 },
199       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x17,0x01,0x02,0x00 },
200       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x01,0x5C,0x00 },
201       mxf_write_s436m_anc_desc },
202     // ProRes
203     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x0d,0x01,0x03,0x01,0x02,0x1c,0x01,0x00 },
204       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01,0x15,0x01,0x17,0x00 },
205       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x03,0x00 },
206       mxf_write_cdci_desc },
207     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
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       NULL },
211 };
212 
213 static const UID mxf_d10_codec_uls[] = {
214     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x01 }, // D-10 625/50 PAL 50mb/s
215     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x02 }, // D-10 525/50 NTSC 50mb/s
216     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x03 }, // D-10 625/50 PAL 40mb/s
217     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x04 }, // D-10 525/50 NTSC 40mb/s
218     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x05 }, // D-10 625/50 PAL 30mb/s
219     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x01,0x02,0x01,0x06 }, // D-10 525/50 NTSC 30mb/s
220 };
221 
222 static const UID mxf_d10_container_uls[] = {
223     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, // D-10 625/50 PAL 50mb/s
224     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x02,0x01 }, // D-10 525/50 NTSC 50mb/s
225     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x03,0x01 }, // D-10 625/50 PAL 40mb/s
226     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x04,0x01 }, // D-10 525/50 NTSC 40mb/s
227     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x05,0x01 }, // D-10 625/50 PAL 30mb/s
228     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x01,0x06,0x01 }, // D-10 525/50 NTSC 30mb/s
229 };
230 
231 static const uint8_t product_uid[]          = { 0xAD,0xAB,0x44,0x24,0x2f,0x25,0x4d,0xc7,0x92,0xff,0x29,0xbd,0x00,0x0c,0x00,0x02};
232 static const uint8_t uuid_base[]            = { 0xAD,0xAB,0x44,0x24,0x2f,0x25,0x4d,0xc7,0x92,0xff };
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     MXFStreamContext timecode_track_priv;
425 } MXFContext;
426 
mxf_write_uuid(AVIOContext * pb,enum MXFMetadataSetType type,int value)427 static void mxf_write_uuid(AVIOContext *pb, enum MXFMetadataSetType type, int value)
428 {
429     avio_write(pb, uuid_base, 10);
430     avio_wb16(pb, type);
431     avio_wb32(pb, value);
432 }
433 
mxf_write_umid(AVFormatContext * s,int type)434 static void mxf_write_umid(AVFormatContext *s, int type)
435 {
436     MXFContext *mxf = s->priv_data;
437     avio_write(s->pb, umid_ul, 13);
438     avio_wb24(s->pb, mxf->instance_number);
439     avio_write(s->pb, mxf->umid, 15);
440     avio_w8(s->pb, type);
441 }
442 
mxf_write_refs_count(AVIOContext * pb,int ref_count)443 static void mxf_write_refs_count(AVIOContext *pb, int ref_count)
444 {
445     avio_wb32(pb, ref_count);
446     avio_wb32(pb, 16);
447 }
448 
klv_ber_length(uint64_t len)449 static int klv_ber_length(uint64_t len)
450 {
451     if (len < 128)
452         return 1;
453     else
454         return (av_log2(len) >> 3) + 2;
455 }
456 
klv_encode_ber_length(AVIOContext * pb,uint64_t len)457 static int klv_encode_ber_length(AVIOContext *pb, uint64_t len)
458 {
459     // Determine the best BER size
460     int size = klv_ber_length(len);
461     if (size == 1) {
462         //short form
463         avio_w8(pb, len);
464         return 1;
465     }
466 
467     size --;
468     // long form
469     avio_w8(pb, 0x80 + size);
470     while(size) {
471         size--;
472         avio_w8(pb, len >> 8 * size & 0xff);
473     }
474     return 0;
475 }
476 
klv_encode_ber4_length(AVIOContext * pb,int len)477 static void klv_encode_ber4_length(AVIOContext *pb, int len)
478 {
479     avio_w8(pb, 0x80 + 3);
480     avio_wb24(pb, len);
481 }
482 
klv_encode_ber9_length(AVIOContext * pb,uint64_t len)483 static void klv_encode_ber9_length(AVIOContext *pb, uint64_t len)
484 {
485     avio_w8(pb, 0x80 + 8);
486     avio_wb64(pb, len);
487 }
488 
489 /*
490  * Get essence container ul index
491  */
mxf_get_essence_container_ul_index(enum AVCodecID id)492 static int mxf_get_essence_container_ul_index(enum AVCodecID id)
493 {
494     int i;
495     for (i = 0; mxf_essence_mappings[i].id; i++)
496         if (mxf_essence_mappings[i].id == id)
497             return mxf_essence_mappings[i].index;
498     return -1;
499 }
500 
mxf_lookup_local_tag(int tag)501 static const MXFLocalTagPair* mxf_lookup_local_tag(int tag)
502 {
503     for (int i = 0; i < MXF_NUM_TAGS; i++) {
504         if (mxf_local_tag_batch[i].local_tag == tag) {
505             return &mxf_local_tag_batch[i];
506         }
507     }
508 
509     // this assert can only be hit during development
510     av_assert0(0 && "you forgot to add your new tag to mxf_local_tag_batch");
511     return NULL;
512 }
513 
mxf_mark_tag_unused(MXFContext * mxf,int tag)514 static void mxf_mark_tag_unused(MXFContext *mxf, int tag)
515 {
516     const MXFLocalTagPair *pair = mxf_lookup_local_tag(tag);
517     mxf->unused_tags[pair - mxf_local_tag_batch] = 1;
518 }
519 
mxf_write_primer_pack(AVFormatContext * s)520 static void mxf_write_primer_pack(AVFormatContext *s)
521 {
522     MXFContext *mxf = s->priv_data;
523     AVIOContext *pb = s->pb;
524     int local_tag_number = MXF_NUM_TAGS, i;
525     int will_have_avc_tags = 0, will_have_mastering_tags = 0;
526 
527     for (i = 0; i < s->nb_streams; i++) {
528         MXFStreamContext *sc = s->streams[i]->priv_data;
529         if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_H264 && !sc->avc_intra) {
530             will_have_avc_tags = 1;
531         }
532         if (av_stream_get_side_data(s->streams[i], AV_PKT_DATA_MASTERING_DISPLAY_METADATA, NULL)) {
533             will_have_mastering_tags = 1;
534         }
535     }
536 
537     if (!mxf->store_user_comments) {
538         mxf_mark_tag_unused(mxf, 0x4406);
539         mxf_mark_tag_unused(mxf, 0x5001);
540         mxf_mark_tag_unused(mxf, 0x5003);
541     }
542 
543     if (!will_have_avc_tags) {
544         mxf_mark_tag_unused(mxf, 0x8100);
545         mxf_mark_tag_unused(mxf, 0x8200);
546         mxf_mark_tag_unused(mxf, 0x8201);
547         mxf_mark_tag_unused(mxf, 0x8202);
548     }
549 
550     if (!will_have_mastering_tags) {
551         mxf_mark_tag_unused(mxf, 0x8301);
552         mxf_mark_tag_unused(mxf, 0x8302);
553         mxf_mark_tag_unused(mxf, 0x8303);
554         mxf_mark_tag_unused(mxf, 0x8304);
555     }
556 
557     for (i = 0; i < MXF_NUM_TAGS; i++) {
558         if (mxf->unused_tags[i]) {
559             local_tag_number--;
560         }
561     }
562 
563     avio_write(pb, primer_pack_key, 16);
564     klv_encode_ber_length(pb, local_tag_number * 18 + 8);
565 
566     avio_wb32(pb, local_tag_number); // local_tag num
567     avio_wb32(pb, 18); // item size, always 18 according to the specs
568 
569     for (i = 0; i < MXF_NUM_TAGS; i++) {
570         if (mxf->unused_tags[i] == 0) {
571             avio_wb16(pb, mxf_local_tag_batch[i].local_tag);
572             avio_write(pb, mxf_local_tag_batch[i].uid, 16);
573         }
574     }
575 }
576 
mxf_write_local_tag(AVFormatContext * s,int size,int tag)577 static void mxf_write_local_tag(AVFormatContext *s, int size, int tag)
578 {
579     MXFContext *mxf = s->priv_data;
580     AVIOContext *pb = s->pb;
581     const MXFLocalTagPair *pair = mxf_lookup_local_tag(tag);
582 
583     // make sure the tag was not declared unnecessary upfront
584     av_assert0(mxf->unused_tags[pair - mxf_local_tag_batch] == 0);
585 
586     avio_wb16(pb, tag);
587     avio_wb16(pb, size);
588 }
589 
mxf_write_metadata_key(AVIOContext * pb,unsigned int value)590 static void mxf_write_metadata_key(AVIOContext *pb, unsigned int value)
591 {
592     avio_write(pb, header_metadata_key, 13);
593     avio_wb24(pb, value);
594 }
595 
mxf_get_codec_ul_by_id(const MXFCodecUL * uls,int id)596 static const MXFCodecUL *mxf_get_codec_ul_by_id(const MXFCodecUL *uls, int id)
597 {
598     while (uls->uid[0]) {
599         if (id == uls->id)
600             break;
601         uls++;
602     }
603     return uls;
604 }
605 
606 //one EC -> one descriptor. N ECs -> MultipleDescriptor + N descriptors
607 #define DESCRIPTOR_COUNT(essence_container_count) \
608     (essence_container_count > 1 ? essence_container_count + 1 : essence_container_count)
609 
mxf_write_essence_container_refs(AVFormatContext * s)610 static void mxf_write_essence_container_refs(AVFormatContext *s)
611 {
612     MXFContext *c = s->priv_data;
613     AVIOContext *pb = s->pb;
614     int i;
615 
616     mxf_write_refs_count(pb, DESCRIPTOR_COUNT(c->essence_container_count));
617     av_log(s,AV_LOG_DEBUG, "essence container count:%d\n", c->essence_container_count);
618     for (i = 0; i < s->nb_streams; i++) {
619         MXFStreamContext *sc = s->streams[i]->priv_data;
620         // check first track of essence container type and only write it once
621         if (sc->track_essence_element_key[15] != 0)
622             continue;
623         avio_write(pb, *sc->container_ul, 16);
624         if (c->essence_container_count == 1)
625             break;
626     }
627 
628     if (c->essence_container_count > 1)
629         avio_write(pb, multiple_desc_ul, 16);
630 }
631 
mxf_write_preface(AVFormatContext * s)632 static void mxf_write_preface(AVFormatContext *s)
633 {
634     MXFContext *mxf = s->priv_data;
635     AVIOContext *pb = s->pb;
636 
637     mxf_write_metadata_key(pb, 0x012f00);
638     PRINT_KEY(s, "preface key", pb->buf_ptr - 16);
639     klv_encode_ber_length(pb, 138 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count));
640 
641     // write preface set uid
642     mxf_write_local_tag(s, 16, 0x3C0A);
643     mxf_write_uuid(pb, Preface, 0);
644     PRINT_KEY(s, "preface uid", pb->buf_ptr - 16);
645 
646     // last modified date
647     mxf_write_local_tag(s, 8, 0x3B02);
648     avio_wb64(pb, mxf->timestamp);
649 
650     // write version
651     mxf_write_local_tag(s, 2, 0x3B05);
652     avio_wb16(pb, 259); // v1.3
653 
654     // Object Model Version
655     mxf_write_local_tag(s, 4, 0x3B07);
656     avio_wb32(pb, 1);
657 
658     // write identification_refs
659     mxf_write_local_tag(s, 16 + 8, 0x3B06);
660     mxf_write_refs_count(pb, 1);
661     mxf_write_uuid(pb, Identification, 0);
662 
663     // write content_storage_refs
664     mxf_write_local_tag(s, 16, 0x3B03);
665     mxf_write_uuid(pb, ContentStorage, 0);
666 
667     // operational pattern
668     mxf_write_local_tag(s, 16, 0x3B09);
669     if (s->oformat == &ff_mxf_opatom_muxer)
670         avio_write(pb, opatom_ul, 16);
671     else
672         avio_write(pb, op1a_ul, 16);
673 
674     // write essence_container_refs
675     mxf_write_local_tag(s, 8 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count), 0x3B0A);
676     mxf_write_essence_container_refs(s);
677 
678     // write dm_scheme_refs
679     mxf_write_local_tag(s, 8, 0x3B0B);
680     avio_wb64(pb, 0);
681 }
682 
683 /*
684  * Returns the length of the UTF-16 string, in 16-bit characters, that would result
685  * from decoding the utf-8 string.
686  */
mxf_utf16len(const char * utf8_str)687 static uint64_t mxf_utf16len(const char *utf8_str)
688 {
689     const uint8_t *q = utf8_str;
690     uint64_t size = 0;
691     while (*q) {
692         uint32_t ch;
693         GET_UTF8(ch, *q++, goto invalid;)
694         if (ch < 0x10000)
695             size++;
696         else
697             size += 2;
698         continue;
699 invalid:
700         av_log(NULL, AV_LOG_ERROR, "Invalid UTF8 sequence in mxf_utf16len\n\n");
701     }
702     size += 1;
703     return size;
704 }
705 
706 /*
707  * Returns the calculated length a local tag containing an utf-8 string as utf-16
708  */
mxf_utf16_local_tag_length(const char * utf8_str)709 static int mxf_utf16_local_tag_length(const char *utf8_str)
710 {
711     uint64_t size;
712 
713     if (!utf8_str)
714         return 0;
715 
716     size = mxf_utf16len(utf8_str);
717     if (size >= UINT16_MAX/2) {
718         av_log(NULL, AV_LOG_ERROR, "utf16 local tag size %"PRIx64" invalid (too large), ignoring\n", size);
719         return 0;
720     }
721 
722     return 4 + size * 2;
723 }
724 
725 /*
726  * Write a local tag containing an utf-8 string as utf-16
727  */
mxf_write_local_tag_utf16(AVFormatContext * s,int tag,const char * value)728 static void mxf_write_local_tag_utf16(AVFormatContext *s, int tag, const char *value)
729 {
730     AVIOContext *pb = s->pb;
731     uint64_t size = mxf_utf16len(value);
732 
733     if (size >= UINT16_MAX/2) {
734         av_log(NULL, AV_LOG_ERROR, "utf16 local tag size %"PRIx64" invalid (too large), ignoring\n", size);
735         return;
736     }
737 
738     mxf_write_local_tag(s, size*2, tag);
739     avio_put_str16be(pb, value);
740 }
741 
store_version(AVFormatContext * s)742 static void store_version(AVFormatContext *s){
743     AVIOContext *pb = s->pb;
744 
745     if (s->flags & AVFMT_FLAG_BITEXACT) {
746         avio_wb16(pb, 0); // major
747         avio_wb16(pb, 0); // minor
748         avio_wb16(pb, 0); // tertiary
749     } else {
750         avio_wb16(pb, LIBAVFORMAT_VERSION_MAJOR); // major
751         avio_wb16(pb, LIBAVFORMAT_VERSION_MINOR); // minor
752         avio_wb16(pb, LIBAVFORMAT_VERSION_MICRO); // tertiary
753     }
754     avio_wb16(pb, 0); // patch
755     avio_wb16(pb, 0); // release
756 }
757 
758 #define PLATFORM_IDENT "Lavf " AV_STRINGIFY((OS_NAME))
mxf_write_identification(AVFormatContext * s)759 static void mxf_write_identification(AVFormatContext *s)
760 {
761     MXFContext *mxf = s->priv_data;
762     AVIOContext *pb = s->pb;
763     AVDictionaryEntry *com_entry = av_dict_get(s->metadata, "company_name", NULL, 0);
764     AVDictionaryEntry *product_entry = av_dict_get(s->metadata, "product_name", NULL, 0);
765     AVDictionaryEntry *version_entry = av_dict_get(s->metadata, "product_version", NULL, 0);
766     const char *company = com_entry ? com_entry->value : "FFmpeg";
767     const char *product = product_entry ? product_entry->value : s->oformat != &ff_mxf_opatom_muxer ? "OP1a Muxer" : "OPAtom Muxer";
768     const char *platform = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : PLATFORM_IDENT;
769     const char *version = version_entry ? version_entry->value :
770                               s->flags & AVFMT_FLAG_BITEXACT ? "0.0.0" :
771                                   AV_STRINGIFY(LIBAVFORMAT_VERSION);
772     int length;
773 
774     mxf_write_metadata_key(pb, 0x013000);
775     PRINT_KEY(s, "identification key", pb->buf_ptr - 16);
776 
777     length = 100 +mxf_utf16_local_tag_length(company) +
778                   mxf_utf16_local_tag_length(product) +
779                   mxf_utf16_local_tag_length(platform) +
780                   mxf_utf16_local_tag_length(version);
781     klv_encode_ber_length(pb, length);
782 
783     // write uid
784     mxf_write_local_tag(s, 16, 0x3C0A);
785     mxf_write_uuid(pb, Identification, 0);
786     PRINT_KEY(s, "identification uid", pb->buf_ptr - 16);
787 
788     // write generation uid
789     mxf_write_local_tag(s, 16, 0x3C09);
790     mxf_write_uuid(pb, Identification, 1);
791     mxf_write_local_tag_utf16(s, 0x3C01, company); // Company Name
792     mxf_write_local_tag_utf16(s, 0x3C02, product); // Product Name
793 
794     mxf_write_local_tag(s, 10, 0x3C03); // Product Version
795     store_version(s);
796 
797     mxf_write_local_tag_utf16(s, 0x3C04, version); // Version String
798     mxf_write_local_tag_utf16(s, 0x3C08, platform); // Platform
799 
800     // write product uid
801     mxf_write_local_tag(s, 16, 0x3C05);
802     avio_write(pb, product_uid, 16);
803 
804     // modification date
805     mxf_write_local_tag(s, 8, 0x3C06);
806     avio_wb64(pb, mxf->timestamp);
807 
808     mxf_write_local_tag(s, 10, 0x3C07); // Toolkit Version
809     store_version(s);
810 }
811 
mxf_write_content_storage(AVFormatContext * s,MXFPackage * packages,int package_count)812 static void mxf_write_content_storage(AVFormatContext *s, MXFPackage *packages, int package_count)
813 {
814     AVIOContext *pb = s->pb;
815     int i;
816 
817     mxf_write_metadata_key(pb, 0x011800);
818     PRINT_KEY(s, "content storage key", pb->buf_ptr - 16);
819     klv_encode_ber_length(pb, 60 + (16 * package_count));
820 
821     // write uid
822     mxf_write_local_tag(s, 16, 0x3C0A);
823     mxf_write_uuid(pb, ContentStorage, 0);
824     PRINT_KEY(s, "content storage uid", pb->buf_ptr - 16);
825 
826     // write package reference
827     mxf_write_local_tag(s, 16 * package_count + 8, 0x1901);
828     mxf_write_refs_count(pb, package_count);
829     for (i = 0; i < package_count; i++) {
830         mxf_write_uuid(pb, packages[i].type, packages[i].instance);
831     }
832 
833     // write essence container data
834     mxf_write_local_tag(s, 8 + 16, 0x1902);
835     mxf_write_refs_count(pb, 1);
836     mxf_write_uuid(pb, EssenceContainerData, 0);
837 }
838 
mxf_write_track(AVFormatContext * s,AVStream * st,MXFPackage * package)839 static void mxf_write_track(AVFormatContext *s, AVStream *st, MXFPackage *package)
840 {
841     MXFContext *mxf = s->priv_data;
842     AVIOContext *pb = s->pb;
843     MXFStreamContext *sc = st->priv_data;
844 
845     mxf_write_metadata_key(pb, 0x013b00);
846     PRINT_KEY(s, "track key", pb->buf_ptr - 16);
847     klv_encode_ber_length(pb, 80);
848 
849     // write track uid
850     mxf_write_local_tag(s, 16, 0x3C0A);
851     mxf_write_uuid(pb, Track, mxf->track_instance_count);
852     PRINT_KEY(s, "track uid", pb->buf_ptr - 16);
853 
854     // write track id
855     mxf_write_local_tag(s, 4, 0x4801);
856     avio_wb32(pb, st->index+2);
857 
858     // write track number
859     mxf_write_local_tag(s, 4, 0x4804);
860     if (package->type == MaterialPackage)
861         avio_wb32(pb, 0); // track number of material package is 0
862     else
863         avio_write(pb, sc->track_essence_element_key + 12, 4);
864 
865     // write edit rate
866     mxf_write_local_tag(s, 8, 0x4B01);
867 
868     if (st == mxf->timecode_track && s->oformat == &ff_mxf_opatom_muxer) {
869         avio_wb32(pb, mxf->tc.rate.num);
870         avio_wb32(pb, mxf->tc.rate.den);
871     } else {
872         avio_wb32(pb, mxf->time_base.den);
873         avio_wb32(pb, mxf->time_base.num);
874     }
875 
876     // write origin
877     mxf_write_local_tag(s, 8, 0x4B02);
878     avio_wb64(pb, 0);
879 
880     // write sequence refs
881     mxf_write_local_tag(s, 16, 0x4803);
882     mxf_write_uuid(pb, Sequence, mxf->track_instance_count);
883 }
884 
885 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 };
886 
mxf_write_common_fields(AVFormatContext * s,AVStream * st)887 static void mxf_write_common_fields(AVFormatContext *s, AVStream *st)
888 {
889     MXFContext *mxf = s->priv_data;
890     AVIOContext *pb = s->pb;
891 
892     // find data define uls
893     mxf_write_local_tag(s, 16, 0x0201);
894     if (st == mxf->timecode_track)
895         avio_write(pb, smpte_12m_timecode_track_data_ul, 16);
896     else {
897         const MXFCodecUL *data_def_ul = mxf_get_codec_ul_by_id(ff_mxf_data_definition_uls, st->codecpar->codec_type);
898         avio_write(pb, data_def_ul->uid, 16);
899     }
900 
901     // write duration
902     mxf_write_local_tag(s, 8, 0x0202);
903 
904     if (st != mxf->timecode_track && s->oformat == &ff_mxf_opatom_muxer && st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
905         avio_wb64(pb, mxf->body_offset / mxf->edit_unit_byte_count);
906     } else {
907         avio_wb64(pb, mxf->duration);
908     }
909 }
910 
mxf_write_sequence(AVFormatContext * s,AVStream * st,MXFPackage * package)911 static void mxf_write_sequence(AVFormatContext *s, AVStream *st, MXFPackage *package)
912 {
913     MXFContext *mxf = s->priv_data;
914     AVIOContext *pb = s->pb;
915     enum MXFMetadataSetType component;
916 
917     mxf_write_metadata_key(pb, 0x010f00);
918     PRINT_KEY(s, "sequence key", pb->buf_ptr - 16);
919     klv_encode_ber_length(pb, 80);
920 
921     mxf_write_local_tag(s, 16, 0x3C0A);
922     mxf_write_uuid(pb, Sequence, mxf->track_instance_count);
923 
924     PRINT_KEY(s, "sequence uid", pb->buf_ptr - 16);
925     mxf_write_common_fields(s, st);
926 
927     // write structural component
928     mxf_write_local_tag(s, 16 + 8, 0x1001);
929     mxf_write_refs_count(pb, 1);
930     if (st == mxf->timecode_track)
931         component = TimecodeComponent;
932     else
933         component = SourceClip;
934 
935     mxf_write_uuid(pb, component, mxf->track_instance_count);
936 }
937 
mxf_write_timecode_component(AVFormatContext * s,AVStream * st,MXFPackage * package)938 static void mxf_write_timecode_component(AVFormatContext *s, AVStream *st, MXFPackage *package)
939 {
940     MXFContext *mxf = s->priv_data;
941     AVIOContext *pb = s->pb;
942 
943     mxf_write_metadata_key(pb, 0x011400);
944     klv_encode_ber_length(pb, 75);
945 
946     // UID
947     mxf_write_local_tag(s, 16, 0x3C0A);
948     mxf_write_uuid(pb, TimecodeComponent, mxf->track_instance_count);
949 
950     mxf_write_common_fields(s, st);
951 
952     // Start Time Code
953     mxf_write_local_tag(s, 8, 0x1501);
954     avio_wb64(pb, mxf->tc.start);
955 
956     // Rounded Time Code Base
957     mxf_write_local_tag(s, 2, 0x1502);
958     avio_wb16(pb, mxf->timecode_base);
959 
960     // Drop Frame
961     mxf_write_local_tag(s, 1, 0x1503);
962     avio_w8(pb, !!(mxf->tc.flags & AV_TIMECODE_FLAG_DROPFRAME));
963 }
964 
mxf_write_structural_component(AVFormatContext * s,AVStream * st,MXFPackage * package)965 static void mxf_write_structural_component(AVFormatContext *s, AVStream *st, MXFPackage *package)
966 {
967     MXFContext *mxf = s->priv_data;
968     AVIOContext *pb = s->pb;
969 
970     mxf_write_metadata_key(pb, 0x011100);
971     PRINT_KEY(s, "sturctural component key", pb->buf_ptr - 16);
972     klv_encode_ber_length(pb, 108);
973 
974     // write uid
975     mxf_write_local_tag(s, 16, 0x3C0A);
976     mxf_write_uuid(pb, SourceClip, mxf->track_instance_count);
977 
978     PRINT_KEY(s, "structural component uid", pb->buf_ptr - 16);
979     mxf_write_common_fields(s, st);
980 
981     // write start_position
982     mxf_write_local_tag(s, 8, 0x1201);
983     avio_wb64(pb, 0);
984 
985     // write source package uid, end of the reference
986     mxf_write_local_tag(s, 32, 0x1101);
987     if (!package->ref) {
988         ffio_fill(pb, 0, 32);
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 
mxf_write_tape_descriptor(AVFormatContext * s)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 
mxf_write_multi_descriptor(AVFormatContext * s)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 
mxf_write_generic_desc(AVFormatContext * s,AVStream * st,const UID key)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 
rescale_mastering_chroma(AVRational q)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 
rescale_mastering_luma(AVRational q)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 
mxf_write_cdci_common(AVFormatContext * s,AVStream * st,const UID key)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 
mxf_update_klv_size(AVIOContext * pb,int64_t pos)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 
mxf_write_avc_subdesc(AVFormatContext * s,AVStream * st)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 
mxf_write_cdci_desc(AVFormatContext * s,AVStream * st)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 
mxf_write_h264_desc(AVFormatContext * s,AVStream * st)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 
mxf_write_s436m_anc_desc(AVFormatContext * s,AVStream * st)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 
mxf_write_mpegvideo_desc(AVFormatContext * s,AVStream * st)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 
mxf_write_generic_sound_common(AVFormatContext * s,AVStream * st,const UID key)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) &&
1459             (st->codecpar->ch_layout.nb_channels != 4) &&
1460             (st->codecpar->ch_layout.nb_channels != 8))
1461             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");
1462         avio_wb32(pb, st->codecpar->ch_layout.nb_channels);
1463     } else if (s->oformat == &ff_mxf_d10_muxer) {
1464         if (show_warnings && (mxf->channel_count < st->codecpar->ch_layout.nb_channels))
1465             av_log(s, AV_LOG_WARNING, "d10_channelcount < actual number of audio channels : some channels will be discarded\n");
1466         if (show_warnings && (mxf->channel_count != 4) && (mxf->channel_count != 8))
1467             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");
1468         avio_wb32(pb, mxf->channel_count);
1469     } else {
1470         avio_wb32(pb, st->codecpar->ch_layout.nb_channels);
1471     }
1472 
1473     mxf_write_local_tag(s, 4, 0x3D01);
1474     avio_wb32(pb, av_get_bits_per_sample(st->codecpar->codec_id));
1475 
1476     return pos;
1477 }
1478 
mxf_write_wav_common(AVFormatContext * s,AVStream * st,const UID key)1479 static int64_t mxf_write_wav_common(AVFormatContext *s, AVStream *st, const UID key)
1480 {
1481     AVIOContext *pb = s->pb;
1482     int64_t pos = mxf_write_generic_sound_common(s, st, key);
1483 
1484     mxf_write_local_tag(s, 2, 0x3D0A);
1485     avio_wb16(pb, st->codecpar->block_align);
1486 
1487     // avg bytes per sec
1488     mxf_write_local_tag(s, 4, 0x3D09);
1489     avio_wb32(pb, st->codecpar->block_align*st->codecpar->sample_rate);
1490 
1491     return pos;
1492 }
1493 
mxf_write_wav_desc(AVFormatContext * s,AVStream * st)1494 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st)
1495 {
1496     int64_t pos = mxf_write_wav_common(s, st, mxf_wav_descriptor_key);
1497     mxf_update_klv_size(s->pb, pos);
1498 }
1499 
mxf_write_aes3_desc(AVFormatContext * s,AVStream * st)1500 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st)
1501 {
1502     int64_t pos = mxf_write_wav_common(s, st, mxf_aes3_descriptor_key);
1503     mxf_update_klv_size(s->pb, pos);
1504 }
1505 
mxf_write_generic_sound_desc(AVFormatContext * s,AVStream * st)1506 static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st)
1507 {
1508     int64_t pos = mxf_write_generic_sound_common(s, st, mxf_generic_sound_descriptor_key);
1509     mxf_update_klv_size(s->pb, pos);
1510 }
1511 
1512 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 };
1513 
mxf_write_tagged_value(AVFormatContext * s,const char * name,const char * value)1514 static int mxf_write_tagged_value(AVFormatContext *s, const char* name, const char* value)
1515 {
1516     MXFContext *mxf = s->priv_data;
1517     AVIOContext *pb = s->pb;
1518     int name_size = mxf_utf16_local_tag_length(name);
1519     int indirect_value_size = 13 + mxf_utf16_local_tag_length(value);
1520 
1521     if (!name_size || indirect_value_size == 13)
1522         return 1;
1523 
1524     mxf_write_metadata_key(pb, 0x013f00);
1525     klv_encode_ber_length(pb, 24 + name_size + indirect_value_size);
1526 
1527     // write instance UID
1528     mxf_write_local_tag(s, 16, 0x3C0A);
1529     mxf_write_uuid(pb, TaggedValue, mxf->tagged_value_count);
1530 
1531     // write name
1532     mxf_write_local_tag_utf16(s, 0x5001, name); // Name
1533 
1534     // write indirect value
1535     mxf_write_local_tag(s, indirect_value_size, 0x5003);
1536     avio_write(pb, mxf_indirect_value_utf16le, 17);
1537     avio_put_str16le(pb, value);
1538 
1539     mxf->tagged_value_count++;
1540     return 0;
1541 }
1542 
mxf_write_user_comments(AVFormatContext * s,const AVDictionary * m)1543 static int mxf_write_user_comments(AVFormatContext *s, const AVDictionary *m)
1544 {
1545     MXFContext *mxf = s->priv_data;
1546     AVDictionaryEntry *t = NULL;
1547     int count = 0;
1548 
1549     while ((t = av_dict_get(m, "comment_", t, AV_DICT_IGNORE_SUFFIX))) {
1550         if (mxf->tagged_value_count >= UINT16_MAX) {
1551             av_log(s, AV_LOG_ERROR, "too many tagged values, ignoring remaining\n");
1552             return count;
1553         }
1554 
1555         if (mxf_write_tagged_value(s, t->key + 8, t->value) == 0)
1556             count++;
1557     }
1558     return count;
1559 }
1560 
mxf_write_package(AVFormatContext * s,MXFPackage * package)1561 static void mxf_write_package(AVFormatContext *s, MXFPackage *package)
1562 {
1563     MXFContext *mxf = s->priv_data;
1564     AVIOContext *pb = s->pb;
1565     int i, track_count = s->nb_streams+1;
1566     int name_size = mxf_utf16_local_tag_length(package->name);
1567     int user_comment_count = 0;
1568 
1569     if (package->type == MaterialPackage) {
1570         if (mxf->store_user_comments)
1571             user_comment_count = mxf_write_user_comments(s, s->metadata);
1572         mxf_write_metadata_key(pb, 0x013600);
1573         PRINT_KEY(s, "Material Package key", pb->buf_ptr - 16);
1574         klv_encode_ber_length(pb, 92 + name_size + (16*track_count) + (16*user_comment_count) + 12LL*mxf->store_user_comments);
1575     } else {
1576         mxf_write_metadata_key(pb, 0x013700);
1577         PRINT_KEY(s, "Source Package key", pb->buf_ptr - 16);
1578         klv_encode_ber_length(pb, 112 + name_size + (16*track_count) + 12LL*mxf->store_user_comments); // 20 bytes length for descriptor reference
1579     }
1580 
1581     // write uid
1582     mxf_write_local_tag(s, 16, 0x3C0A);
1583     mxf_write_uuid(pb, package->type, package->instance);
1584     av_log(s, AV_LOG_DEBUG, "package type:%d\n", package->type);
1585     PRINT_KEY(s, "package uid", pb->buf_ptr - 16);
1586 
1587     // write package umid
1588     mxf_write_local_tag(s, 32, 0x4401);
1589     mxf_write_umid(s, package->instance);
1590     PRINT_KEY(s, "package umid second part", pb->buf_ptr - 16);
1591 
1592     // package name
1593     if (name_size)
1594         mxf_write_local_tag_utf16(s, 0x4402, package->name);
1595 
1596     // package creation date
1597     mxf_write_local_tag(s, 8, 0x4405);
1598     avio_wb64(pb, mxf->timestamp);
1599 
1600     // package modified date
1601     mxf_write_local_tag(s, 8, 0x4404);
1602     avio_wb64(pb, mxf->timestamp);
1603 
1604     // write track refs
1605     mxf_write_local_tag(s, track_count*16 + 8, 0x4403);
1606     mxf_write_refs_count(pb, track_count);
1607     // these are the uuids of the tracks the will be written in mxf_write_track
1608     for (i = 0; i < track_count; i++)
1609         mxf_write_uuid(pb, Track,  mxf->track_instance_count + i);
1610 
1611     // write user comment refs
1612     if (mxf->store_user_comments) {
1613         mxf_write_local_tag(s, user_comment_count*16 + 8, 0x4406);
1614         mxf_write_refs_count(pb, user_comment_count);
1615         for (i = 0; i < user_comment_count; i++)
1616             mxf_write_uuid(pb, TaggedValue, mxf->tagged_value_count - user_comment_count + i);
1617     }
1618 
1619     // write multiple descriptor reference
1620     if (package->type == SourcePackage && package->instance == 1) {
1621         mxf_write_local_tag(s, 16, 0x4701);
1622         if (s->nb_streams > 1) {
1623             mxf_write_uuid(pb, MultipleDescriptor, 0);
1624             mxf_write_multi_descriptor(s);
1625         } else
1626             mxf_write_uuid(pb, SubDescriptor, 0);
1627     } else if (package->type == SourcePackage && package->instance == 2) {
1628         mxf_write_local_tag(s, 16, 0x4701);
1629         mxf_write_uuid(pb, TapeDescriptor, 0);
1630         mxf_write_tape_descriptor(s);
1631     }
1632 
1633     /*
1634      * for every 1 track in a package there is 1 sequence and 1 component.
1635      * all 3 of these elements share the same instance number for generating
1636      * there instance uuids. mxf->track_instance_count stores this value.
1637      * mxf->track_instance_count is incremented after a group of all 3 of
1638      * these elements are written.
1639      */
1640 
1641     // write timecode track
1642     mxf_write_track(s, mxf->timecode_track, package);
1643     mxf_write_sequence(s, mxf->timecode_track, package);
1644     mxf_write_timecode_component(s, mxf->timecode_track, package);
1645     mxf->track_instance_count++;
1646 
1647     for (i = 0; i < s->nb_streams; i++) {
1648         AVStream *st = s->streams[i];
1649         mxf_write_track(s, st, package);
1650         mxf_write_sequence(s, st, package);
1651         mxf_write_structural_component(s, st, package);
1652         mxf->track_instance_count++;
1653 
1654         if (package->type == SourcePackage && package->instance == 1) {
1655             MXFStreamContext *sc = st->priv_data;
1656             mxf_essence_container_uls[sc->index].write_desc(s, st);
1657         }
1658     }
1659 }
1660 
mxf_write_essence_container_data(AVFormatContext * s)1661 static int mxf_write_essence_container_data(AVFormatContext *s)
1662 {
1663     AVIOContext *pb = s->pb;
1664 
1665     mxf_write_metadata_key(pb, 0x012300);
1666     klv_encode_ber_length(pb, 72);
1667 
1668     mxf_write_local_tag(s, 16, 0x3C0A); // Instance UID
1669     mxf_write_uuid(pb, EssenceContainerData, 0);
1670 
1671     mxf_write_local_tag(s, 32, 0x2701); // Linked Package UID
1672     mxf_write_umid(s, 1);
1673 
1674     mxf_write_local_tag(s, 4, 0x3F07); // BodySID
1675     avio_wb32(pb, 1);
1676 
1677     mxf_write_local_tag(s, 4, 0x3F06); // IndexSID
1678     avio_wb32(pb, 2);
1679 
1680     return 0;
1681 }
1682 
mxf_write_header_metadata_sets(AVFormatContext * s)1683 static int mxf_write_header_metadata_sets(AVFormatContext *s)
1684 {
1685     MXFContext *mxf = s->priv_data;
1686     AVDictionaryEntry *entry = NULL;
1687     AVStream *st = NULL;
1688     int i;
1689     MXFPackage packages[3] = {{0}};
1690     int package_count = 2;
1691     packages[0].type = MaterialPackage;
1692     packages[1].type = SourcePackage;
1693     packages[1].instance = 1;
1694     packages[0].ref = &packages[1];
1695 
1696 
1697     if (entry = av_dict_get(s->metadata, "material_package_name", NULL, 0))
1698        packages[0].name = entry->value;
1699 
1700     if (entry = av_dict_get(s->metadata, "file_package_name", NULL, 0)) {
1701         packages[1].name = entry->value;
1702     } else {
1703         /* check if any of the streams contain a file_package_name */
1704         for (i = 0; i < s->nb_streams; i++) {
1705             st = s->streams[i];
1706             if (entry = av_dict_get(st->metadata, "file_package_name", NULL, 0)) {
1707                 packages[1].name = entry->value;
1708                 break;
1709             }
1710         }
1711     }
1712 
1713     entry = av_dict_get(s->metadata, "reel_name", NULL, 0);
1714     if (entry) {
1715         packages[2].name = entry->value;
1716         packages[2].type = SourcePackage;
1717         packages[2].instance = 2;
1718         packages[1].ref = &packages[2];
1719         package_count = 3;
1720     }
1721 
1722     mxf_write_preface(s);
1723     mxf_write_identification(s);
1724     mxf_write_content_storage(s, packages, package_count);
1725     mxf->track_instance_count = 0;
1726     for (i = 0; i < package_count; i++)
1727         mxf_write_package(s, &packages[i]);
1728     mxf_write_essence_container_data(s);
1729     return 0;
1730 }
1731 
klv_fill_size(uint64_t size)1732 static unsigned klv_fill_size(uint64_t size)
1733 {
1734     unsigned pad = KAG_SIZE - (size & (KAG_SIZE-1));
1735     if (pad < 20) // smallest fill item possible
1736         return pad + KAG_SIZE;
1737     else
1738         return pad & (KAG_SIZE-1);
1739 }
1740 
mxf_write_index_table_segment(AVFormatContext * s)1741 static void mxf_write_index_table_segment(AVFormatContext *s)
1742 {
1743     MXFContext *mxf = s->priv_data;
1744     AVIOContext *pb = s->pb;
1745     int i, j, temporal_reordering = 0;
1746     int key_index = mxf->last_key_index;
1747     int prev_non_b_picture = 0;
1748     int audio_frame_size = 0;
1749     int64_t pos;
1750 
1751     av_log(s, AV_LOG_DEBUG, "edit units count %d\n", mxf->edit_units_count);
1752 
1753     if (!mxf->edit_units_count && !mxf->edit_unit_byte_count)
1754         return;
1755 
1756     avio_write(pb, index_table_segment_key, 16);
1757 
1758     klv_encode_ber4_length(pb, 0);
1759     pos = avio_tell(pb);
1760 
1761     // instance id
1762     mxf_write_local_tag(s, 16, 0x3C0A);
1763     mxf_write_uuid(pb, IndexTableSegment, mxf->last_indexed_edit_unit);
1764 
1765     // index edit rate
1766     mxf_write_local_tag(s, 8, 0x3F0B);
1767     avio_wb32(pb, mxf->time_base.den);
1768     avio_wb32(pb, mxf->time_base.num);
1769 
1770     // index start position
1771     mxf_write_local_tag(s, 8, 0x3F0C);
1772     avio_wb64(pb, mxf->last_indexed_edit_unit);
1773 
1774     // index duration
1775     mxf_write_local_tag(s, 8, 0x3F0D);
1776     if (mxf->edit_unit_byte_count)
1777         avio_wb64(pb, 0); // index table covers whole container
1778     else
1779         avio_wb64(pb, mxf->edit_units_count);
1780 
1781     // edit unit byte count
1782     mxf_write_local_tag(s, 4, 0x3F05);
1783     avio_wb32(pb, mxf->edit_unit_byte_count);
1784 
1785     // index sid
1786     mxf_write_local_tag(s, 4, 0x3F06);
1787     avio_wb32(pb, 2);
1788 
1789     // body sid
1790     mxf_write_local_tag(s, 4, 0x3F07);
1791     avio_wb32(pb, 1);
1792 
1793     // real slice count - 1
1794     mxf_write_local_tag(s, 1, 0x3F08);
1795     avio_w8(pb, !mxf->edit_unit_byte_count); // only one slice for CBR
1796 
1797     // delta entry array
1798     mxf_write_local_tag(s, 8 + (s->nb_streams+1)*6, 0x3F09);
1799     avio_wb32(pb, s->nb_streams+1); // num of entries
1800     avio_wb32(pb, 6);               // size of one entry
1801     // write system item delta entry
1802     avio_w8(pb, 0);
1803     avio_w8(pb, 0); // slice entry
1804     avio_wb32(pb, 0); // element delta
1805     // write each stream delta entry
1806     for (i = 0; i < s->nb_streams; i++) {
1807         AVStream *st = s->streams[i];
1808         MXFStreamContext *sc = st->priv_data;
1809         avio_w8(pb, sc->temporal_reordering);
1810         if (sc->temporal_reordering)
1811             temporal_reordering = 1;
1812         if (mxf->edit_unit_byte_count) {
1813             avio_w8(pb, 0); // slice number
1814             avio_wb32(pb, sc->slice_offset);
1815         } else if (i == 0) { // video track
1816             avio_w8(pb, 0); // slice number
1817             avio_wb32(pb, KAG_SIZE); // system item size including klv fill
1818         } else { // audio or data track
1819             if (!audio_frame_size) {
1820                 audio_frame_size = sc->frame_size;
1821                 audio_frame_size += klv_fill_size(audio_frame_size);
1822             }
1823             avio_w8(pb, 1);
1824             avio_wb32(pb, (i-1)*audio_frame_size); // element delta
1825         }
1826     }
1827 
1828     if (!mxf->edit_unit_byte_count) {
1829         MXFStreamContext *sc = s->streams[0]->priv_data;
1830         mxf_write_local_tag(s, 8 + mxf->edit_units_count*15, 0x3F0A);
1831         avio_wb32(pb, mxf->edit_units_count);  // num of entries
1832         avio_wb32(pb, 15);  // size of one entry
1833 
1834         for (i = 0; i < mxf->edit_units_count; i++) {
1835             int temporal_offset = 0;
1836 
1837             if (!(mxf->index_entries[i].flags & 0x33)) { // I-frame
1838                 sc->max_gop = FFMAX(sc->max_gop, i - mxf->last_key_index);
1839                 mxf->last_key_index = key_index;
1840                 key_index = i;
1841             }
1842 
1843             if (temporal_reordering) {
1844                 int pic_num_in_gop = i - key_index;
1845                 if (pic_num_in_gop != mxf->index_entries[i].temporal_ref) {
1846                     for (j = key_index; j < mxf->edit_units_count; j++) {
1847                         if (pic_num_in_gop == mxf->index_entries[j].temporal_ref)
1848                             break;
1849                     }
1850                     if (j == mxf->edit_units_count)
1851                         av_log(s, AV_LOG_WARNING, "missing frames\n");
1852                     temporal_offset = j - key_index - pic_num_in_gop;
1853                 }
1854             }
1855             avio_w8(pb, temporal_offset);
1856 
1857             if ((mxf->index_entries[i].flags & 0x30) == 0x30) { // back and forward prediction
1858                 sc->b_picture_count = FFMAX(sc->b_picture_count, i - prev_non_b_picture);
1859                 avio_w8(pb, mxf->last_key_index - i);
1860             } else {
1861                 avio_w8(pb, key_index - i); // key frame offset
1862                 if ((mxf->index_entries[i].flags & 0x20) == 0x20) // only forward
1863                     mxf->last_key_index = key_index;
1864                 prev_non_b_picture = i;
1865             }
1866 
1867             if (!(mxf->index_entries[i].flags & 0x33) && // I-frame
1868                 mxf->index_entries[i].flags & 0x40 && !temporal_offset)
1869                 mxf->index_entries[i].flags |= 0x80; // random access
1870             avio_w8(pb, mxf->index_entries[i].flags);
1871             // stream offset
1872             avio_wb64(pb, mxf->index_entries[i].offset);
1873             if (s->nb_streams > 1)
1874                 avio_wb32(pb, mxf->index_entries[i].slice_offset);
1875             else
1876                 avio_wb32(pb, 0);
1877         }
1878 
1879         mxf->last_key_index = key_index - mxf->edit_units_count;
1880         mxf->last_indexed_edit_unit += mxf->edit_units_count;
1881         mxf->edit_units_count = 0;
1882     }
1883 
1884     mxf_update_klv_size(pb, pos);
1885 }
1886 
mxf_write_klv_fill(AVFormatContext * s)1887 static void mxf_write_klv_fill(AVFormatContext *s)
1888 {
1889     unsigned pad = klv_fill_size(avio_tell(s->pb));
1890     if (pad) {
1891         avio_write(s->pb, klv_fill_key, 16);
1892         pad -= 16 + 4;
1893         klv_encode_ber4_length(s->pb, pad);
1894         ffio_fill(s->pb, 0, pad);
1895         av_assert1(!(avio_tell(s->pb) & (KAG_SIZE-1)));
1896     }
1897 }
1898 
mxf_write_partition(AVFormatContext * s,int bodysid,int indexsid,const uint8_t * key,int write_metadata)1899 static int mxf_write_partition(AVFormatContext *s, int bodysid,
1900                                 int indexsid,
1901                                 const uint8_t *key, int write_metadata)
1902 {
1903     MXFContext *mxf = s->priv_data;
1904     AVIOContext *pb = s->pb;
1905     int64_t header_byte_count_offset;
1906     unsigned index_byte_count = 0;
1907     uint64_t partition_offset = avio_tell(pb);
1908     int err;
1909 
1910     if (!mxf->edit_unit_byte_count && mxf->edit_units_count)
1911         index_byte_count = 85 + 12+(s->nb_streams+1)*6 +
1912             12+mxf->edit_units_count*15;
1913     else if (mxf->edit_unit_byte_count && indexsid)
1914         index_byte_count = 80;
1915 
1916     if (index_byte_count) {
1917         index_byte_count += 16 + 4; // add encoded ber4 length
1918         index_byte_count += klv_fill_size(index_byte_count);
1919     }
1920 
1921     if (key && !memcmp(key, body_partition_key, 16)) {
1922         if ((err = av_reallocp_array(&mxf->body_partition_offset, mxf->body_partitions_count + 1,
1923                                      sizeof(*mxf->body_partition_offset))) < 0) {
1924             mxf->body_partitions_count = 0;
1925             return err;
1926         }
1927         mxf->body_partition_offset[mxf->body_partitions_count++] = partition_offset;
1928     }
1929 
1930     // write klv
1931     if (key)
1932         avio_write(pb, key, 16);
1933     else
1934         avio_write(pb, body_partition_key, 16);
1935 
1936     klv_encode_ber4_length(pb, 88 + 16LL * DESCRIPTOR_COUNT(mxf->essence_container_count));
1937 
1938     // write partition value
1939     avio_wb16(pb, 1); // majorVersion
1940     avio_wb16(pb, 3); // minorVersion
1941     avio_wb32(pb, KAG_SIZE); // KAGSize
1942 
1943     avio_wb64(pb, partition_offset); // ThisPartition
1944 
1945     if (key && !memcmp(key, body_partition_key, 16) && mxf->body_partitions_count > 1)
1946         avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-2]); // PreviousPartition
1947     else if (key && !memcmp(key, footer_partition_key, 16) && mxf->body_partitions_count)
1948         avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-1]); // PreviousPartition
1949     else
1950         avio_wb64(pb, 0);
1951 
1952     avio_wb64(pb, mxf->footer_partition_offset); // footerPartition
1953 
1954     // set offset
1955     header_byte_count_offset = avio_tell(pb);
1956     avio_wb64(pb, 0); // headerByteCount, update later
1957 
1958     // indexTable
1959     avio_wb64(pb, index_byte_count); // indexByteCount
1960     avio_wb32(pb, index_byte_count ? indexsid : 0); // indexSID
1961 
1962     // BodyOffset
1963     if (bodysid && mxf->edit_units_count && mxf->body_partitions_count && s->oformat != &ff_mxf_opatom_muxer)
1964         avio_wb64(pb, mxf->body_offset);
1965     else
1966         avio_wb64(pb, 0);
1967 
1968     avio_wb32(pb, bodysid); // bodySID
1969 
1970     // operational pattern
1971     if (s->oformat == &ff_mxf_opatom_muxer)
1972         avio_write(pb, opatom_ul, 16);
1973     else
1974         avio_write(pb, op1a_ul, 16);
1975 
1976     // essence container
1977     mxf_write_essence_container_refs(s);
1978 
1979     if (write_metadata) {
1980         // mark the start of the headermetadata and calculate metadata size
1981         int64_t pos, start;
1982         unsigned header_byte_count;
1983 
1984         mxf_write_klv_fill(s);
1985         start = avio_tell(s->pb);
1986         mxf_write_primer_pack(s);
1987         mxf_write_klv_fill(s);
1988         mxf_write_header_metadata_sets(s);
1989         pos = avio_tell(s->pb);
1990         header_byte_count = pos - start + klv_fill_size(pos);
1991 
1992         // update header_byte_count
1993         avio_seek(pb, header_byte_count_offset, SEEK_SET);
1994         avio_wb64(pb, header_byte_count);
1995         avio_seek(pb, pos, SEEK_SET);
1996     }
1997 
1998     if(key)
1999         avio_write_marker(pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
2000 
2001     return 0;
2002 }
2003 
2004 static const struct {
2005     int profile;
2006     UID codec_ul;
2007 } mxf_prores_codec_uls[] = {
2008     { FF_PROFILE_PRORES_PROXY,    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x01,0x00 } },
2009     { FF_PROFILE_PRORES_LT,       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x02,0x00 } },
2010     { FF_PROFILE_PRORES_STANDARD, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x03,0x00 } },
2011     { FF_PROFILE_PRORES_HQ,       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x04,0x00 } },
2012     { FF_PROFILE_PRORES_4444,     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x05,0x00 } },
2013     { FF_PROFILE_PRORES_XQ,       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x03,0x06,0x06,0x00 } },
2014 };
2015 
mxf_parse_prores_frame(AVFormatContext * s,AVStream * st,AVPacket * pkt)2016 static int mxf_parse_prores_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
2017 {
2018     MXFContext *mxf = s->priv_data;
2019     MXFStreamContext *sc = st->priv_data;
2020     int i, profile;
2021 
2022     if (mxf->header_written)
2023         return 1;
2024 
2025     profile = st->codecpar->profile;
2026     for (i = 0; i < FF_ARRAY_ELEMS(mxf_prores_codec_uls); i++) {
2027         if (profile == mxf_prores_codec_uls[i].profile) {
2028             sc->codec_ul = &mxf_prores_codec_uls[i].codec_ul;
2029             break;
2030         }
2031     }
2032     if (i == FF_ARRAY_ELEMS(mxf_prores_codec_uls))
2033         return 0;
2034 
2035     sc->frame_size = pkt->size;
2036 
2037     return 1;
2038 }
2039 
2040 static const struct {
2041     uint16_t cid;
2042     uint8_t  interlaced;
2043     UID codec_ul;
2044 } mxf_dnxhd_codec_uls[] = {
2045     { 1235, 0, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x01,0x00,0x00 } }, // 1080p 10bit HIGH
2046     { 1237, 0, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x03,0x00,0x00 } }, // 1080p 8bit MED
2047     { 1238, 0, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x04,0x00,0x00 } }, // 1080p 8bit HIGH
2048     { 1241, 1, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x07,0x00,0x00 } }, // 1080i 10bit HIGH
2049     { 1242, 1, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x08,0x00,0x00 } }, // 1080i 8bit MED
2050     { 1243, 1, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x09,0x00,0x00 } }, // 1080i 8bit HIGH
2051     { 1244, 1, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x0a,0x00,0x00 } }, // 1080i 8bit TR
2052     { 1250, 0, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x10,0x00,0x00 } }, // 720p 10bit
2053     { 1251, 0, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x11,0x00,0x00 } }, // 720p 8bit HIGH
2054     { 1252, 0, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x12,0x00,0x00 } }, // 720p 8bit MED
2055     { 1253, 0, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x13,0x00,0x00 } }, // 720p 8bit LOW
2056     { 1256, 0, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x16,0x00,0x00 } }, // 1080p 10bit 444
2057     { 1258, 0, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x18,0x00,0x00 } }, // 720p 8bit TR
2058     { 1259, 0, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x19,0x00,0x00 } }, // 1080p 8bit TR
2059     { 1260, 1, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x1a,0x00,0x00 } }, // 1080i 8bit TR MBAFF
2060     { 1270, 0, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x24,0x00,0x00 } }, // DNXHR 444
2061     { 1271, 0, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x25,0x00,0x00 } }, // DNXHR HQX
2062     { 1272, 0, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x26,0x00,0x00 } }, // DNXHR HQ
2063     { 1273, 0, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x27,0x00,0x00 } }, // DNXHR SQ
2064     { 1274, 0, { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x71,0x28,0x00,0x00 } }, // DNXHR LB
2065 };
2066 
mxf_parse_dnxhd_frame(AVFormatContext * s,AVStream * st,AVPacket * pkt)2067 static int mxf_parse_dnxhd_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
2068 {
2069     MXFContext *mxf = s->priv_data;
2070     MXFStreamContext *sc = st->priv_data;
2071     int i, cid;
2072 
2073     if (mxf->header_written)
2074         return 1;
2075 
2076     if (pkt->size < 43)
2077         return 0;
2078 
2079     cid = AV_RB32(pkt->data + 0x28);
2080     for (i = 0; i < FF_ARRAY_ELEMS(mxf_dnxhd_codec_uls); i++) {
2081         if (cid == mxf_dnxhd_codec_uls[i].cid) {
2082             sc->codec_ul = &mxf_dnxhd_codec_uls[i].codec_ul;
2083             sc->interlaced = mxf_dnxhd_codec_uls[i].interlaced;
2084             break;
2085         }
2086     }
2087     if (i == FF_ARRAY_ELEMS(mxf_dnxhd_codec_uls))
2088         return 0;
2089 
2090     sc->component_depth = 0;
2091     switch (pkt->data[0x21] >> 5) {
2092     case 1: sc->component_depth = 8; break;
2093     case 2: sc->component_depth = 10; break;
2094     case 3: sc->component_depth = 12; break;
2095     }
2096     if (!sc->component_depth)
2097         return 0;
2098 
2099     if (cid >= 1270) { // RI raster
2100         av_reduce(&sc->aspect_ratio.num, &sc->aspect_ratio.den,
2101                   st->codecpar->width, st->codecpar->height,
2102                   INT_MAX);
2103     } else {
2104         sc->aspect_ratio = (AVRational){ 16, 9 };
2105     }
2106 
2107     sc->frame_size = pkt->size;
2108 
2109     return 1;
2110 }
2111 
2112 static const struct {
2113     const UID container_ul;
2114     const UID codec_ul;
2115 } mxf_dv_uls[] = {
2116     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x01,0x01 }, // IEC DV25 525/60
2117       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x01,0x01,0x00 } },
2118     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x02,0x01 }, // IEC DV25 626/50
2119       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x01,0x02,0x00 } },
2120     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x40,0x01 }, // DV25 525/60
2121       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x01,0x00 }, },
2122     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, // DV25 625/50
2123       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x02,0x00 }, },
2124     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x50,0x01 }, // DV50 525/60
2125       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x03,0x00 }, },
2126     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x51,0x01 }, // DV50 625/50
2127       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x04,0x00 }, },
2128     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x60,0x01 }, // DV100 1080/60
2129       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x05,0x00 }, },
2130     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x61,0x01 }, // DV100 1080/50
2131       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x06,0x00 }, },
2132     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x62,0x01 }, // DV100 720/60
2133       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x07,0x00 }, },
2134     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x02,0x63,0x01 }, // DV100 720/50
2135       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x01,0x02,0x02,0x02,0x02,0x08,0x00 }, },
2136 };
2137 
mxf_parse_dv_frame(AVFormatContext * s,AVStream * st,AVPacket * pkt)2138 static int mxf_parse_dv_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
2139 {
2140     MXFContext *mxf = s->priv_data;
2141     MXFStreamContext *sc = st->priv_data;
2142     const uint8_t *vs_pack, *vsc_pack;
2143     int apt, ul_index, stype, pal;
2144 
2145     if (mxf->header_written)
2146         return 1;
2147 
2148     // Check for minimal frame size
2149     if (pkt->size < 120000)
2150         return -1;
2151 
2152     apt      = pkt->data[4] & 0x7;
2153     vs_pack  = pkt->data + 80*5 + 48;
2154     vsc_pack = pkt->data + 80*5 + 53;
2155     stype    = vs_pack[3] & 0x1f;
2156     pal      = (vs_pack[3] >> 5) & 0x1;
2157 
2158     if ((vsc_pack[2] & 0x07) == 0x02) {
2159         sc->aspect_ratio = (AVRational){ 16, 9 };
2160     } else {
2161         sc->aspect_ratio = (AVRational){ 4, 3 };
2162     }
2163 
2164     sc->interlaced = (vsc_pack[3] >> 4) & 0x01;
2165     // TODO: fix dv encoder to set proper FF/FS value in VSC pack
2166     // and set field dominance accordingly
2167     // av_log(s, AV_LOG_DEBUG, "DV vsc pack ff/ss = %x\n", vsc_pack[2] >> 6);
2168 
2169     switch (stype) {
2170     case 0x18: // DV100 720p
2171         ul_index = 8+pal;
2172         if (sc->interlaced) {
2173             av_log(s, AV_LOG_ERROR, "source marked as interlaced but codec profile is progressive\n");
2174             sc->interlaced = 0;
2175         }
2176         break;
2177     case 0x14: // DV100 1080i
2178         ul_index = 6+pal;
2179         break;
2180     case 0x04: // DV50
2181         ul_index = 4+pal;
2182         break;
2183     default: // DV25
2184         if (!apt) { // IEC
2185             ul_index = 0+pal;
2186         } else {
2187             ul_index = 2+pal;
2188         }
2189     }
2190 
2191     sc->container_ul = &mxf_dv_uls[ul_index].container_ul;
2192     sc->codec_ul = &mxf_dv_uls[ul_index].codec_ul;
2193 
2194     sc->frame_size = pkt->size;
2195 
2196     return 1;
2197 }
2198 
2199 static const struct {
2200     UID uid;
2201     int frame_size;
2202     uint8_t profile;
2203     uint8_t interlaced;
2204     int8_t intra_only; // 1 or 0 when there are separate UIDs for Long GOP and Intra, -1 when Intra/LGOP detection can be ignored
2205 } mxf_h264_codec_uls[] = {
2206     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x11,0x01 },      0,  66, 0, -1 }, // AVC Baseline
2207     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x20,0x01 },      0,  77, 0, -1 }, // AVC Main
2208     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x30,0x01 },      0,  88, 0, -1 }, // AVC Extended
2209     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x40,0x01 },      0, 100, 0, -1 }, // AVC High
2210     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x50,0x01 },      0, 110, 0,  0 }, // AVC High 10
2211     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x60,0x01 },      0, 122, 0,  0 }, // AVC High 422
2212     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x31,0x70,0x01 },      0, 244, 0,  0 }, // AVC High 444
2213     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x20,0x01 },      0, 110, 0,  1 }, // AVC High 10 Intra
2214     {{ 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
2215     {{ 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
2216     {{ 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
2217     {{ 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
2218     {{ 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
2219     {{ 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
2220     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0a,0x04,0x01,0x02,0x02,0x01,0x32,0x30,0x01 },      0, 122, 0,  1 }, // AVC High 422 Intra
2221     {{ 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
2222     {{ 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
2223     {{ 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
2224     {{ 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
2225     {{ 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
2226     {{ 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
2227     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x01,0x32,0x40,0x01 },      0, 244, 0,  1 }, // AVC High 444 Intra
2228     {{ 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x0d,0x04,0x01,0x02,0x02,0x01,0x32,0x50,0x01 },      0,  44, 0, -1 }, // AVC CAVLC 444
2229 };
2230 
mxf_parse_h264_frame(AVFormatContext * s,AVStream * st,AVPacket * pkt,MXFIndexEntry * e)2231 static int mxf_parse_h264_frame(AVFormatContext *s, AVStream *st,
2232                                 AVPacket *pkt, MXFIndexEntry *e)
2233 {
2234     MXFContext *mxf = s->priv_data;
2235     MXFStreamContext *sc = st->priv_data;
2236     H264SPS seq, *const sps = &seq;
2237     GetBitContext gb;
2238     const uint8_t *buf = pkt->data;
2239     const uint8_t *buf_end = pkt->data + pkt->size;
2240     const uint8_t *nal_end;
2241     const UID *codec_ul = NULL;
2242     uint32_t state = -1;
2243     int extra_size = 512; // support AVC Intra files without SPS/PPS header
2244     int i, frame_size, slice_type, has_sps = 0, intra_only = 0, ret;
2245 
2246     for (;;) {
2247         buf = avpriv_find_start_code(buf, buf_end, &state);
2248         if (buf >= buf_end)
2249             break;
2250 
2251         switch (state & 0x1f) {
2252         case H264_NAL_SPS:
2253             e->flags |= 0x40;
2254 
2255             if (mxf->header_written)
2256                 break;
2257 
2258             nal_end = ff_avc_find_startcode(buf, buf_end);
2259             ret = ff_avc_decode_sps(sps, buf, nal_end - buf);
2260             if (ret < 0) {
2261                 av_log(s, AV_LOG_ERROR, "error parsing sps\n");
2262                 return 0;
2263             }
2264             has_sps = 1;
2265 
2266             sc->aspect_ratio.num = st->codecpar->width * sps->sar.num;
2267             sc->aspect_ratio.den = st->codecpar->height * sps->sar.den;
2268             av_reduce(&sc->aspect_ratio.num, &sc->aspect_ratio.den,
2269                       sc->aspect_ratio.num, sc->aspect_ratio.den, 1024*1024);
2270             intra_only = (sps->constraint_set_flags >> 3) & 1;
2271             sc->interlaced = !sps->frame_mbs_only_flag;
2272             sc->component_depth = sps->bit_depth_luma;
2273 
2274             buf = nal_end;
2275             break;
2276         case H264_NAL_PPS:
2277             if (e->flags & 0x40) { // sequence header present
2278                 e->flags |= 0x80; // random access
2279                 extra_size = 0;
2280             }
2281             break;
2282         case H264_NAL_IDR_SLICE:
2283             e->flags |= 0x04; // IDR Picture
2284             buf = buf_end;
2285             break;
2286         case H264_NAL_SLICE:
2287             init_get_bits8(&gb, buf, buf_end - buf);
2288             get_ue_golomb_long(&gb); // skip first_mb_in_slice
2289             slice_type = get_ue_golomb_31(&gb);
2290             switch (slice_type % 5) {
2291             case 0:
2292                 e->flags |= 0x20; // P Picture
2293                 e->flags |= 0x06; // P Picture
2294                 break;
2295             case 1:
2296                 e->flags |= 0x30; // B Picture
2297                 e->flags |= 0x03; // non-referenced B Picture
2298                 break;
2299             }
2300             buf = buf_end;
2301             break;
2302         default:
2303             break;
2304         }
2305     }
2306 
2307     if (mxf->header_written)
2308         return 1;
2309 
2310     if (!has_sps)
2311         sc->interlaced = st->codecpar->field_order != AV_FIELD_PROGRESSIVE ? 1 : 0;
2312     frame_size = pkt->size + extra_size;
2313 
2314     for (i = 0; i < FF_ARRAY_ELEMS(mxf_h264_codec_uls); i++) {
2315         if (frame_size == mxf_h264_codec_uls[i].frame_size && sc->interlaced == mxf_h264_codec_uls[i].interlaced) {
2316             codec_ul = &mxf_h264_codec_uls[i].uid;
2317             sc->component_depth = 10; // AVC Intra is always 10 Bit
2318             sc->aspect_ratio = (AVRational){ 16, 9 }; // 16:9 is mandatory for broadcast HD
2319             st->codecpar->profile = mxf_h264_codec_uls[i].profile;
2320             sc->avc_intra = 1;
2321             mxf->cbr_index = 1;
2322             sc->frame_size = pkt->size;
2323             if (sc->interlaced)
2324                 sc->field_dominance = 1; // top field first is mandatory for AVC Intra
2325             break;
2326         } else if (has_sps && mxf_h264_codec_uls[i].frame_size == 0 &&
2327                    mxf_h264_codec_uls[i].profile == sps->profile_idc &&
2328                    (mxf_h264_codec_uls[i].intra_only < 0 ||
2329                     mxf_h264_codec_uls[i].intra_only == intra_only)) {
2330             codec_ul = &mxf_h264_codec_uls[i].uid;
2331             st->codecpar->profile = sps->profile_idc;
2332             st->codecpar->level = sps->level_idc;
2333             // continue to check for avc intra
2334         }
2335     }
2336 
2337     if (!codec_ul) {
2338         av_log(s, AV_LOG_ERROR, "h264 profile not supported\n");
2339         return 0;
2340     }
2341     sc->codec_ul = codec_ul;
2342 
2343     return 1;
2344 }
2345 
2346 static const UID mxf_mpeg2_codec_uls[] = {
2347     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x10,0x00 }, // MP-ML I-Frame
2348     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, // MP-ML Long GOP
2349     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, // 422P-ML I-Frame
2350     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, // 422P-ML Long GOP
2351     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x02,0x00 }, // MP-HL I-Frame
2352     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, // MP-HL Long GOP
2353     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, // 422P-HL I-Frame
2354     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, // 422P-HL Long GOP
2355     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x05,0x02,0x00 }, // MP@H-14 I-Frame
2356     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x05,0x03,0x00 }, // MP@H-14 Long GOP
2357 };
2358 
mxf_get_mpeg2_codec_ul(AVCodecParameters * par)2359 static const UID *mxf_get_mpeg2_codec_ul(AVCodecParameters *par)
2360 {
2361     int long_gop = 1;
2362 
2363     if (par->profile == 4) { // Main
2364         if (par->level == 8) // Main
2365             return &mxf_mpeg2_codec_uls[0+long_gop];
2366         else if (par->level == 4) // High
2367             return &mxf_mpeg2_codec_uls[4+long_gop];
2368         else if (par->level == 6) // High 14
2369             return &mxf_mpeg2_codec_uls[8+long_gop];
2370     } else if (par->profile == 0) { // 422
2371         if (par->level == 5) // Main
2372             return &mxf_mpeg2_codec_uls[2+long_gop];
2373         else if (par->level == 2) // High
2374             return &mxf_mpeg2_codec_uls[6+long_gop];
2375     }
2376     return NULL;
2377 }
2378 
mxf_parse_mpeg2_frame(AVFormatContext * s,AVStream * st,AVPacket * pkt,MXFIndexEntry * e)2379 static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st,
2380                                  AVPacket *pkt, MXFIndexEntry *e)
2381 {
2382     MXFStreamContext *sc = st->priv_data;
2383     uint32_t c = -1;
2384     int i;
2385 
2386     for(i = 0; i < pkt->size - 4; i++) {
2387         c = (c<<8) + pkt->data[i];
2388         if (c == 0x1b5) {
2389             if ((pkt->data[i+1] & 0xf0) == 0x10) { // seq ext
2390                 st->codecpar->profile = pkt->data[i+1] & 0x07;
2391                 st->codecpar->level   = pkt->data[i+2] >> 4;
2392                 sc->low_delay = pkt->data[i+6] >> 7;
2393             } else if (i + 5 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x80) { // pict coding ext
2394                 sc->interlaced = !(pkt->data[i+5] & 0x80); // progressive frame
2395                 if (sc->interlaced)
2396                     sc->field_dominance = 1 + !(pkt->data[i+4] & 0x80); // top field first
2397                 break;
2398             }
2399         } else if (c == 0x1b8) { // gop
2400             if (pkt->data[i+4]>>6 & 0x01) { // closed
2401                 if (sc->seq_closed_gop == -1)
2402                     sc->seq_closed_gop = 1;
2403                 sc->closed_gop = 1;
2404                 if (e->flags & 0x40) // sequence header present
2405                     e->flags |= 0x80; // random access
2406             } else {
2407                 sc->seq_closed_gop = 0;
2408                 sc->closed_gop = 0;
2409             }
2410         } else if (c == 0x1b3) { // seq
2411             e->flags |= 0x40;
2412             switch ((pkt->data[i+4]>>4) & 0xf) {
2413             case 2:  sc->aspect_ratio = (AVRational){  4,  3}; break;
2414             case 3:  sc->aspect_ratio = (AVRational){ 16,  9}; break;
2415             case 4:  sc->aspect_ratio = (AVRational){221,100}; break;
2416             default:
2417                 av_reduce(&sc->aspect_ratio.num, &sc->aspect_ratio.den,
2418                           st->codecpar->width, st->codecpar->height, 1024*1024);
2419             }
2420         } else if (c == 0x100) { // pic
2421             int pict_type = (pkt->data[i+2]>>3) & 0x07;
2422             e->temporal_ref = (pkt->data[i+1]<<2) | (pkt->data[i+2]>>6);
2423             if (pict_type == 2) { // P-frame
2424                 e->flags |= 0x22;
2425                 sc->closed_gop = 0; // reset closed GOP, don't matter anymore
2426             } else if (pict_type == 3) { // B-frame
2427                 if (sc->closed_gop)
2428                     e->flags |= 0x13; // only backward prediction
2429                 else
2430                     e->flags |= 0x33;
2431                 sc->temporal_reordering = -1;
2432             } else if (!pict_type) {
2433                 av_log(s, AV_LOG_ERROR, "error parsing mpeg2 frame\n");
2434                 return 0;
2435             }
2436         }
2437     }
2438     if (s->oformat != &ff_mxf_d10_muxer) {
2439         const UID *codec_ul = mxf_get_mpeg2_codec_ul(st->codecpar);
2440         if (!codec_ul)
2441             return 0;
2442         sc->codec_ul = codec_ul;
2443     }
2444     return 1;
2445 }
2446 
mxf_parse_timestamp(int64_t timestamp64)2447 static uint64_t mxf_parse_timestamp(int64_t timestamp64)
2448 {
2449     time_t timestamp = timestamp64 / 1000000;
2450     struct tm tmbuf;
2451     struct tm *time = gmtime_r(&timestamp, &tmbuf);
2452     if (!time)
2453         return 0;
2454     return (uint64_t)(time->tm_year+1900) << 48 |
2455            (uint64_t)(time->tm_mon+1)     << 40 |
2456            (uint64_t) time->tm_mday       << 32 |
2457                       time->tm_hour       << 24 |
2458                       time->tm_min        << 16 |
2459                       time->tm_sec        << 8  |
2460                       (timestamp64 % 1000000) / 4000;
2461 }
2462 
mxf_gen_umid(AVFormatContext * s)2463 static void mxf_gen_umid(AVFormatContext *s)
2464 {
2465     MXFContext *mxf = s->priv_data;
2466     uint32_t seed = av_get_random_seed();
2467     uint64_t umid = seed + 0x5294713400000000LL;
2468 
2469     AV_WB64(mxf->umid  , umid);
2470     AV_WB64(mxf->umid+8, umid>>8);
2471 
2472     mxf->instance_number = seed & 0xFFFFFF;
2473 }
2474 
mxf_init_timecode(AVFormatContext * s,AVStream * st,AVRational tbc)2475 static int mxf_init_timecode(AVFormatContext *s, AVStream *st, AVRational tbc)
2476 {
2477     MXFContext *mxf = s->priv_data;
2478     AVDictionaryEntry *tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
2479 
2480     if (!ff_mxf_get_content_package_rate(tbc)) {
2481         if (s->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL) {
2482             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);
2483             return AVERROR(EINVAL);
2484         } else {
2485             av_log(s, AV_LOG_WARNING, "Unofficial frame rate %d/%d.\n", tbc.den, tbc.num);
2486         }
2487     }
2488 
2489     mxf->timecode_base = (tbc.den + tbc.num/2) / tbc.num;
2490     if (!tcr)
2491         tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
2492 
2493     if (tcr)
2494         return av_timecode_init_from_string(&mxf->tc, av_inv_q(tbc), tcr->value, s);
2495     else
2496         return av_timecode_init(&mxf->tc, av_inv_q(tbc), 0, 0, s);
2497 }
2498 
choose_chroma_location(AVFormatContext * s,AVStream * st)2499 static enum AVChromaLocation choose_chroma_location(AVFormatContext *s, AVStream *st)
2500 {
2501     AVCodecParameters *par = st->codecpar;
2502     const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(par->format);
2503 
2504     if (par->chroma_location != AVCHROMA_LOC_UNSPECIFIED)
2505         return par->chroma_location;
2506 
2507     if (pix_desc) {
2508         if (pix_desc->log2_chroma_h == 0) {
2509             return AVCHROMA_LOC_TOPLEFT;
2510         } else if (pix_desc->log2_chroma_w == 1 && pix_desc->log2_chroma_h == 1) {
2511             if (par->field_order == AV_FIELD_UNKNOWN || par->field_order == AV_FIELD_PROGRESSIVE) {
2512                 switch (par->codec_id) {
2513                 case AV_CODEC_ID_MJPEG:
2514                 case AV_CODEC_ID_MPEG1VIDEO: return AVCHROMA_LOC_CENTER;
2515                 }
2516             }
2517             if (par->field_order == AV_FIELD_UNKNOWN || par->field_order != AV_FIELD_PROGRESSIVE) {
2518                 switch (par->codec_id) {
2519                 case AV_CODEC_ID_MPEG2VIDEO: return AVCHROMA_LOC_LEFT;
2520                 }
2521             }
2522         }
2523     }
2524 
2525     return AVCHROMA_LOC_UNSPECIFIED;
2526 }
2527 
mxf_init(AVFormatContext * s)2528 static int mxf_init(AVFormatContext *s)
2529 {
2530     MXFContext *mxf = s->priv_data;
2531     int i, ret;
2532     uint8_t present[FF_ARRAY_ELEMS(mxf_essence_container_uls)] = {0};
2533     int64_t timestamp = 0;
2534 
2535     if (s->oformat == &ff_mxf_opatom_muxer && s->nb_streams !=1) {
2536         av_log(s, AV_LOG_ERROR, "there must be exactly one stream for mxf opatom\n");
2537         return -1;
2538     }
2539 
2540     if (!av_dict_get(s->metadata, "comment_", NULL, AV_DICT_IGNORE_SUFFIX))
2541         mxf->store_user_comments = 0;
2542 
2543     for (i = 0; i < s->nb_streams; i++) {
2544         AVStream *st = s->streams[i];
2545         MXFStreamContext *sc = av_mallocz(sizeof(*sc));
2546         if (!sc)
2547             return AVERROR(ENOMEM);
2548         st->priv_data = sc;
2549         sc->index = -1;
2550 
2551         if (((i == 0) ^ (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)) && s->oformat != &ff_mxf_opatom_muxer) {
2552             av_log(s, AV_LOG_ERROR, "there must be exactly one video stream and it must be the first one\n");
2553             return -1;
2554         }
2555 
2556         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2557             const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(st->codecpar->format);
2558             // TODO: should be avg_frame_rate
2559             AVRational tbc = st->time_base;
2560             // Default component depth to 8
2561             sc->component_depth = 8;
2562             sc->h_chroma_sub_sample = 2;
2563             sc->v_chroma_sub_sample = 2;
2564             sc->color_siting = 0xFF;
2565 
2566             if (st->codecpar->sample_aspect_ratio.num && st->codecpar->sample_aspect_ratio.den) {
2567                 sc->aspect_ratio = av_mul_q(st->codecpar->sample_aspect_ratio,
2568                                             av_make_q(st->codecpar->width, st->codecpar->height));
2569             }
2570 
2571             if (pix_desc) {
2572                 sc->component_depth     = pix_desc->comp[0].depth;
2573                 sc->h_chroma_sub_sample = 1 << pix_desc->log2_chroma_w;
2574                 sc->v_chroma_sub_sample = 1 << pix_desc->log2_chroma_h;
2575             }
2576             switch (choose_chroma_location(s, st)) {
2577             case AVCHROMA_LOC_TOPLEFT: sc->color_siting = 0; break;
2578             case AVCHROMA_LOC_LEFT:    sc->color_siting = 6; break;
2579             case AVCHROMA_LOC_TOP:     sc->color_siting = 1; break;
2580             case AVCHROMA_LOC_CENTER:  sc->color_siting = 3; break;
2581             }
2582 
2583             mxf->content_package_rate = ff_mxf_get_content_package_rate(tbc);
2584             mxf->time_base = tbc;
2585             avpriv_set_pts_info(st, 64, mxf->time_base.num, mxf->time_base.den);
2586             if((ret = mxf_init_timecode(s, st, tbc)) < 0)
2587                 return ret;
2588 
2589             if (st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
2590                 sc->seq_closed_gop = -1; // unknown yet
2591             }
2592 
2593             sc->video_bit_rate = st->codecpar->bit_rate;
2594 
2595             if (s->oformat == &ff_mxf_d10_muxer ||
2596                 st->codecpar->codec_id == AV_CODEC_ID_DNXHD ||
2597                 st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO)
2598                 mxf->cbr_index = 1;
2599 
2600             if (s->oformat == &ff_mxf_d10_muxer) {
2601                 int ntsc = mxf->time_base.den != 25;
2602                 int ul_index;
2603 
2604                 if (st->codecpar->codec_id != AV_CODEC_ID_MPEG2VIDEO) {
2605                     av_log(s, AV_LOG_ERROR, "error MXF D-10 only support MPEG-2 Video\n");
2606                     return AVERROR(EINVAL);
2607                 }
2608                 if ((sc->video_bit_rate == 50000000) && (mxf->time_base.den == 25)) {
2609                     ul_index = 0;
2610                 } else if ((sc->video_bit_rate == 49999840 || sc->video_bit_rate == 50000000) && ntsc) {
2611                     ul_index = 1;
2612                 } else if (sc->video_bit_rate == 40000000) {
2613                     ul_index = 2+ntsc;
2614                 } else if (sc->video_bit_rate == 30000000) {
2615                     ul_index = 4+ntsc;
2616                 } else {
2617                     av_log(s, AV_LOG_ERROR, "error MXF D-10 only support 30/40/50 mbit/s\n");
2618                     return -1;
2619                 }
2620 
2621                 sc->codec_ul = &mxf_d10_codec_uls[ul_index];
2622                 sc->container_ul = &mxf_d10_container_uls[ul_index];
2623                 sc->index = INDEX_D10_VIDEO;
2624                 sc->signal_standard = 1;
2625                 sc->color_siting = 0;
2626                 sc->frame_size = (int64_t)sc->video_bit_rate *
2627                     mxf->time_base.num / (8*mxf->time_base.den);
2628             }
2629             if (mxf->signal_standard >= 0)
2630                 sc->signal_standard = mxf->signal_standard;
2631         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2632             char bsf_arg[32];
2633             if (st->codecpar->sample_rate != 48000) {
2634                 av_log(s, AV_LOG_ERROR, "only 48khz is implemented\n");
2635                 return -1;
2636             }
2637             avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
2638             if (s->oformat == &ff_mxf_d10_muxer) {
2639                 if (st->index != 1) {
2640                     av_log(s, AV_LOG_ERROR, "MXF D-10 only support one audio track\n");
2641                     return -1;
2642                 }
2643                 if (st->codecpar->codec_id != AV_CODEC_ID_PCM_S16LE &&
2644                     st->codecpar->codec_id != AV_CODEC_ID_PCM_S24LE) {
2645                     av_log(s, AV_LOG_ERROR, "MXF D-10 only support 16 or 24 bits le audio\n");
2646                 }
2647                 sc->index = INDEX_D10_AUDIO;
2648                 sc->container_ul = ((MXFStreamContext*)s->streams[0]->priv_data)->container_ul;
2649                 sc->frame_size = 4 + 8 * av_rescale_rnd(st->codecpar->sample_rate, mxf->time_base.num, mxf->time_base.den, AV_ROUND_UP) * 4;
2650             } else if (s->oformat == &ff_mxf_opatom_muxer) {
2651                 AVRational tbc = av_inv_q(mxf->audio_edit_rate);
2652 
2653                 if (st->codecpar->codec_id != AV_CODEC_ID_PCM_S16LE &&
2654                     st->codecpar->codec_id != AV_CODEC_ID_PCM_S24LE) {
2655                     av_log(s, AV_LOG_ERROR, "Only pcm_s16le and pcm_s24le audio codecs are implemented\n");
2656                     return AVERROR_PATCHWELCOME;
2657                 }
2658                 if (st->codecpar->ch_layout.nb_channels != 1) {
2659                     av_log(s, AV_LOG_ERROR, "MXF OPAtom only supports single channel audio\n");
2660                     return AVERROR(EINVAL);
2661                 }
2662 
2663                 mxf->time_base = st->time_base;
2664                 if((ret = mxf_init_timecode(s, st, tbc)) < 0)
2665                     return ret;
2666 
2667                 mxf->edit_unit_byte_count = (av_get_bits_per_sample(st->codecpar->codec_id) * st->codecpar->ch_layout.nb_channels) >> 3;
2668                 sc->index = INDEX_WAV;
2669             } else {
2670                 mxf->slice_count = 1;
2671                 sc->frame_size = st->codecpar->ch_layout.nb_channels *
2672                                  av_rescale_rnd(st->codecpar->sample_rate, mxf->time_base.num, mxf->time_base.den, AV_ROUND_UP) *
2673                                  av_get_bits_per_sample(st->codecpar->codec_id) / 8;
2674             }
2675             snprintf(bsf_arg, sizeof(bsf_arg), "r=%d/%d", mxf->tc.rate.num, mxf->tc.rate.den);
2676             ret = ff_stream_add_bitstream_filter(st, "pcm_rechunk", bsf_arg);
2677             if (ret < 0)
2678                 return ret;
2679         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
2680             AVDictionaryEntry *e = av_dict_get(st->metadata, "data_type", NULL, 0);
2681             if (e && !strcmp(e->value, "vbi_vanc_smpte_436M")) {
2682                 sc->index = INDEX_S436M;
2683             } else {
2684                 av_log(s, AV_LOG_ERROR, "track %d: unsupported data type\n", i);
2685                 return -1;
2686             }
2687             if (st->index != s->nb_streams - 1) {
2688                 av_log(s, AV_LOG_ERROR, "data track must be placed last\n");
2689                 return -1;
2690             }
2691         }
2692 
2693         if (sc->index == -1) {
2694             sc->index = mxf_get_essence_container_ul_index(st->codecpar->codec_id);
2695             if (sc->index == -1) {
2696                 av_log(s, AV_LOG_ERROR, "track %d: could not find essence container ul, "
2697                        "codec not currently supported in container\n", i);
2698                 return -1;
2699             }
2700         }
2701 
2702         if (!sc->codec_ul)
2703             sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
2704         if (!sc->container_ul)
2705             sc->container_ul = &mxf_essence_container_uls[sc->index].container_ul;
2706 
2707         memcpy(sc->track_essence_element_key, mxf_essence_container_uls[sc->index].element_ul, 15);
2708         sc->track_essence_element_key[15] = present[sc->index];
2709         if (s->oformat == &ff_mxf_opatom_muxer && st->codecpar->codec_id == AV_CODEC_ID_DNXHD) {
2710             // clip-wrapping requires 0x0D per ST2019-4:2009 or 0x06 per previous version ST2019-4:2008
2711             // we choose to use 0x06 instead 0x0D to be compatible with AVID systems
2712             // and produce mxf files with the most relevant flavour for opatom
2713             sc->track_essence_element_key[14] = 0x06;
2714         }
2715         PRINT_KEY(s, "track essence element key", sc->track_essence_element_key);
2716 
2717         if (!present[sc->index])
2718             mxf->essence_container_count++;
2719         present[sc->index]++;
2720     }
2721 
2722     if (s->oformat == &ff_mxf_d10_muxer || s->oformat == &ff_mxf_opatom_muxer) {
2723         mxf->essence_container_count = 1;
2724     }
2725 
2726     if (!(s->flags & AVFMT_FLAG_BITEXACT))
2727         mxf_gen_umid(s);
2728 
2729     for (i = 0; i < s->nb_streams; i++) {
2730         MXFStreamContext *sc = s->streams[i]->priv_data;
2731         // update element count
2732         sc->track_essence_element_key[13] = present[sc->index];
2733         if (!memcmp(sc->track_essence_element_key, mxf_essence_container_uls[INDEX_DV].element_ul, 13)) // DV
2734             sc->order = (0x15 << 24) | AV_RB32(sc->track_essence_element_key+13);
2735         else
2736             sc->order = AV_RB32(sc->track_essence_element_key+12);
2737     }
2738 
2739     if (ff_parse_creation_time_metadata(s, &timestamp, 0) > 0)
2740         mxf->timestamp = mxf_parse_timestamp(timestamp);
2741     mxf->duration = -1;
2742 
2743     mxf->timecode_track = av_mallocz(sizeof(*mxf->timecode_track));
2744     if (!mxf->timecode_track)
2745         return AVERROR(ENOMEM);
2746     mxf->timecode_track->priv_data = &mxf->timecode_track_priv;
2747     mxf->timecode_track->index = -1;
2748 
2749     return 0;
2750 }
2751 
2752 static const uint8_t system_metadata_pack_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04,0x01,0x01,0x00 };
2753 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 };
2754 
mxf_write_system_item(AVFormatContext * s)2755 static void mxf_write_system_item(AVFormatContext *s)
2756 {
2757     MXFContext *mxf = s->priv_data;
2758     AVIOContext *pb = s->pb;
2759     unsigned frame;
2760     uint32_t time_code;
2761     int i, system_item_bitmap = 0x58; // UL, user date/time stamp, picture present
2762 
2763     frame = mxf->last_indexed_edit_unit + mxf->edit_units_count;
2764 
2765     // write system metadata pack
2766     avio_write(pb, system_metadata_pack_key, 16);
2767     klv_encode_ber4_length(pb, 57);
2768 
2769     for (i = 0; i < s->nb_streams; i++) {
2770         if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
2771             system_item_bitmap |= 0x4;
2772         else if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_DATA)
2773             system_item_bitmap |= 0x2;
2774     }
2775     avio_w8(pb, system_item_bitmap);
2776     avio_w8(pb, mxf->content_package_rate); // content package rate
2777     avio_w8(pb, 0x00); // content package type
2778     avio_wb16(pb, 0x00); // channel handle
2779     avio_wb16(pb, frame & 0xFFFF); // continuity count, supposed to overflow
2780     if (mxf->essence_container_count > 1)
2781         avio_write(pb, multiple_desc_ul, 16);
2782     else {
2783         MXFStreamContext *sc = s->streams[0]->priv_data;
2784         avio_write(pb, *sc->container_ul, 16);
2785     }
2786     avio_w8(pb, 0);
2787     avio_wb64(pb, 0);
2788     avio_wb64(pb, 0); // creation date/time stamp
2789 
2790     avio_w8(pb, 0x81); // SMPTE 12M time code
2791     time_code = av_timecode_get_smpte_from_framenum(&mxf->tc, frame);
2792     avio_wb32(pb, time_code);
2793     avio_wb32(pb, 0); // binary group data
2794     avio_wb64(pb, 0);
2795 
2796     // write system metadata package set
2797     avio_write(pb, system_metadata_package_set_key, 16);
2798     klv_encode_ber4_length(pb, 35);
2799     avio_w8(pb, 0x83); // UMID
2800     avio_wb16(pb, 0x20);
2801     mxf_write_umid(s, 1);
2802 }
2803 
mxf_write_d10_audio_packet(AVFormatContext * s,AVStream * st,AVPacket * pkt)2804 static void mxf_write_d10_audio_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt)
2805 {
2806     MXFContext *mxf = s->priv_data;
2807     AVIOContext *pb = s->pb;
2808     int frame_size = pkt->size / st->codecpar->block_align;
2809     const uint8_t *samples = pkt->data;
2810     const uint8_t *const end = pkt->data + pkt->size;
2811     int i;
2812 
2813     klv_encode_ber4_length(pb, 4 + frame_size*4*8);
2814 
2815     avio_w8(pb, (frame_size == 1920 ? 0 : (mxf->edit_units_count-1) % 5 + 1));
2816     avio_wl16(pb, frame_size);
2817     avio_w8(pb, (1 << st->codecpar->ch_layout.nb_channels)-1);
2818 
2819     while (samples < end) {
2820         for (i = 0; i < st->codecpar->ch_layout.nb_channels; i++) {
2821             uint32_t sample;
2822             if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S24LE) {
2823                 sample = AV_RL24(samples)<< 4;
2824                 samples += 3;
2825             } else {
2826                 sample = AV_RL16(samples)<<12;
2827                 samples += 2;
2828             }
2829             avio_wl32(pb, sample | i);
2830         }
2831         for (; i < 8; i++)
2832             avio_wl32(pb, i);
2833     }
2834 }
2835 
mxf_write_opatom_body_partition(AVFormatContext * s)2836 static int mxf_write_opatom_body_partition(AVFormatContext *s)
2837 {
2838     MXFContext *mxf = s->priv_data;
2839     AVIOContext *pb = s->pb;
2840     AVStream *st = s->streams[0];
2841     MXFStreamContext *sc = st->priv_data;
2842     const uint8_t *key = NULL;
2843 
2844     int err;
2845 
2846     if (!mxf->header_written)
2847         key = body_partition_key;
2848 
2849     if ((err = mxf_write_partition(s, 1, 0, key, 0)) < 0)
2850         return err;
2851     mxf_write_klv_fill(s);
2852     avio_write(pb, sc->track_essence_element_key, 16);
2853     klv_encode_ber9_length(pb, mxf->body_offset);
2854     return 0;
2855 }
2856 
mxf_write_opatom_packet(AVFormatContext * s,AVPacket * pkt,MXFIndexEntry * ie)2857 static int mxf_write_opatom_packet(AVFormatContext *s, AVPacket *pkt, MXFIndexEntry *ie)
2858 {
2859     MXFContext *mxf = s->priv_data;
2860     AVIOContext *pb = s->pb;
2861 
2862     int err;
2863 
2864     if (!mxf->header_written) {
2865         if ((err = mxf_write_partition(s, 0, 0, header_open_partition_key, 1)) < 0)
2866             return err;
2867         mxf_write_klv_fill(s);
2868 
2869         if ((err = mxf_write_opatom_body_partition(s)) < 0)
2870             return err;
2871         mxf->header_written = 1;
2872     }
2873 
2874     if (!mxf->edit_unit_byte_count) {
2875         mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;
2876         mxf->index_entries[mxf->edit_units_count].flags = ie->flags;
2877         mxf->index_entries[mxf->edit_units_count].temporal_ref = ie->temporal_ref;
2878     }
2879     mxf->edit_units_count++;
2880     avio_write(pb, pkt->data, pkt->size);
2881     mxf->body_offset += pkt->size;
2882 
2883     return 0;
2884 }
2885 
mxf_compute_edit_unit_byte_count(AVFormatContext * s)2886 static void mxf_compute_edit_unit_byte_count(AVFormatContext *s)
2887 {
2888     MXFContext *mxf = s->priv_data;
2889     int i;
2890 
2891     if (s->oformat == &ff_mxf_opatom_muxer) {
2892         MXFStreamContext *sc = s->streams[0]->priv_data;
2893         mxf->edit_unit_byte_count = sc->frame_size;
2894         return;
2895     }
2896 
2897     mxf->edit_unit_byte_count = KAG_SIZE; // system element
2898     for (i = 0; i < s->nb_streams; i++) {
2899         AVStream *st = s->streams[i];
2900         MXFStreamContext *sc = st->priv_data;
2901         sc->slice_offset = mxf->edit_unit_byte_count;
2902         mxf->edit_unit_byte_count += 16 + 4 + sc->frame_size;
2903         mxf->edit_unit_byte_count += klv_fill_size(mxf->edit_unit_byte_count);
2904     }
2905 }
2906 
mxf_write_packet(AVFormatContext * s,AVPacket * pkt)2907 static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
2908 {
2909     MXFContext *mxf = s->priv_data;
2910     AVIOContext *pb = s->pb;
2911     AVStream *st = s->streams[pkt->stream_index];
2912     MXFStreamContext *sc = st->priv_data;
2913     MXFIndexEntry ie = {0};
2914     int err;
2915 
2916     if (!mxf->header_written && pkt->stream_index != 0 &&
2917         s->oformat != &ff_mxf_opatom_muxer) {
2918         av_log(s, AV_LOG_ERROR, "Received non-video packet before "
2919                                 "header has been written\n");
2920         return AVERROR_INVALIDDATA;
2921     }
2922 
2923     if (!mxf->cbr_index && !mxf->edit_unit_byte_count && !(mxf->edit_units_count % EDIT_UNITS_PER_BODY)) {
2924         if ((err = av_reallocp_array(&mxf->index_entries, mxf->edit_units_count
2925                                      + EDIT_UNITS_PER_BODY, sizeof(*mxf->index_entries))) < 0) {
2926             mxf->edit_units_count = 0;
2927             av_log(s, AV_LOG_ERROR, "could not allocate index entries\n");
2928             return err;
2929         }
2930     }
2931 
2932     if (st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
2933         if (!mxf_parse_mpeg2_frame(s, st, pkt, &ie)) {
2934             av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
2935             return -1;
2936         }
2937     } else if (st->codecpar->codec_id == AV_CODEC_ID_DNXHD) {
2938         if (!mxf_parse_dnxhd_frame(s, st, pkt)) {
2939             av_log(s, AV_LOG_ERROR, "could not get dnxhd profile\n");
2940             return -1;
2941         }
2942     } else if (st->codecpar->codec_id == AV_CODEC_ID_PRORES) {
2943         if (!mxf_parse_prores_frame(s, st, pkt)) {
2944             av_log(s, AV_LOG_ERROR, "could not get prores profile\n");
2945             return -1;
2946         }
2947     } else if (st->codecpar->codec_id == AV_CODEC_ID_DVVIDEO) {
2948         if (!mxf_parse_dv_frame(s, st, pkt)) {
2949             av_log(s, AV_LOG_ERROR, "could not get dv profile\n");
2950             return -1;
2951         }
2952     } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
2953         if (!mxf_parse_h264_frame(s, st, pkt, &ie)) {
2954             av_log(s, AV_LOG_ERROR, "could not get h264 profile\n");
2955             return -1;
2956         }
2957     }
2958 
2959     if (mxf->cbr_index) {
2960         if (pkt->size != sc->frame_size && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2961             av_log(s, AV_LOG_ERROR, "track %d: frame size does not match index unit size, %d != %d\n",
2962                    st->index, pkt->size, sc->frame_size);
2963             return -1;
2964         }
2965         if (!mxf->header_written)
2966             mxf_compute_edit_unit_byte_count(s);
2967     }
2968 
2969     if (s->oformat == &ff_mxf_opatom_muxer)
2970         return mxf_write_opatom_packet(s, pkt, &ie);
2971 
2972     if (!mxf->header_written) {
2973         if (mxf->edit_unit_byte_count) {
2974             if ((err = mxf_write_partition(s, 1, 2, header_open_partition_key, 1)) < 0)
2975                 return err;
2976             mxf_write_klv_fill(s);
2977             mxf_write_index_table_segment(s);
2978         } else {
2979             if ((err = mxf_write_partition(s, 0, 0, header_open_partition_key, 1)) < 0)
2980                 return err;
2981         }
2982         mxf->header_written = 1;
2983     }
2984 
2985     if (st->index == 0) {
2986         if (!mxf->edit_unit_byte_count &&
2987             (!mxf->edit_units_count || mxf->edit_units_count > EDIT_UNITS_PER_BODY) &&
2988             !(ie.flags & 0x33)) { // I-frame, GOP start
2989             mxf_write_klv_fill(s);
2990             if ((err = mxf_write_partition(s, 1, 2, body_partition_key, 0)) < 0)
2991                 return err;
2992             mxf_write_klv_fill(s);
2993             mxf_write_index_table_segment(s);
2994         }
2995 
2996         mxf_write_klv_fill(s);
2997         mxf_write_system_item(s);
2998 
2999         if (!mxf->edit_unit_byte_count) {
3000             mxf->index_entries[mxf->edit_units_count].offset = mxf->body_offset;
3001             mxf->index_entries[mxf->edit_units_count].flags = ie.flags;
3002             mxf->index_entries[mxf->edit_units_count].temporal_ref = ie.temporal_ref;
3003             mxf->body_offset += KAG_SIZE; // size of system element
3004         }
3005         mxf->edit_units_count++;
3006     } else if (!mxf->edit_unit_byte_count && st->index == 1) {
3007         if (!mxf->edit_units_count) {
3008             av_log(s, AV_LOG_ERROR, "No packets in first stream\n");
3009             return AVERROR_PATCHWELCOME;
3010         }
3011         mxf->index_entries[mxf->edit_units_count-1].slice_offset =
3012             mxf->body_offset - mxf->index_entries[mxf->edit_units_count-1].offset;
3013     }
3014 
3015     mxf_write_klv_fill(s);
3016     avio_write(pb, sc->track_essence_element_key, 16); // write key
3017     if (s->oformat == &ff_mxf_d10_muxer &&
3018         st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3019         mxf_write_d10_audio_packet(s, st, pkt);
3020     } else {
3021         klv_encode_ber4_length(pb, pkt->size); // write length
3022         avio_write(pb, pkt->data, pkt->size);
3023         mxf->body_offset += 16+4+pkt->size + klv_fill_size(16+4+pkt->size);
3024     }
3025 
3026     return 0;
3027 }
3028 
mxf_write_random_index_pack(AVFormatContext * s)3029 static void mxf_write_random_index_pack(AVFormatContext *s)
3030 {
3031     MXFContext *mxf = s->priv_data;
3032     AVIOContext *pb = s->pb;
3033     uint64_t pos = avio_tell(pb);
3034     int i;
3035 
3036     avio_write(pb, ff_mxf_random_index_pack_key, 16);
3037     klv_encode_ber_length(pb, 28 + 12LL*mxf->body_partitions_count);
3038 
3039     if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer)
3040         avio_wb32(pb, 1); // BodySID of header partition
3041     else
3042         avio_wb32(pb, 0);
3043     avio_wb64(pb, 0); // offset of header partition
3044 
3045     for (i = 0; i < mxf->body_partitions_count; i++) {
3046         avio_wb32(pb, 1); // BodySID
3047         avio_wb64(pb, mxf->body_partition_offset[i]);
3048     }
3049 
3050     avio_wb32(pb, 0); // BodySID of footer partition
3051     avio_wb64(pb, mxf->footer_partition_offset);
3052 
3053     avio_wb32(pb, avio_tell(pb) - pos + 4);
3054 }
3055 
mxf_write_footer(AVFormatContext * s)3056 static int mxf_write_footer(AVFormatContext *s)
3057 {
3058     MXFContext *mxf = s->priv_data;
3059     AVIOContext *pb = s->pb;
3060     int i, err;
3061 
3062     if (!mxf->header_written ||
3063         (s->oformat == &ff_mxf_opatom_muxer && !mxf->body_partition_offset)) {
3064         /* reason could be invalid options/not supported codec/out of memory */
3065         return AVERROR_UNKNOWN;
3066     }
3067 
3068     mxf->duration = mxf->last_indexed_edit_unit + mxf->edit_units_count;
3069 
3070     mxf_write_klv_fill(s);
3071     mxf->footer_partition_offset = avio_tell(pb);
3072     if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer) { // no need to repeat index
3073         if ((err = mxf_write_partition(s, 0, 0, footer_partition_key, 0)) < 0)
3074             return err;
3075     } else {
3076         if ((err = mxf_write_partition(s, 0, 2, footer_partition_key, 0)) < 0)
3077             return err;
3078         mxf_write_klv_fill(s);
3079         mxf_write_index_table_segment(s);
3080     }
3081 
3082     mxf_write_klv_fill(s);
3083     mxf_write_random_index_pack(s);
3084 
3085     if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
3086         if (s->oformat == &ff_mxf_opatom_muxer) {
3087             /* rewrite body partition to update lengths */
3088             avio_seek(pb, mxf->body_partition_offset[0], SEEK_SET);
3089             if ((err = mxf_write_opatom_body_partition(s)) < 0)
3090                 return err;
3091         }
3092 
3093         avio_seek(pb, 0, SEEK_SET);
3094         if (mxf->edit_unit_byte_count && s->oformat != &ff_mxf_opatom_muxer) {
3095             if ((err = mxf_write_partition(s, 1, 2, header_closed_partition_key, 1)) < 0)
3096                 return err;
3097             mxf_write_klv_fill(s);
3098             mxf_write_index_table_segment(s);
3099         } else {
3100             if ((err = mxf_write_partition(s, 0, 0, header_closed_partition_key, 1)) < 0)
3101                 return err;
3102         }
3103         // update footer partition offset
3104         for (i = 0; i < mxf->body_partitions_count; i++) {
3105             avio_seek(pb, mxf->body_partition_offset[i]+44, SEEK_SET);
3106             avio_wb64(pb, mxf->footer_partition_offset);
3107         }
3108     }
3109 
3110     return 0;
3111 }
3112 
mxf_deinit(AVFormatContext * s)3113 static void mxf_deinit(AVFormatContext *s)
3114 {
3115     MXFContext *mxf = s->priv_data;
3116 
3117     av_freep(&mxf->index_entries);
3118     av_freep(&mxf->body_partition_offset);
3119     av_freep(&mxf->timecode_track);
3120 }
3121 
mxf_interleave_get_packet(AVFormatContext * s,AVPacket * out,int flush)3122 static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, int flush)
3123 {
3124     FFFormatContext *const si = ffformatcontext(s);
3125     int i, stream_count = 0;
3126 
3127     for (i = 0; i < s->nb_streams; i++)
3128         stream_count += !!ffstream(s->streams[i])->last_in_packet_buffer;
3129 
3130     if (stream_count && (s->nb_streams == stream_count || flush)) {
3131         PacketListEntry *pktl = si->packet_buffer.head;
3132         if (s->nb_streams != stream_count) {
3133             PacketListEntry *last = NULL;
3134             // find last packet in edit unit
3135             while (pktl) {
3136                 if (!stream_count || pktl->pkt.stream_index == 0)
3137                     break;
3138                 // update last packet in packet buffer
3139                 if (ffstream(s->streams[pktl->pkt.stream_index])->last_in_packet_buffer != pktl)
3140                     ffstream(s->streams[pktl->pkt.stream_index])->last_in_packet_buffer = pktl;
3141                 last = pktl;
3142                 pktl = pktl->next;
3143                 stream_count--;
3144             }
3145             // purge packet queue
3146             while (pktl) {
3147                 PacketListEntry *next = pktl->next;
3148                 av_packet_unref(&pktl->pkt);
3149                 av_freep(&pktl);
3150                 pktl = next;
3151             }
3152             if (last)
3153                 last->next = NULL;
3154             else {
3155                 si->packet_buffer.head = NULL;
3156                 si->packet_buffer.tail = NULL;
3157                 goto out;
3158             }
3159             pktl = si->packet_buffer.head;
3160         }
3161 
3162         if (ffstream(s->streams[pktl->pkt.stream_index])->last_in_packet_buffer == pktl)
3163             ffstream(s->streams[pktl->pkt.stream_index])->last_in_packet_buffer = NULL;
3164         avpriv_packet_list_get(&si->packet_buffer, out);
3165         av_log(s, AV_LOG_TRACE, "out st:%d dts:%"PRId64"\n", out->stream_index, out->dts);
3166         return 1;
3167     } else {
3168     out:
3169         return 0;
3170     }
3171 }
3172 
mxf_compare_timestamps(AVFormatContext * s,const AVPacket * next,const AVPacket * pkt)3173 static int mxf_compare_timestamps(AVFormatContext *s, const AVPacket *next,
3174                                                       const AVPacket *pkt)
3175 {
3176     MXFStreamContext *sc  = s->streams[pkt ->stream_index]->priv_data;
3177     MXFStreamContext *sc2 = s->streams[next->stream_index]->priv_data;
3178 
3179     return next->dts > pkt->dts ||
3180         (next->dts == pkt->dts && sc->order < sc2->order);
3181 }
3182 
mxf_interleave(AVFormatContext * s,AVPacket * pkt,int flush,int has_packet)3183 static int mxf_interleave(AVFormatContext *s, AVPacket *pkt,
3184                           int flush, int has_packet)
3185 {
3186     int ret;
3187     if (has_packet) {
3188         MXFStreamContext *sc = s->streams[pkt->stream_index]->priv_data;
3189         pkt->pts = pkt->dts = sc->pkt_cnt++;
3190         if ((ret = ff_interleave_add_packet(s, pkt, mxf_compare_timestamps)) < 0)
3191             return ret;
3192     }
3193     return mxf_interleave_get_packet(s, pkt, flush);
3194 }
3195 
3196 #define MXF_COMMON_OPTIONS \
3197     { "signal_standard", "Force/set Signal Standard",\
3198       offsetof(MXFContext, signal_standard), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3199     { "bt601", "ITU-R BT.601 and BT.656, also SMPTE 125M (525 and 625 line interlaced)",\
3200       0, AV_OPT_TYPE_CONST, {.i64 = 1}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3201     { "bt1358", "ITU-R BT.1358 and ITU-R BT.799-3, also SMPTE 293M (525 and 625 line progressive)",\
3202       0, AV_OPT_TYPE_CONST, {.i64 = 2}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3203     { "smpte347m", "SMPTE 347M (540 Mbps mappings)",\
3204       0, AV_OPT_TYPE_CONST, {.i64 = 3}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3205     { "smpte274m", "SMPTE 274M (1125 line)",\
3206       0, AV_OPT_TYPE_CONST, {.i64 = 4}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3207     { "smpte296m", "SMPTE 296M (750 line progressive)",\
3208       0, AV_OPT_TYPE_CONST, {.i64 = 5}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3209     { "smpte349m", "SMPTE 349M (1485 Mbps mappings)",\
3210       0, AV_OPT_TYPE_CONST, {.i64 = 6}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},\
3211     { "smpte428", "SMPTE 428-1 DCDM",\
3212       0, AV_OPT_TYPE_CONST, {.i64 = 7}, -1, 7, AV_OPT_FLAG_ENCODING_PARAM, "signal_standard"},
3213 
3214 
3215 
3216 static const AVOption mxf_options[] = {
3217     MXF_COMMON_OPTIONS
3218     { "store_user_comments", "",
3219       offsetof(MXFContext, store_user_comments), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
3220     { NULL },
3221 };
3222 
3223 static const AVClass mxf_muxer_class = {
3224     .class_name     = "MXF muxer",
3225     .item_name      = av_default_item_name,
3226     .option         = mxf_options,
3227     .version        = LIBAVUTIL_VERSION_INT,
3228 };
3229 
3230 static const AVOption d10_options[] = {
3231     { "d10_channelcount", "Force/set channelcount in generic sound essence descriptor",
3232       offsetof(MXFContext, channel_count), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 8, AV_OPT_FLAG_ENCODING_PARAM},
3233     MXF_COMMON_OPTIONS
3234     { "store_user_comments", "",
3235       offsetof(MXFContext, store_user_comments), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
3236     { NULL },
3237 };
3238 
3239 static const AVClass mxf_d10_muxer_class = {
3240     .class_name     = "MXF-D10 muxer",
3241     .item_name      = av_default_item_name,
3242     .option         = d10_options,
3243     .version        = LIBAVUTIL_VERSION_INT,
3244 };
3245 
3246 static const AVOption opatom_options[] = {
3247     { "mxf_audio_edit_rate", "Audio edit rate for timecode",
3248         offsetof(MXFContext, audio_edit_rate), AV_OPT_TYPE_RATIONAL, {.dbl=25}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
3249     MXF_COMMON_OPTIONS
3250     { "store_user_comments", "",
3251       offsetof(MXFContext, store_user_comments), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
3252     { NULL },
3253 };
3254 
3255 static const AVClass mxf_opatom_muxer_class = {
3256     .class_name     = "MXF-OPAtom muxer",
3257     .item_name      = av_default_item_name,
3258     .option         = opatom_options,
3259     .version        = LIBAVUTIL_VERSION_INT,
3260 };
3261 
3262 const AVOutputFormat ff_mxf_muxer = {
3263     .name              = "mxf",
3264     .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format)"),
3265     .mime_type         = "application/mxf",
3266     .extensions        = "mxf",
3267     .priv_data_size    = sizeof(MXFContext),
3268     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
3269     .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
3270     .init              = mxf_init,
3271     .write_packet      = mxf_write_packet,
3272     .write_trailer     = mxf_write_footer,
3273     .deinit            = mxf_deinit,
3274     .flags             = AVFMT_NOTIMESTAMPS,
3275     .interleave_packet = mxf_interleave,
3276     .priv_class        = &mxf_muxer_class,
3277 };
3278 
3279 const AVOutputFormat ff_mxf_d10_muxer = {
3280     .name              = "mxf_d10",
3281     .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format) D-10 Mapping"),
3282     .mime_type         = "application/mxf",
3283     .priv_data_size    = sizeof(MXFContext),
3284     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
3285     .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
3286     .init              = mxf_init,
3287     .write_packet      = mxf_write_packet,
3288     .write_trailer     = mxf_write_footer,
3289     .deinit            = mxf_deinit,
3290     .flags             = AVFMT_NOTIMESTAMPS,
3291     .interleave_packet = mxf_interleave,
3292     .priv_class        = &mxf_d10_muxer_class,
3293 };
3294 
3295 const AVOutputFormat ff_mxf_opatom_muxer = {
3296     .name              = "mxf_opatom",
3297     .long_name         = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format) Operational Pattern Atom"),
3298     .mime_type         = "application/mxf",
3299     .extensions        = "mxf",
3300     .priv_data_size    = sizeof(MXFContext),
3301     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
3302     .video_codec       = AV_CODEC_ID_DNXHD,
3303     .init              = mxf_init,
3304     .write_packet      = mxf_write_packet,
3305     .write_trailer     = mxf_write_footer,
3306     .deinit            = mxf_deinit,
3307     .flags             = AVFMT_NOTIMESTAMPS,
3308     .interleave_packet = mxf_interleave,
3309     .priv_class        = &mxf_opatom_muxer_class,
3310 };
3311