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