d7280223bfb7080e9d56389d602d29a02f10c8a1
[ffmpeg.git] / libavformat / mxfenc.c
1 /*
2  * MXF muxer
3  * Copyright (c) 2008 GUCAS, Zhentan Feng <spyfeng at gmail dot com>
4  * Copyright (c) 2008 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /*
24  * References
25  * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
26  * SMPTE 377M MXF File Format Specifications
27  * SMPTE 379M MXF Generic Container
28  * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
29  * SMPTE RP210: SMPTE Metadata Dictionary
30  * SMPTE RP224: Registry of SMPTE Universal Labels
31  */
32
33 //#define DEBUG
34
35 #include <math.h>
36
37 #include "libavutil/fifo.h"
38 #include "mxf.h"
39
40 static const int NTSC_samples_per_frame[] = { 1602, 1601, 1602, 1601, 1602, 0 };
41 static const int PAL_samples_per_frame[]  = { 1920, 0 };
42
43 #define MXF_INDEX_CLUSTER_SIZE 4096
44
45 typedef struct {
46     AVFifoBuffer fifo;
47     unsigned fifo_size;           ///< current fifo size allocated
48     uint64_t dts;                 ///< current dts
49     int sample_size;              ///< size of one sample all channels included
50     const int *samples_per_frame; ///< must be 0 terminated
51     const int *samples;           ///< current samples per frame, pointer to samples_per_frame
52 } AudioInterleaveContext;
53
54 typedef struct {
55     int local_tag;
56     UID uid;
57 } MXFLocalTagPair;
58
59 typedef struct {
60     uint8_t flags;
61     uint64_t offset;
62     unsigned slice_offset[17]; // one video, 16 audio
63 } MXFIndexEntry;
64
65 typedef struct {
66     AudioInterleaveContext aic;
67     UID track_essence_element_key;
68     int index;            ///< index in mxf_essence_container_uls table
69     const UID *codec_ul;
70     int64_t duration;
71     int order;            ///< interleaving order if dts are equal
72     int interlaced;       ///< wether picture is interlaced
73     int temporal_reordering;
74 } MXFStreamContext;
75
76 typedef struct {
77     UID container_ul;
78     UID element_ul;
79     UID codec_ul;
80     void (*write_desc)();
81 } MXFContainerEssenceEntry;
82
83 static const struct {
84     enum CodecID id;
85     int index;
86 } mxf_essence_mappings[] = {
87     { CODEC_ID_MPEG2VIDEO, 0 },
88     { CODEC_ID_PCM_S24LE,  1 },
89     { CODEC_ID_PCM_S16LE,  1 },
90     { 0 }
91 };
92
93 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st);
94 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st);
95 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st);
96
97 static const MXFContainerEssenceEntry mxf_essence_container_uls[] = {
98     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 },
99       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
100       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
101       mxf_write_mpegvideo_desc },
102     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x03,0x00 },
103       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x03,0x00 },
104       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
105       mxf_write_aes3_desc },
106     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 },
107       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x01,0x00 },
108       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
109       mxf_write_wav_desc },
110     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
111       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
112       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
113       NULL },
114 };
115
116 typedef struct MXFContext {
117     int64_t footer_partition_offset;
118     int essence_container_count;
119     uint8_t essence_containers_indices[FF_ARRAY_ELEMS(mxf_essence_container_uls)];
120     AVRational time_base;
121     int header_written;
122     MXFIndexEntry *index_entries;
123     unsigned edit_units_count;
124     int edit_unit_start;  ///< index of the stream starting edit unit
125 } MXFContext;
126
127 static const uint8_t uuid_base[]            = { 0xAD,0xAB,0x44,0x24,0x2f,0x25,0x4d,0xc7,0x92,0xff,0x29,0xbd };
128 static const uint8_t umid_base[]            = { 0x06,0x0A,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x01,0x0D,0x00,0x13,0x00,0x00,0x00 };
129
130 /**
131  * complete key for operation pattern, partitions, and primer pack
132  */
133 static const uint8_t op1a_ul[]                     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x01,0x01,0x00 };
134 static const uint8_t footer_partition_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }; // ClosedComplete
135 static const uint8_t primer_pack_key[]             = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x05,0x01,0x00 };
136 static const uint8_t index_table_segment_key[]     = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 };
137 static const uint8_t random_index_pack_key[]       = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x11,0x01,0x00 };
138 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
139 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
140
141 /**
142  * partial key for header metadata
143  */
144 static const uint8_t header_metadata_key[]  = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01 };
145 static const uint8_t multiple_desc_ul[]     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x0D,0x01,0x03,0x01,0x02,0x7F,0x01,0x00 };
146
147 /**
148  * SMPTE RP210 http://www.smpte-ra.org/mdd/index.html
149  */
150 static const MXFLocalTagPair mxf_local_tag_batch[] = {
151     // preface set
152     { 0x3C0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x02,0x00,0x00,0x00,0x00}}, /* Instance UID */
153     { 0x3B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x04,0x00,0x00}}, /* Last Modified Date */
154     { 0x3B05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x01,0x05,0x00,0x00,0x00}}, /* Version */
155     { 0x3B06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x04,0x00,0x00}}, /* Identifications reference */
156     { 0x3B03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x01,0x00,0x00}}, /* Content Storage reference */
157     { 0x3B09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x03,0x00,0x00,0x00,0x00}}, /* Operational Pattern UL */
158     { 0x3B0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x01,0x00,0x00}}, /* Essence Containers UL batch */
159     { 0x3B0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x02,0x00,0x00}}, /* DM Schemes UL batch */
160     // Identification
161     { 0x3C09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x01,0x00,0x00,0x00}}, /* This Generation UID */
162     { 0x3C01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x02,0x01,0x00,0x00}}, /* Company Name */
163     { 0x3C02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x03,0x01,0x00,0x00}}, /* Product Name */
164     { 0x3C04, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x05,0x01,0x00,0x00}}, /* Version String */
165     { 0x3C05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x07,0x00,0x00,0x00}}, /* Product ID */
166     { 0x3C06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x03,0x00,0x00}}, /* Modification Date */
167     // Content Storage
168     { 0x1901, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x01,0x00,0x00}}, /* Package strong reference batch */
169     { 0x1902, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x02,0x00,0x00}}, /* Package strong reference batch */
170     // Essence Container Data
171     { 0x2701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x06,0x01,0x00,0x00,0x00}}, /* Linked Package UID */
172     { 0x3F07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x04,0x00,0x00,0x00,0x00}}, /* BodySID */
173     // Package
174     { 0x4401, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x10,0x00,0x00,0x00,0x00}}, /* Package UID */
175     { 0x4405, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x01,0x03,0x00,0x00}}, /* Package Creation Date */
176     { 0x4404, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x05,0x00,0x00}}, /* Package Modified Date */
177     { 0x4403, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x05,0x00,0x00}}, /* Tracks Strong reference array */
178     { 0x4701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x03,0x00,0x00}}, /* Descriptor */
179     // Track
180     { 0x4801, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x07,0x01,0x01,0x00,0x00,0x00,0x00}}, /* Track ID */
181     { 0x4804, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x04,0x01,0x03,0x00,0x00,0x00,0x00}}, /* Track Number */
182     { 0x4B01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x30,0x04,0x05,0x00,0x00,0x00,0x00}}, /* Edit Rate */
183     { 0x4B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x03,0x00,0x00}}, /* Origin */
184     { 0x4803, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x04,0x00,0x00}}, /* Sequence reference */
185     // Sequence
186     { 0x0201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x07,0x01,0x00,0x00,0x00,0x00,0x00}}, /* Data Definition UL */
187     { 0x0202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x02,0x01,0x01,0x03,0x00,0x00}}, /* Duration */
188     { 0x1001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x09,0x00,0x00}}, /* Structural Components reference array */
189     // Source Clip
190     { 0x1201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x01,0x03,0x01,0x04,0x00,0x00}}, /* Start position */
191     { 0x1101, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x01,0x00,0x00,0x00}}, /* SourcePackageID */
192     { 0x1102, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x02,0x00,0x00,0x00}}, /* SourceTrackID */
193     // File Descriptor
194     { 0x3F01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x04,0x06,0x0B,0x00,0x00}}, /* Sub Descriptors reference array */
195     { 0x3006, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x06,0x01,0x01,0x03,0x05,0x00,0x00,0x00}}, /* Linked Track ID */
196     { 0x3001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x00,0x00,0x00,0x00}}, /* SampleRate */
197     { 0x3004, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x01,0x02,0x00,0x00}}, /* Essence Container */
198     // Generic Picture Essence Descriptor
199     { 0x320C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Frame Layout */
200     { 0x320D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x03,0x02,0x05,0x00,0x00,0x00}}, /* Video Line Map */
201     { 0x3203, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x02,0x00,0x00,0x00}}, /* Stored Width */
202     { 0x3202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x01,0x00,0x00,0x00}}, /* Stored Height */
203     { 0x3209, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0C,0x00,0x00,0x00}}, /* Display Width */
204     { 0x3208, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0B,0x00,0x00,0x00}}, /* Display Height */
205     { 0x320E, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x01,0x01,0x01,0x00,0x00,0x00}}, /* Aspect Ratio */
206     { 0x3201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x06,0x01,0x00,0x00,0x00,0x00}}, /* Picture Essence Coding */
207     // Generic Sound Essence Descriptor
208     { 0x3D02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Locked/Unlocked */
209     { 0x3D03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x01,0x01,0x01,0x00,0x00}}, /* Audio sampling rate */
210     { 0x3D07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x01,0x01,0x04,0x00,0x00,0x00}}, /* ChannelCount */
211     { 0x3D01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x03,0x04,0x00,0x00,0x00}}, /* Quantization bits */
212     { 0x3D06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x02,0x04,0x02,0x00,0x00,0x00,0x00}}, /* Sound Essence Compression */
213     // Index Table Segment
214     { 0x3F0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x05,0x30,0x04,0x06,0x00,0x00,0x00,0x00}}, /* Index Edit Rate */
215     { 0x3F0C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x01,0x03,0x01,0x0A,0x00,0x00}}, /* Index Start Position */
216     { 0x3F0D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x02,0x01,0x01,0x02,0x00,0x00}}, /* Index Duration */
217     { 0x3F05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x06,0x02,0x01,0x00,0x00,0x00,0x00,0x00}}, /* Edit Unit Byte Count */
218     { 0x3F06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x05,0x00,0x00,0x00,0x00}}, /* IndexSID */
219     { 0x3F08, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x04,0x04,0x01,0x01,0x00,0x00,0x00}}, /* Slice Count */
220     { 0x3F09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x01,0x06,0x00,0x00,0x00}}, /* Delta Entry Array */
221     { 0x3F0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x02,0x05,0x00,0x00,0x00}}, /* Index Entry Array */
222     // MPEG video Descriptor
223     { 0x8000, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x0B,0x00,0x00}}, /* BitRate */
224     // Wave Audio Essence Descriptor
225     { 0x3D09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x03,0x05,0x00,0x00,0x00}}, /* Average Bytes Per Second */
226     { 0x3D0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x02,0x01,0x00,0x00,0x00}}, /* Block Align */
227 };
228
229 static void mxf_write_uuid(ByteIOContext *pb, enum MXFMetadataSetType type, int value)
230 {
231     put_buffer(pb, uuid_base, 12);
232     put_be16(pb, type);
233     put_be16(pb, value);
234 }
235
236 static void mxf_write_umid(ByteIOContext *pb, enum MXFMetadataSetType type, int value)
237 {
238     put_buffer(pb, umid_base, 16);
239     mxf_write_uuid(pb, type, value);
240 }
241
242 static void mxf_write_refs_count(ByteIOContext *pb, int ref_count)
243 {
244     put_be32(pb, ref_count);
245     put_be32(pb, 16);
246 }
247
248 static int klv_encode_ber_length(ByteIOContext *pb, uint64_t len)
249 {
250     // Determine the best BER size
251     int size;
252     if (len < 128) {
253         //short form
254         put_byte(pb, len);
255         return 1;
256     }
257
258     size = (av_log2(len) >> 3) + 1;
259
260     // long form
261     put_byte(pb, 0x80 + size);
262     while(size) {
263         size--;
264         put_byte(pb, len >> 8 * size & 0xff);
265     }
266     return 0;
267 }
268
269 /*
270  * Get essence container ul index
271  */
272 static int mxf_get_essence_container_ul_index(enum CodecID id)
273 {
274     int i;
275     for (i = 0; mxf_essence_mappings[i].id; i++)
276         if (mxf_essence_mappings[i].id == id)
277             return mxf_essence_mappings[i].index;
278     return -1;
279 }
280
281 static void mxf_write_primer_pack(AVFormatContext *s)
282 {
283     ByteIOContext *pb = s->pb;
284     int local_tag_number, i = 0;
285
286     local_tag_number = FF_ARRAY_ELEMS(mxf_local_tag_batch);
287
288     put_buffer(pb, primer_pack_key, 16);
289     klv_encode_ber_length(pb, local_tag_number * 18 + 8);
290
291     put_be32(pb, local_tag_number); // local_tag num
292     put_be32(pb, 18); // item size, always 18 according to the specs
293
294     for (i = 0; i < local_tag_number; i++) {
295         put_be16(pb, mxf_local_tag_batch[i].local_tag);
296         put_buffer(pb, mxf_local_tag_batch[i].uid, 16);
297     }
298 }
299
300 static void mxf_write_local_tag(ByteIOContext *pb, int size, int tag)
301 {
302     put_be16(pb, tag);
303     put_be16(pb, size);
304 }
305
306 static void mxf_write_metadata_key(ByteIOContext *pb, unsigned int value)
307 {
308     put_buffer(pb, header_metadata_key, 13);
309     put_be24(pb, value);
310 }
311
312 static void mxf_free(AVFormatContext *s)
313 {
314     int i;
315
316     for (i = 0; i < s->nb_streams; i++) {
317         AVStream *st = s->streams[i];
318         av_freep(&st->priv_data);
319     }
320 }
321
322 static const MXFDataDefinitionUL *mxf_get_data_definition_ul(enum CodecType type)
323 {
324     const MXFDataDefinitionUL *uls = ff_mxf_data_definition_uls;
325     while (uls->type != CODEC_TYPE_DATA) {
326         if (type == uls->type)
327             break;
328         uls++;
329     }
330     return uls;
331 }
332
333 static void mxf_write_essence_container_refs(AVFormatContext *s)
334 {
335     MXFContext *c = s->priv_data;
336     ByteIOContext *pb = s->pb;
337     int i;
338
339     mxf_write_refs_count(pb, c->essence_container_count);
340     av_log(s,AV_LOG_DEBUG, "essence container count:%d\n", c->essence_container_count);
341     for (i = 0; i < c->essence_container_count; i++) {
342         put_buffer(pb, mxf_essence_container_uls[c->essence_containers_indices[i]].container_ul, 16);
343         PRINT_KEY(s, "essence container ul:\n", mxf_essence_container_uls[c->essence_containers_indices[i]].container_ul);
344     }
345 }
346
347 static void mxf_write_preface(AVFormatContext *s)
348 {
349     MXFContext *mxf = s->priv_data;
350     ByteIOContext *pb = s->pb;
351
352     mxf_write_metadata_key(pb, 0x012f00);
353     PRINT_KEY(s, "preface key", pb->buf_ptr - 16);
354     klv_encode_ber_length(pb, 130 + 16 * mxf->essence_container_count);
355
356     // write preface set uid
357     mxf_write_local_tag(pb, 16, 0x3C0A);
358     mxf_write_uuid(pb, Preface, 0);
359     PRINT_KEY(s, "preface uid", pb->buf_ptr - 16);
360
361     // write create date as unknown
362     mxf_write_local_tag(pb, 8, 0x3B02);
363     put_be64(pb, 0);
364
365     // write version
366     mxf_write_local_tag(pb, 2, 0x3B05);
367     put_be16(pb, 1);
368
369     // write identification_refs
370     mxf_write_local_tag(pb, 16 + 8, 0x3B06);
371     mxf_write_refs_count(pb, 1);
372     mxf_write_uuid(pb, Identification, 0);
373
374     // write content_storage_refs
375     mxf_write_local_tag(pb, 16, 0x3B03);
376     mxf_write_uuid(pb, ContentStorage, 0);
377
378     mxf_write_local_tag(pb, 16, 0x3B09);
379     put_buffer(pb, op1a_ul, 16);
380
381     // write essence_container_refs
382     mxf_write_local_tag(pb, 8 + 16 * mxf->essence_container_count, 0x3B0A);
383     mxf_write_essence_container_refs(s);
384
385     // write dm_scheme_refs
386     mxf_write_local_tag(pb, 8, 0x3B0B);
387     put_be64(pb, 0);
388 }
389
390 /*
391  * Write a local tag containing an ascii string as utf-16
392  */
393 static void mxf_write_local_tag_utf16(ByteIOContext *pb, int tag, const char *value)
394 {
395     int i, size = strlen(value);
396     mxf_write_local_tag(pb, size*2, tag);
397     for (i = 0; i < size; i++)
398         put_be16(pb, value[i]);
399 }
400
401 static void mxf_write_identification(AVFormatContext *s)
402 {
403     ByteIOContext *pb = s->pb;
404     const char *company = "FFmpeg";
405     const char *product = "OP1a Muxer";
406     const char *version;
407     int length;
408
409     mxf_write_metadata_key(pb, 0x013000);
410     PRINT_KEY(s, "identification key", pb->buf_ptr - 16);
411
412     version = s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT ?
413         "0.0.0" : AV_STRINGIFY(LIBAVFORMAT_VERSION);
414     length = 84 + (strlen(company)+strlen(product)+strlen(version))*2; // utf-16
415     klv_encode_ber_length(pb, length);
416
417     // write uid
418     mxf_write_local_tag(pb, 16, 0x3C0A);
419     mxf_write_uuid(pb, Identification, 0);
420     PRINT_KEY(s, "identification uid", pb->buf_ptr - 16);
421
422     // write generation uid
423     mxf_write_local_tag(pb, 16, 0x3C09);
424     mxf_write_uuid(pb, Identification, 1);
425
426     mxf_write_local_tag_utf16(pb, 0x3C01, company); // Company Name
427     mxf_write_local_tag_utf16(pb, 0x3C02, product); // Product Name
428     mxf_write_local_tag_utf16(pb, 0x3C04, version); // Version String
429
430     // write product uid
431     mxf_write_local_tag(pb, 16, 0x3C05);
432     mxf_write_uuid(pb, Identification, 2);
433
434     // write modified date
435     mxf_write_local_tag(pb, 8, 0x3C06);
436     put_be64(pb, 0);
437 }
438
439 static void mxf_write_content_storage(AVFormatContext *s)
440 {
441     ByteIOContext *pb = s->pb;
442
443     mxf_write_metadata_key(pb, 0x011800);
444     PRINT_KEY(s, "content storage key", pb->buf_ptr - 16);
445     klv_encode_ber_length(pb, 92);
446
447     // write uid
448     mxf_write_local_tag(pb, 16, 0x3C0A);
449     mxf_write_uuid(pb, ContentStorage, 0);
450     PRINT_KEY(s, "content storage uid", pb->buf_ptr - 16);
451
452     // write package reference
453     mxf_write_local_tag(pb, 16 * 2 + 8, 0x1901);
454     mxf_write_refs_count(pb, 2);
455     mxf_write_uuid(pb, MaterialPackage, 0);
456     mxf_write_uuid(pb, SourcePackage, 0);
457
458     // write essence container data
459     mxf_write_local_tag(pb, 8 + 16, 0x1902);
460     mxf_write_refs_count(pb, 1);
461     mxf_write_uuid(pb, EssenceContainerData, 0);
462 }
463
464 static void mxf_write_track(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
465 {
466     ByteIOContext *pb = s->pb;
467     MXFStreamContext *sc = st->priv_data;
468
469     mxf_write_metadata_key(pb, 0x013b00);
470     PRINT_KEY(s, "track key", pb->buf_ptr - 16);
471     klv_encode_ber_length(pb, 80);
472
473     // write track uid
474     mxf_write_local_tag(pb, 16, 0x3C0A);
475     mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, st->index);
476     PRINT_KEY(s, "track uid", pb->buf_ptr - 16);
477
478     // write track id
479     mxf_write_local_tag(pb, 4, 0x4801);
480     put_be32(pb, st->index);
481
482     // write track number
483     mxf_write_local_tag(pb, 4, 0x4804);
484     if (type == MaterialPackage)
485         put_be32(pb, 0); // track number of material package is 0
486     else
487         put_buffer(pb, sc->track_essence_element_key + 12, 4);
488
489     mxf_write_local_tag(pb, 8, 0x4B01);
490     put_be32(pb, st->time_base.den);
491     put_be32(pb, st->time_base.num);
492
493     // write origin
494     mxf_write_local_tag(pb, 8, 0x4B02);
495     put_be64(pb, 0);
496
497     // write sequence refs
498     mxf_write_local_tag(pb, 16, 0x4803);
499     mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
500 }
501
502 static void mxf_write_common_fields(ByteIOContext *pb, AVStream *st)
503 {
504     const MXFDataDefinitionUL *data_def_ul = mxf_get_data_definition_ul(st->codec->codec_type);
505     MXFStreamContext *sc = st->priv_data;
506
507     // find data define uls
508     mxf_write_local_tag(pb, 16, 0x0201);
509     put_buffer(pb, data_def_ul->uid, 16);
510
511     // write duration
512     mxf_write_local_tag(pb, 8, 0x0202);
513     put_be64(pb, sc->duration);
514 }
515
516 static void mxf_write_sequence(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
517 {
518     ByteIOContext *pb = s->pb;
519
520     mxf_write_metadata_key(pb, 0x010f00);
521     PRINT_KEY(s, "sequence key", pb->buf_ptr - 16);
522     klv_encode_ber_length(pb, 80);
523
524     mxf_write_local_tag(pb, 16, 0x3C0A);
525     mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
526
527     PRINT_KEY(s, "sequence uid", pb->buf_ptr - 16);
528     mxf_write_common_fields(pb, st);
529
530     // write structural component
531     mxf_write_local_tag(pb, 16 + 8, 0x1001);
532     mxf_write_refs_count(pb, 1);
533     mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
534 }
535
536 static void mxf_write_structural_component(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
537 {
538     ByteIOContext *pb = s->pb;
539     int i;
540
541     mxf_write_metadata_key(pb, 0x011100);
542     PRINT_KEY(s, "sturctural component key", pb->buf_ptr - 16);
543     klv_encode_ber_length(pb, 108);
544
545     // write uid
546     mxf_write_local_tag(pb, 16, 0x3C0A);
547     mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
548
549     PRINT_KEY(s, "structural component uid", pb->buf_ptr - 16);
550     mxf_write_common_fields(pb, st);
551
552     // write start_position
553     mxf_write_local_tag(pb, 8, 0x1201);
554     put_be64(pb, 0);
555
556     // write source package uid, end of the reference
557     mxf_write_local_tag(pb, 32, 0x1101);
558     if (type == SourcePackage) {
559         for (i = 0; i < 4; i++)
560             put_be64(pb, 0);
561     } else
562         mxf_write_umid(pb, SourcePackage, 0);
563
564     // write source track id
565     mxf_write_local_tag(pb, 4, 0x1102);
566     if (type == SourcePackage)
567         put_be32(pb, 0);
568     else
569         put_be32(pb, st->index);
570 }
571
572 static void mxf_write_multi_descriptor(AVFormatContext *s)
573 {
574     ByteIOContext *pb = s->pb;
575     int i;
576
577     mxf_write_metadata_key(pb, 0x014400);
578     PRINT_KEY(s, "multiple descriptor key", pb->buf_ptr - 16);
579     klv_encode_ber_length(pb, 64 + 16 * s->nb_streams);
580
581     mxf_write_local_tag(pb, 16, 0x3C0A);
582     mxf_write_uuid(pb, MultipleDescriptor, 0);
583     PRINT_KEY(s, "multi_desc uid", pb->buf_ptr - 16);
584
585     // write sample rate
586     mxf_write_local_tag(pb, 8, 0x3001);
587     put_be32(pb, s->streams[0]->time_base.den);
588     put_be32(pb, s->streams[0]->time_base.num);
589
590     // write essence container ul
591     mxf_write_local_tag(pb, 16, 0x3004);
592     put_buffer(pb, multiple_desc_ul, 16);
593
594     // write sub descriptor refs
595     mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x3F01);
596     mxf_write_refs_count(pb, s->nb_streams);
597     for (i = 0; i < s->nb_streams; i++)
598         mxf_write_uuid(pb, SubDescriptor, i);
599 }
600
601 static void mxf_write_generic_desc(ByteIOContext *pb, AVStream *st, const UID key, unsigned size)
602 {
603     MXFStreamContext *sc = st->priv_data;
604
605     put_buffer(pb, key, 16);
606     klv_encode_ber_length(pb, size);
607
608     mxf_write_local_tag(pb, 16, 0x3C0A);
609     mxf_write_uuid(pb, SubDescriptor, st->index);
610
611     mxf_write_local_tag(pb, 4, 0x3006);
612     put_be32(pb, st->index);
613
614     mxf_write_local_tag(pb, 8, 0x3001);
615     put_be32(pb, st->time_base.den);
616     put_be32(pb, st->time_base.num);
617
618     mxf_write_local_tag(pb, 16, 0x3004);
619     put_buffer(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
620 }
621
622 static const UID mxf_mpegvideo_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 };
623 static const UID mxf_wav_descriptor_key       = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 };
624 static const UID mxf_aes3_descriptor_key      = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 };
625
626 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st)
627 {
628     MXFStreamContext *sc = st->priv_data;
629     ByteIOContext *pb = s->pb;
630     int stored_height = (st->codec->height+15)/16*16;
631     AVRational dar;
632     int f1, f2;
633
634     mxf_write_generic_desc(pb, st, mxf_mpegvideo_descriptor_key, 153+sc->interlaced*4);
635
636     mxf_write_local_tag(pb, 4, 0x3203);
637     put_be32(pb, st->codec->width);
638
639     mxf_write_local_tag(pb, 4, 0x3202);
640     put_be32(pb, stored_height>>sc->interlaced);
641
642     mxf_write_local_tag(pb, 4, 0x3209);
643     put_be32(pb, st->codec->width);
644
645     mxf_write_local_tag(pb, 4, 0x3208);
646     put_be32(pb, st->codec->height>>sc->interlaced);
647
648     // bit rate
649     mxf_write_local_tag(pb, 4, 0x8000);
650     put_be32(pb, st->codec->bit_rate);
651
652     // frame layout
653     mxf_write_local_tag(pb, 1, 0x320C);
654     put_byte(pb, sc->interlaced);
655
656     // video line map
657     switch (st->codec->height) {
658     case  576: f1 = 23; f2 = 336; break;
659     case  608: f1 =  7; f2 = 320; break;
660     case  480: f1 = 20; f2 = 283; break;
661     case  512: f1 =  7; f2 = 270; break;
662     case  720: f1 = 26; f2 =   0; break; // progressive
663     case 1080: f1 = 21; f2 = 584; break;
664     default:   f1 =  0; f2 =   0; break;
665     }
666
667     if (!sc->interlaced) {
668         f2  = 0;
669         f1 *= 2;
670     }
671
672     mxf_write_local_tag(pb, 12+sc->interlaced*4, 0x320D);
673     put_be32(pb, sc->interlaced ? 2 : 1);
674     put_be32(pb, 4);
675     put_be32(pb, f1);
676     if (sc->interlaced)
677         put_be32(pb, f2);
678
679     av_reduce(&dar.num, &dar.den,
680               st->codec->width*st->codec->sample_aspect_ratio.num,
681               st->codec->height*st->codec->sample_aspect_ratio.den,
682               1024*1024);
683
684     mxf_write_local_tag(pb, 8, 0x320E);
685     put_be32(pb, dar.num);
686     put_be32(pb, dar.den);
687
688     mxf_write_local_tag(pb, 16, 0x3201);
689     put_buffer(pb, *sc->codec_ul, 16);
690 }
691
692 static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
693 {
694     ByteIOContext *pb = s->pb;
695
696     mxf_write_generic_desc(pb, st, key, size);
697
698     // audio locked
699     mxf_write_local_tag(pb, 1, 0x3D02);
700     put_byte(pb, 1);
701
702     // write audio sampling rate
703     mxf_write_local_tag(pb, 8, 0x3D03);
704     put_be32(pb, st->codec->sample_rate);
705     put_be32(pb, 1);
706
707     mxf_write_local_tag(pb, 4, 0x3D07);
708     put_be32(pb, st->codec->channels);
709
710     mxf_write_local_tag(pb, 4, 0x3D01);
711     put_be32(pb, av_get_bits_per_sample(st->codec->codec_id));
712 }
713
714 static void mxf_write_wav_common_desc(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
715 {
716     ByteIOContext *pb = s->pb;
717
718     mxf_write_generic_sound_desc(s, st, key, size);
719
720     mxf_write_local_tag(pb, 2, 0x3D0A);
721     put_be16(pb, st->codec->block_align);
722
723     // avg bytes per sec
724     mxf_write_local_tag(pb, 4, 0x3D09);
725     put_be32(pb, st->codec->block_align*st->codec->sample_rate);
726 }
727
728 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st)
729 {
730     mxf_write_wav_common_desc(s, st, mxf_wav_descriptor_key, 107);
731 }
732
733 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st)
734 {
735     mxf_write_wav_common_desc(s, st, mxf_aes3_descriptor_key, 107);
736 }
737
738 static void mxf_write_package(AVFormatContext *s, enum MXFMetadataSetType type)
739 {
740     ByteIOContext *pb = s->pb;
741     int i;
742
743     if (type == MaterialPackage) {
744         mxf_write_metadata_key(pb, 0x013600);
745         PRINT_KEY(s, "Material Package key", pb->buf_ptr - 16);
746         klv_encode_ber_length(pb, 92 + 16 * s->nb_streams);
747     } else {
748         mxf_write_metadata_key(pb, 0x013700);
749         PRINT_KEY(s, "Source Package key", pb->buf_ptr - 16);
750         klv_encode_ber_length(pb, 112 + 16 * s->nb_streams); // 20 bytes length for descriptor reference
751     }
752
753     // write uid
754     mxf_write_local_tag(pb, 16, 0x3C0A);
755     mxf_write_uuid(pb, type, 0);
756     av_log(s,AV_LOG_DEBUG, "package type:%d\n", type);
757     PRINT_KEY(s, "package uid", pb->buf_ptr - 16);
758
759     // write package umid
760     mxf_write_local_tag(pb, 32, 0x4401);
761     mxf_write_umid(pb, type, 0);
762     PRINT_KEY(s, "package umid second part", pb->buf_ptr - 16);
763
764     // write create date
765     mxf_write_local_tag(pb, 8, 0x4405);
766     put_be64(pb, 0);
767
768     // write modified date
769     mxf_write_local_tag(pb, 8, 0x4404);
770     put_be64(pb, 0);
771
772     // write track refs
773     mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x4403);
774     mxf_write_refs_count(pb, s->nb_streams);
775     for (i = 0; i < s->nb_streams; i++)
776         mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, i);
777
778     // write multiple descriptor reference
779     if (type == SourcePackage) {
780         mxf_write_local_tag(pb, 16, 0x4701);
781         if (s->nb_streams > 1) {
782             mxf_write_uuid(pb, MultipleDescriptor, 0);
783             mxf_write_multi_descriptor(s);
784         } else
785             mxf_write_uuid(pb, SubDescriptor, 0);
786     }
787
788     for (i = 0; i < s->nb_streams; i++) {
789         AVStream *st = s->streams[i];
790         mxf_write_track(s, st, type);
791         mxf_write_sequence(s, st, type);
792         mxf_write_structural_component(s, st, type);
793
794         if (type == SourcePackage) {
795             MXFStreamContext *sc = st->priv_data;
796             mxf_essence_container_uls[sc->index].write_desc(s, st);
797         }
798     }
799 }
800
801 static int mxf_write_essence_container_data(AVFormatContext *s)
802 {
803     ByteIOContext *pb = s->pb;
804
805     mxf_write_metadata_key(pb, 0x012300);
806     klv_encode_ber_length(pb, 72);
807
808     mxf_write_local_tag(pb, 16, 0x3C0A); // Instance UID
809     mxf_write_uuid(pb, EssenceContainerData, 0);
810
811     mxf_write_local_tag(pb, 32, 0x2701); // Linked Package UID
812     mxf_write_umid(pb, SourcePackage, 0);
813
814     mxf_write_local_tag(pb, 4, 0x3F07); // BodySID
815     put_be32(pb, 1);
816
817     mxf_write_local_tag(pb, 4, 0x3F06); // IndexSID
818     put_be32(pb, 2);
819
820     return 0;
821 }
822
823 static int mxf_write_header_metadata_sets(AVFormatContext *s)
824 {
825     mxf_write_preface(s);
826     mxf_write_identification(s);
827     mxf_write_content_storage(s);
828     mxf_write_package(s, MaterialPackage);
829     mxf_write_package(s, SourcePackage);
830     mxf_write_essence_container_data(s);
831     return 0;
832 }
833
834 static int mxf_write_index_table_segment(AVFormatContext *s)
835 {
836     MXFContext *mxf = s->priv_data;
837     ByteIOContext *pb = s->pb;
838     int i, j, k, ret, key_offset = 0;
839     int temporal_reordering = 0;
840
841     av_log(s, AV_LOG_DEBUG, "edit units count %d\n", mxf->edit_units_count);
842
843     put_buffer(pb, index_table_segment_key, 16);
844     ret = klv_encode_ber_length(pb, 109 + s->nb_streams*6 +
845                                 mxf->edit_units_count*(11+(s->nb_streams-1)*4));
846
847     // instance id
848     mxf_write_local_tag(pb, 16, 0x3C0A);
849     mxf_write_uuid(pb, IndexTableSegment, 0);
850
851     // index edit rate
852     mxf_write_local_tag(pb, 8, 0x3F0B);
853     put_be32(pb, mxf->time_base.num);
854     put_be32(pb, mxf->time_base.den);
855
856     // index start position
857     mxf_write_local_tag(pb, 8, 0x3F0C);
858     put_be64(pb, 0);
859
860     // index duration
861     mxf_write_local_tag(pb, 8, 0x3F0D);
862     put_be64(pb, mxf->edit_units_count);
863
864     // edit unit byte count
865     mxf_write_local_tag(pb, 4, 0x3F05);
866     put_be32(pb, 0);
867
868     // index sid
869     mxf_write_local_tag(pb, 4, 0x3F06);
870     put_be32(pb, 2);
871
872     // body sid
873     mxf_write_local_tag(pb, 4, 0x3F07);
874     put_be32(pb, 1);
875
876     // slice count - 1
877     mxf_write_local_tag(pb, 1, 0x3F08);
878     put_byte(pb, s->nb_streams-1);
879
880     // delta entry array
881     mxf_write_local_tag(pb, 8 + s->nb_streams*6, 0x3F09);
882     put_be32(pb, s->nb_streams); // num of entries
883     put_be32(pb, 6);             // size of one entry
884     for (i = 0; i < s->nb_streams; i++) {
885         AVStream *st = s->streams[i];
886         MXFStreamContext *sc = st->priv_data;
887         put_byte(pb, sc->temporal_reordering);
888         if (sc->temporal_reordering)
889             temporal_reordering = 1;
890         put_byte(pb, i);
891         put_be32(pb, 0); // element delta
892     }
893
894     mxf_write_local_tag(pb, 8 + mxf->edit_units_count*(11+(s->nb_streams-1)*4), 0x3F0A);
895     put_be32(pb, mxf->edit_units_count);  // num of entries
896     put_be32(pb, 11+(s->nb_streams-1)*4); // size of one entry
897     for (i = 0; i < mxf->edit_units_count; i++) {
898         if (mxf->index_entries[i].flags & 0x40)
899             key_offset = 0;
900         if (temporal_reordering) {
901             int temporal_offset = 0;
902             for (j = i+1; j < mxf->edit_units_count; j++) {
903                 temporal_offset++;
904                 if (mxf->index_entries[j].flags & 0x10) { // backward prediction
905                     // next is not b, so is reordered
906                     if (!(mxf->index_entries[i+1].flags & 0x10)) {
907                         if ((mxf->index_entries[i].flags & 0x11) == 0) // i frame
908                             temporal_offset = 0;
909                         else
910                             temporal_offset = -temporal_offset;
911                     }
912                     break;
913                 }
914             }
915             put_byte(pb, temporal_offset);
916         } else
917             put_byte(pb, 0);
918         put_byte(pb, key_offset);
919         put_byte(pb, mxf->index_entries[i].flags);
920         // stream offset
921         put_be64(pb, mxf->index_entries[i].offset - mxf->index_entries[0].offset);
922         for (k = 0; k < s->nb_streams; k++) {
923             if (mxf->index_entries[i].slice_offset[k])
924                 put_be32(pb, mxf->index_entries[i].slice_offset[k]);
925         }
926         key_offset--;
927     }
928
929     return ret;
930 }
931
932 static void mxf_write_partition(AVFormatContext *s, int bodysid,
933                                 int indexsid, unsigned index_byte_count,
934                                 const uint8_t *key, int write_metadata)
935 {
936     MXFContext *mxf = s->priv_data;
937     ByteIOContext *pb = s->pb;
938     int64_t header_byte_count_offset;
939
940     // write klv
941     put_buffer(pb, key, 16);
942
943     klv_encode_ber_length(pb, 88 + 16 * mxf->essence_container_count);
944
945     // write partition value
946     put_be16(pb, 1); // majorVersion
947     put_be16(pb, 2); // minorVersion
948     put_be32(pb, 1); // kagSize
949
950     put_be64(pb, url_ftell(pb) - 25); // thisPartition
951     put_be64(pb, 0); // previousPartition
952
953     put_be64(pb, mxf->footer_partition_offset); // footerPartition
954
955     // set offset
956     header_byte_count_offset = url_ftell(pb);
957     put_be64(pb, 0); // headerByteCount, update later
958
959     // indexTable
960     put_be64(pb, index_byte_count); // indexByteCount
961     put_be32(pb, indexsid); // indexSID
962     put_be64(pb, 0); // bodyOffset
963
964     put_be32(pb, bodysid); // bodySID
965     put_buffer(pb, op1a_ul, 16); // operational pattern
966
967     // essence container
968     mxf_write_essence_container_refs(s);
969
970     if (write_metadata) {
971         // mark the start of the headermetadata and calculate metadata size
972         int64_t pos, start = url_ftell(s->pb);
973         mxf_write_primer_pack(s);
974         mxf_write_header_metadata_sets(s);
975         pos = url_ftell(s->pb);
976         // update header_byte_count
977         url_fseek(pb, header_byte_count_offset, SEEK_SET);
978         put_be64(pb, pos - start);
979         url_fseek(pb, pos, SEEK_SET);
980     }
981
982     put_flush_packet(pb);
983 }
984
985 static const UID mxf_mpeg2_codec_uls[] = {
986     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x10,0x00 }, // MP-ML I-Frame
987     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, // MP-ML Long GOP
988     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, // 422P-ML I-Frame
989     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, // 422P-ML Long GOP
990     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x02,0x00 }, // MP-HL I-Frame
991     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, // MP-HL Long GOP
992     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, // 422P-HL I-Frame
993     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, // 422P-HL Long GOP
994 };
995
996 static const UID *mxf_get_mpeg2_codec_ul(AVCodecContext *avctx)
997 {
998     if (avctx->profile == 4) { // Main
999         if (avctx->level == 8) // Main
1000             return avctx->gop_size ?
1001                 &mxf_mpeg2_codec_uls[1] :
1002                 &mxf_mpeg2_codec_uls[0];
1003         else if (avctx->level == 4) // High
1004             return avctx->gop_size ?
1005                 &mxf_mpeg2_codec_uls[5] :
1006                 &mxf_mpeg2_codec_uls[4];
1007     } else if (avctx->profile == 0) { // 422
1008         if (avctx->level == 5) // Main
1009             return avctx->gop_size ?
1010                 &mxf_mpeg2_codec_uls[3] :
1011                 &mxf_mpeg2_codec_uls[2];
1012         else if (avctx->level == 2) // High
1013             return avctx->gop_size ?
1014                 &mxf_mpeg2_codec_uls[7] :
1015                 &mxf_mpeg2_codec_uls[6];
1016     }
1017     return NULL;
1018 }
1019
1020 static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
1021 {
1022     MXFContext *mxf = s->priv_data;
1023     MXFStreamContext *sc = st->priv_data;
1024     uint32_t c = -1;
1025     int i;
1026
1027     mxf->index_entries[mxf->edit_units_count].flags = 0;
1028
1029     for(i = 0; i < pkt->size - 4; i++) {
1030         c = (c<<8) + pkt->data[i];
1031         if (c == 0x1B5) {
1032             if (i + 2 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x10) { // seq ext
1033                 st->codec->profile = pkt->data[i+1] & 0x07;
1034                 st->codec->level   = pkt->data[i+2] >> 4;
1035             } else if (i + 5 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x80) { // pict coding ext
1036                 sc->interlaced = !(pkt->data[i+5] & 0x80); // progressive frame
1037                 break;
1038             }
1039         } else if (c == 0x1b8) { // gop
1040             if (i + 4 < pkt->size && pkt->data[i+4]>>6 & 0x01) // closed
1041                 mxf->index_entries[mxf->edit_units_count].flags |= 0x80; // random access
1042         } else if (c == 0x1b3) { // seq
1043             mxf->index_entries[mxf->edit_units_count].flags |= 0x40;
1044         } else if (c == 0x100) { // pic
1045             int pict_type = (pkt->data[i+2]>>3) & 0x07;
1046             if (pict_type == 2) { // P frame
1047                 mxf->index_entries[mxf->edit_units_count].flags |= 0x22;
1048                 st->codec->gop_size = 1;
1049             } else if (pict_type == 3) { // B frame
1050                 mxf->index_entries[mxf->edit_units_count].flags |= 0x33;
1051                 sc->temporal_reordering = -1;
1052             } else if (!pict_type) {
1053                 av_log(s, AV_LOG_ERROR, "error parsing mpeg2 frame\n");
1054                 return 0;
1055             }
1056         }
1057     }
1058     sc->codec_ul = mxf_get_mpeg2_codec_ul(st->codec);
1059     return !!sc->codec_ul;
1060 }
1061
1062 static int ff_audio_interleave_init(AVFormatContext *s, const int *samples_per_frame)
1063 {
1064     int i;
1065
1066     if (!samples_per_frame)
1067         return -1;
1068
1069     for (i = 0; i < s->nb_streams; i++) {
1070         AVStream *st = s->streams[i];
1071         AudioInterleaveContext *aic = st->priv_data;
1072
1073         if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1074             aic->sample_size = (st->codec->channels *
1075                                 av_get_bits_per_sample(st->codec->codec_id)) / 8;
1076             if (!aic->sample_size) {
1077                 av_log(s, AV_LOG_ERROR, "could not compute sample size\n");
1078                 return -1;
1079             }
1080             aic->samples_per_frame = samples_per_frame;
1081             aic->samples = aic->samples_per_frame;
1082
1083             av_fifo_init(&aic->fifo, 100 * *aic->samples);
1084         }
1085     }
1086
1087     return 0;
1088 }
1089
1090 static void ff_audio_interleave_close(AVFormatContext *s)
1091 {
1092     int i;
1093     for (i = 0; i < s->nb_streams; i++) {
1094         AVStream *st = s->streams[i];
1095         AudioInterleaveContext *aic = st->priv_data;
1096
1097         if (st->codec->codec_type == CODEC_TYPE_AUDIO)
1098             av_fifo_free(&aic->fifo);
1099     }
1100 }
1101
1102 static int mxf_write_header(AVFormatContext *s)
1103 {
1104     MXFContext *mxf = s->priv_data;
1105     int i;
1106     uint8_t present[FF_ARRAY_ELEMS(mxf_essence_container_uls)] = {0};
1107     const int *samples_per_frame = NULL;
1108
1109     if (s->nb_streams > 17) {
1110         av_log(s, AV_LOG_ERROR, "error, mxf muxer supports 17 tracks maximum\n");
1111         return -1;
1112     }
1113
1114     for (i = 0; i < s->nb_streams; i++) {
1115         AVStream *st = s->streams[i];
1116         MXFStreamContext *sc = av_mallocz(sizeof(*sc));
1117         if (!sc)
1118             return AVERROR(ENOMEM);
1119         st->priv_data = sc;
1120
1121         if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1122             if (fabs(av_q2d(st->codec->time_base) - 1/25.0) < 0.0001) {
1123                 samples_per_frame = PAL_samples_per_frame;
1124                 mxf->time_base = (AVRational){ 1, 25 };
1125             } else if (fabs(av_q2d(st->codec->time_base) - 1001/30000.0) < 0.0001) {
1126                 samples_per_frame = NTSC_samples_per_frame;
1127                 mxf->time_base = (AVRational){ 1001, 30000 };
1128             } else {
1129                 av_log(s, AV_LOG_ERROR, "unsupported video frame rate\n");
1130                 return -1;
1131             }
1132             mxf->edit_unit_start = st->index;
1133         } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1134             if (st->codec->sample_rate != 48000) {
1135                 av_log(s, AV_LOG_ERROR, "only 48khz is implemented\n");
1136                 return -1;
1137             }
1138         }
1139         sc->duration = -1;
1140
1141         sc->index = mxf_get_essence_container_ul_index(st->codec->codec_id);
1142         if (sc->index == -1) {
1143             av_log(s, AV_LOG_ERROR, "track %d: could not find essence container ul, "
1144                    "codec not currently supported in container\n", i);
1145             return -1;
1146         }
1147
1148         sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
1149
1150         if (!present[sc->index]) {
1151             mxf->essence_containers_indices[mxf->essence_container_count++] = sc->index;
1152             present[sc->index] = 1;
1153         } else
1154             present[sc->index]++;
1155         memcpy(sc->track_essence_element_key, mxf_essence_container_uls[sc->index].element_ul, 15);
1156         sc->track_essence_element_key[15] = present[sc->index];
1157         PRINT_KEY(s, "track essence element key", sc->track_essence_element_key);
1158     }
1159
1160     for (i = 0; i < s->nb_streams; i++) {
1161         MXFStreamContext *sc = s->streams[i]->priv_data;
1162         av_set_pts_info(s->streams[i], 64, mxf->time_base.num, mxf->time_base.den);
1163         // update element count
1164         sc->track_essence_element_key[13] = present[sc->index];
1165         sc->order = AV_RB32(sc->track_essence_element_key+12);
1166     }
1167
1168     if (!samples_per_frame)
1169         samples_per_frame = PAL_samples_per_frame;
1170
1171     if (ff_audio_interleave_init(s, samples_per_frame) < 0)
1172         return -1;
1173
1174     return 0;
1175 }
1176
1177 static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
1178 {
1179     MXFContext *mxf = s->priv_data;
1180     ByteIOContext *pb = s->pb;
1181     AVStream *st = s->streams[pkt->stream_index];
1182     MXFStreamContext *sc = st->priv_data;
1183
1184     if (!(mxf->edit_units_count % MXF_INDEX_CLUSTER_SIZE)) {
1185         mxf->index_entries = av_realloc(mxf->index_entries,
1186             (mxf->edit_units_count + MXF_INDEX_CLUSTER_SIZE)*
1187              sizeof(*mxf->index_entries));
1188         if (!mxf->index_entries) {
1189             av_log(s, AV_LOG_ERROR, "could not allocate index entries\n");
1190             return -1;
1191         }
1192     }
1193
1194     if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO) {
1195         if (!mxf_parse_mpeg2_frame(s, st, pkt)) {
1196             av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
1197             return -1;
1198         }
1199     }
1200
1201     if (!mxf->header_written) {
1202         mxf_write_partition(s, 1, 0, 0, header_open_partition_key, 1);
1203         mxf->header_written = 1;
1204     }
1205
1206     if (st->index == mxf->edit_unit_start) {
1207         mxf->index_entries[mxf->edit_units_count].offset = url_ftell(pb);
1208         mxf->index_entries[mxf->edit_units_count].slice_offset[st->index] = 0;
1209         mxf->edit_units_count++;
1210     } else {
1211         mxf->index_entries[mxf->edit_units_count-1].slice_offset[st->index] =
1212             url_ftell(pb) - mxf->index_entries[mxf->edit_units_count-1].offset;
1213     }
1214
1215     put_buffer(pb, sc->track_essence_element_key, 16); // write key
1216     klv_encode_ber_length(pb, pkt->size); // write length
1217     put_buffer(pb, pkt->data, pkt->size); // write value
1218
1219     sc->duration = FFMAX(pkt->pts + pkt->duration, sc->duration);
1220
1221     put_flush_packet(pb);
1222     return 0;
1223 }
1224
1225 static void mxf_write_random_index_pack(AVFormatContext *s)
1226 {
1227     MXFContext *mxf = s->priv_data;
1228     ByteIOContext *pb = s->pb;
1229     uint64_t pos = url_ftell(pb);
1230
1231     put_buffer(pb, random_index_pack_key, 16);
1232     klv_encode_ber_length(pb, 28);
1233
1234     put_be32(pb, 1); // BodySID of header partition
1235     put_be64(pb, 0); // offset of header partition
1236
1237     put_be32(pb, 0); // BodySID of footer partition
1238     put_be64(pb, mxf->footer_partition_offset);
1239
1240     put_be32(pb, url_ftell(pb) - pos + 4);
1241 }
1242
1243 static int mxf_write_footer(AVFormatContext *s)
1244 {
1245     MXFContext *mxf = s->priv_data;
1246     ByteIOContext *pb = s->pb;
1247     unsigned index_byte_count =
1248         109 + s->nb_streams*6 +
1249         mxf->edit_units_count*(11+(s->nb_streams-1)*4);
1250
1251     // add encoded ber length
1252     index_byte_count += 16 +
1253         (index_byte_count < 128 ? 1 : (av_log2(index_byte_count) >> 3) + 2);
1254
1255     mxf->footer_partition_offset = url_ftell(pb);
1256     mxf_write_partition(s, 0, 2, index_byte_count, footer_partition_key, 0);
1257
1258     mxf_write_index_table_segment(s);
1259
1260     mxf_write_random_index_pack(s);
1261
1262     if (!url_is_streamed(s->pb)) {
1263         url_fseek(pb, 0, SEEK_SET);
1264         mxf_write_partition(s, 1, 0, 0, header_closed_partition_key, 1);
1265     }
1266
1267     ff_audio_interleave_close(s);
1268
1269     mxf_free(s);
1270     return 0;
1271 }
1272
1273 static int mxf_interleave_new_audio_packet(AVFormatContext *s, AVPacket *pkt,
1274                                            int stream_index, int flush)
1275 {
1276     AVStream *st = s->streams[stream_index];
1277     AudioInterleaveContext *aic = st->priv_data;
1278
1279     int size = FFMIN(av_fifo_size(&aic->fifo), *aic->samples * aic->sample_size);
1280     if (!size || (!flush && size == av_fifo_size(&aic->fifo)))
1281         return 0;
1282
1283     av_new_packet(pkt, size);
1284     av_fifo_read(&aic->fifo, pkt->data, size);
1285
1286     pkt->dts = pkt->pts = aic->dts;
1287     pkt->duration = av_rescale_q(*aic->samples,
1288                                  (AVRational){ 1, st->codec->sample_rate },
1289                                  st->time_base);
1290     pkt->stream_index = stream_index;
1291     aic->dts += pkt->duration;
1292
1293     aic->samples++;
1294     if (!*aic->samples)
1295         aic->samples = aic->samples_per_frame;
1296
1297     return size;
1298 }
1299
1300 static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1301 {
1302     AVPacketList *pktl;
1303     int stream_count = 0;
1304     int streams[MAX_STREAMS];
1305
1306     memset(streams, 0, sizeof(streams));
1307     pktl = s->packet_buffer;
1308     while (pktl) {
1309         //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
1310         if (!streams[pktl->pkt.stream_index])
1311             stream_count++;
1312         streams[pktl->pkt.stream_index]++;
1313         pktl = pktl->next;
1314     }
1315
1316     if (stream_count && (s->nb_streams == stream_count || flush)) {
1317         pktl = s->packet_buffer;
1318         if (s->nb_streams != stream_count) {
1319             MXFContext *mxf = s->priv_data;
1320             AVPacketList *first = NULL;
1321             // find first packet in edit unit
1322             while (pktl) {
1323                 AVStream *st = s->streams[pktl->pkt.stream_index];
1324                 if (st->index == mxf->edit_unit_start)
1325                     break;
1326                 else if (!first)
1327                     first = pktl;
1328                 pktl = pktl->next;
1329             }
1330             // purge packet queue
1331             while (pktl) {
1332                 AVPacketList *next = pktl->next;
1333                 av_free_packet(&pktl->pkt);
1334                 av_freep(&pktl);
1335                 pktl = next;
1336             }
1337             if (!first)
1338                 goto out;
1339             pktl = first;
1340         }
1341
1342         *out = pktl->pkt;
1343         //av_log(s, AV_LOG_DEBUG, "out st:%d dts:%lld\n", (*out).stream_index, (*out).dts);
1344         s->packet_buffer = pktl->next;
1345         av_freep(&pktl);
1346         return 1;
1347     } else {
1348     out:
1349         av_init_packet(out);
1350         return 0;
1351     }
1352 }
1353
1354 static int mxf_compare_timestamps(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
1355 {
1356     AVStream *st  = s->streams[pkt ->stream_index];
1357     AVStream *st2 = s->streams[next->stream_index];
1358     MXFStreamContext *sc  = st ->priv_data;
1359     MXFStreamContext *sc2 = st2->priv_data;
1360
1361     int64_t left  = st2->time_base.num * (int64_t)st ->time_base.den;
1362     int64_t right = st ->time_base.num * (int64_t)st2->time_base.den;
1363
1364     return next->dts * left > pkt->dts * right || // FIXME this can overflow
1365         (next->dts * left == pkt->dts * right && sc->order < sc2->order);
1366 }
1367
1368 static int mxf_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1369 {
1370     int i;
1371
1372     if (pkt) {
1373         AVStream *st = s->streams[pkt->stream_index];
1374         AudioInterleaveContext *aic = st->priv_data;
1375         if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1376             av_fifo_generic_write(&aic->fifo, pkt->data, pkt->size, NULL);
1377         } else {
1378             // rewrite pts and dts to be decoded time line position
1379             pkt->pts = pkt->dts = aic->dts;
1380             aic->dts += pkt->duration;
1381             ff_interleave_add_packet(s, pkt, mxf_compare_timestamps);
1382         }
1383         pkt = NULL;
1384     }
1385
1386     for (i = 0; i < s->nb_streams; i++) {
1387         AVStream *st = s->streams[i];
1388         if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1389             AVPacket new_pkt;
1390             while (mxf_interleave_new_audio_packet(s, &new_pkt, i, flush))
1391                 ff_interleave_add_packet(s, &new_pkt, mxf_compare_timestamps);
1392         }
1393     }
1394
1395     return mxf_interleave_get_packet(s, out, pkt, flush);
1396 }
1397
1398 AVOutputFormat mxf_muxer = {
1399     "mxf",
1400     NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1401     NULL,
1402     "mxf",
1403     sizeof(MXFContext),
1404     CODEC_ID_PCM_S16LE,
1405     CODEC_ID_MPEG2VIDEO,
1406     mxf_write_header,
1407     mxf_write_packet,
1408     mxf_write_footer,
1409     AVFMT_NOTIMESTAMPS,
1410     NULL,
1411     mxf_interleave,
1412 };