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