use sample rate as audio input time base
[ffmpeg.git] / libavformat / mxfenc.c
1 /*
2  * MXF muxer
3  * Copyright (c) 2008 GUCAS, Zhentan Feng <spyfeng at gmail dot com>
4  * Copyright (c) 2008 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /*
24  * References
25  * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value
26  * SMPTE 377M MXF File Format Specifications
27  * SMPTE 379M MXF Generic Container
28  * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container
29  * SMPTE RP210: SMPTE Metadata Dictionary
30  * SMPTE RP224: Registry of SMPTE Universal Labels
31  */
32
33 //#define DEBUG
34
35 #include <math.h>
36
37 #include "libavutil/fifo.h"
38 #include "mxf.h"
39
40 static const int NTSC_samples_per_frame[] = { 1602, 1601, 1602, 1601, 1602, 0 };
41 static const int PAL_samples_per_frame[]  = { 1920, 0 };
42
43 #define MXF_INDEX_CLUSTER_SIZE 4096
44
45 typedef struct {
46     AVFifoBuffer fifo;
47     unsigned fifo_size;           ///< current fifo size allocated
48     uint64_t dts;                 ///< current dts
49     int sample_size;              ///< size of one sample all channels included
50     const int *samples_per_frame; ///< must be 0 terminated
51     const int *samples;           ///< current samples per frame, pointer to samples_per_frame
52     AVRational time_base;         ///< time base of output audio packets
53 } AudioInterleaveContext;
54
55 typedef struct {
56     int local_tag;
57     UID uid;
58 } MXFLocalTagPair;
59
60 typedef struct {
61     uint8_t flags;
62     uint64_t offset;
63     unsigned slice_offset[17]; // one video, 16 audio
64 } MXFIndexEntry;
65
66 typedef struct {
67     AudioInterleaveContext aic;
68     UID track_essence_element_key;
69     int index;            ///< index in mxf_essence_container_uls table
70     const UID *codec_ul;
71     int64_t duration;
72     int order;            ///< interleaving order if dts are equal
73     int interlaced;       ///< wether picture is interlaced
74     int temporal_reordering;
75 } MXFStreamContext;
76
77 typedef struct {
78     UID container_ul;
79     UID element_ul;
80     UID codec_ul;
81     void (*write_desc)();
82 } MXFContainerEssenceEntry;
83
84 static const struct {
85     enum CodecID id;
86     int index;
87 } mxf_essence_mappings[] = {
88     { CODEC_ID_MPEG2VIDEO, 0 },
89     { CODEC_ID_PCM_S24LE,  1 },
90     { CODEC_ID_PCM_S16LE,  1 },
91     { 0 }
92 };
93
94 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st);
95 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st);
96 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st);
97
98 static const MXFContainerEssenceEntry mxf_essence_container_uls[] = {
99     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 },
100       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
101       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
102       mxf_write_mpegvideo_desc },
103     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x03,0x00 },
104       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x03,0x00 },
105       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
106       mxf_write_aes3_desc },
107     { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 },
108       { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x01,0x00 },
109       { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
110       mxf_write_wav_desc },
111     { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
112       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
113       { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
114       NULL },
115 };
116
117 typedef struct MXFContext {
118     int64_t footer_partition_offset;
119     int essence_container_count;
120     uint8_t essence_containers_indices[FF_ARRAY_ELEMS(mxf_essence_container_uls)];
121     AVRational time_base;
122     int header_written;
123     MXFIndexEntry *index_entries;
124     unsigned edit_units_count;
125     int edit_unit_start;  ///< index of the stream starting edit unit
126 } MXFContext;
127
128 static const uint8_t uuid_base[]            = { 0xAD,0xAB,0x44,0x24,0x2f,0x25,0x4d,0xc7,0x92,0xff,0x29,0xbd };
129 static const uint8_t umid_base[]            = { 0x06,0x0A,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x01,0x0D,0x00,0x13,0x00,0x00,0x00 };
130
131 /**
132  * complete key for operation pattern, partitions, and primer pack
133  */
134 static const uint8_t op1a_ul[]                     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x01,0x01,0x00 };
135 static const uint8_t footer_partition_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }; // ClosedComplete
136 static const uint8_t primer_pack_key[]             = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x05,0x01,0x00 };
137 static const uint8_t index_table_segment_key[]     = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 };
138 static const uint8_t random_index_pack_key[]       = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x11,0x01,0x00 };
139 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
140 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
141
142 /**
143  * partial key for header metadata
144  */
145 static const uint8_t header_metadata_key[]  = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01 };
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     MXFContext *mxf = s->priv_data;
468     ByteIOContext *pb = s->pb;
469     MXFStreamContext *sc = st->priv_data;
470
471     mxf_write_metadata_key(pb, 0x013b00);
472     PRINT_KEY(s, "track key", pb->buf_ptr - 16);
473     klv_encode_ber_length(pb, 80);
474
475     // write track uid
476     mxf_write_local_tag(pb, 16, 0x3C0A);
477     mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, st->index);
478     PRINT_KEY(s, "track uid", pb->buf_ptr - 16);
479
480     // write track id
481     mxf_write_local_tag(pb, 4, 0x4801);
482     put_be32(pb, st->index);
483
484     // write track number
485     mxf_write_local_tag(pb, 4, 0x4804);
486     if (type == MaterialPackage)
487         put_be32(pb, 0); // track number of material package is 0
488     else
489         put_buffer(pb, sc->track_essence_element_key + 12, 4);
490
491     mxf_write_local_tag(pb, 8, 0x4B01);
492     put_be32(pb, mxf->time_base.den);
493     put_be32(pb, mxf->time_base.num);
494
495     // write origin
496     mxf_write_local_tag(pb, 8, 0x4B02);
497     put_be64(pb, 0);
498
499     // write sequence refs
500     mxf_write_local_tag(pb, 16, 0x4803);
501     mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
502 }
503
504 static void mxf_write_common_fields(ByteIOContext *pb, AVStream *st)
505 {
506     const MXFDataDefinitionUL *data_def_ul = mxf_get_data_definition_ul(st->codec->codec_type);
507     MXFStreamContext *sc = st->priv_data;
508
509     // find data define uls
510     mxf_write_local_tag(pb, 16, 0x0201);
511     put_buffer(pb, data_def_ul->uid, 16);
512
513     // write duration
514     mxf_write_local_tag(pb, 8, 0x0202);
515     put_be64(pb, sc->duration);
516 }
517
518 static void mxf_write_sequence(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
519 {
520     ByteIOContext *pb = s->pb;
521
522     mxf_write_metadata_key(pb, 0x010f00);
523     PRINT_KEY(s, "sequence key", pb->buf_ptr - 16);
524     klv_encode_ber_length(pb, 80);
525
526     mxf_write_local_tag(pb, 16, 0x3C0A);
527     mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
528
529     PRINT_KEY(s, "sequence uid", pb->buf_ptr - 16);
530     mxf_write_common_fields(pb, st);
531
532     // write structural component
533     mxf_write_local_tag(pb, 16 + 8, 0x1001);
534     mxf_write_refs_count(pb, 1);
535     mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
536 }
537
538 static void mxf_write_structural_component(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
539 {
540     ByteIOContext *pb = s->pb;
541     int i;
542
543     mxf_write_metadata_key(pb, 0x011100);
544     PRINT_KEY(s, "sturctural component key", pb->buf_ptr - 16);
545     klv_encode_ber_length(pb, 108);
546
547     // write uid
548     mxf_write_local_tag(pb, 16, 0x3C0A);
549     mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
550
551     PRINT_KEY(s, "structural component uid", pb->buf_ptr - 16);
552     mxf_write_common_fields(pb, st);
553
554     // write start_position
555     mxf_write_local_tag(pb, 8, 0x1201);
556     put_be64(pb, 0);
557
558     // write source package uid, end of the reference
559     mxf_write_local_tag(pb, 32, 0x1101);
560     if (type == SourcePackage) {
561         for (i = 0; i < 4; i++)
562             put_be64(pb, 0);
563     } else
564         mxf_write_umid(pb, SourcePackage, 0);
565
566     // write source track id
567     mxf_write_local_tag(pb, 4, 0x1102);
568     if (type == SourcePackage)
569         put_be32(pb, 0);
570     else
571         put_be32(pb, st->index);
572 }
573
574 static void mxf_write_multi_descriptor(AVFormatContext *s)
575 {
576     ByteIOContext *pb = s->pb;
577     int i;
578
579     mxf_write_metadata_key(pb, 0x014400);
580     PRINT_KEY(s, "multiple descriptor key", pb->buf_ptr - 16);
581     klv_encode_ber_length(pb, 64 + 16 * s->nb_streams);
582
583     mxf_write_local_tag(pb, 16, 0x3C0A);
584     mxf_write_uuid(pb, MultipleDescriptor, 0);
585     PRINT_KEY(s, "multi_desc uid", pb->buf_ptr - 16);
586
587     // write sample rate
588     mxf_write_local_tag(pb, 8, 0x3001);
589     put_be32(pb, s->streams[0]->time_base.den);
590     put_be32(pb, s->streams[0]->time_base.num);
591
592     // write essence container ul
593     mxf_write_local_tag(pb, 16, 0x3004);
594     put_buffer(pb, multiple_desc_ul, 16);
595
596     // write sub descriptor refs
597     mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x3F01);
598     mxf_write_refs_count(pb, s->nb_streams);
599     for (i = 0; i < s->nb_streams; i++)
600         mxf_write_uuid(pb, SubDescriptor, i);
601 }
602
603 static void mxf_write_generic_desc(ByteIOContext *pb, AVStream *st, const UID key, unsigned size)
604 {
605     MXFStreamContext *sc = st->priv_data;
606
607     put_buffer(pb, key, 16);
608     klv_encode_ber_length(pb, size);
609
610     mxf_write_local_tag(pb, 16, 0x3C0A);
611     mxf_write_uuid(pb, SubDescriptor, st->index);
612
613     mxf_write_local_tag(pb, 4, 0x3006);
614     put_be32(pb, st->index);
615
616     mxf_write_local_tag(pb, 8, 0x3001);
617     put_be32(pb, st->time_base.den);
618     put_be32(pb, st->time_base.num);
619
620     mxf_write_local_tag(pb, 16, 0x3004);
621     put_buffer(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
622 }
623
624 static const UID mxf_mpegvideo_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 };
625 static const UID mxf_wav_descriptor_key       = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 };
626 static const UID mxf_aes3_descriptor_key      = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 };
627
628 static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st)
629 {
630     MXFStreamContext *sc = st->priv_data;
631     ByteIOContext *pb = s->pb;
632     int stored_height = (st->codec->height+15)/16*16;
633     AVRational dar;
634     int f1, f2;
635
636     mxf_write_generic_desc(pb, st, mxf_mpegvideo_descriptor_key, 153+sc->interlaced*4);
637
638     mxf_write_local_tag(pb, 4, 0x3203);
639     put_be32(pb, st->codec->width);
640
641     mxf_write_local_tag(pb, 4, 0x3202);
642     put_be32(pb, stored_height>>sc->interlaced);
643
644     mxf_write_local_tag(pb, 4, 0x3209);
645     put_be32(pb, st->codec->width);
646
647     mxf_write_local_tag(pb, 4, 0x3208);
648     put_be32(pb, st->codec->height>>sc->interlaced);
649
650     // bit rate
651     mxf_write_local_tag(pb, 4, 0x8000);
652     put_be32(pb, st->codec->bit_rate);
653
654     // frame layout
655     mxf_write_local_tag(pb, 1, 0x320C);
656     put_byte(pb, sc->interlaced);
657
658     // video line map
659     switch (st->codec->height) {
660     case  576: f1 = 23; f2 = 336; break;
661     case  608: f1 =  7; f2 = 320; break;
662     case  480: f1 = 20; f2 = 283; break;
663     case  512: f1 =  7; f2 = 270; break;
664     case  720: f1 = 26; f2 =   0; break; // progressive
665     case 1080: f1 = 21; f2 = 584; break;
666     default:   f1 =  0; f2 =   0; break;
667     }
668
669     if (!sc->interlaced) {
670         f2  = 0;
671         f1 *= 2;
672     }
673
674     mxf_write_local_tag(pb, 12+sc->interlaced*4, 0x320D);
675     put_be32(pb, sc->interlaced ? 2 : 1);
676     put_be32(pb, 4);
677     put_be32(pb, f1);
678     if (sc->interlaced)
679         put_be32(pb, f2);
680
681     av_reduce(&dar.num, &dar.den,
682               st->codec->width*st->codec->sample_aspect_ratio.num,
683               st->codec->height*st->codec->sample_aspect_ratio.den,
684               1024*1024);
685
686     mxf_write_local_tag(pb, 8, 0x320E);
687     put_be32(pb, dar.num);
688     put_be32(pb, dar.den);
689
690     mxf_write_local_tag(pb, 16, 0x3201);
691     put_buffer(pb, *sc->codec_ul, 16);
692 }
693
694 static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
695 {
696     ByteIOContext *pb = s->pb;
697
698     mxf_write_generic_desc(pb, st, key, size);
699
700     // audio locked
701     mxf_write_local_tag(pb, 1, 0x3D02);
702     put_byte(pb, 1);
703
704     // write audio sampling rate
705     mxf_write_local_tag(pb, 8, 0x3D03);
706     put_be32(pb, st->codec->sample_rate);
707     put_be32(pb, 1);
708
709     mxf_write_local_tag(pb, 4, 0x3D07);
710     put_be32(pb, st->codec->channels);
711
712     mxf_write_local_tag(pb, 4, 0x3D01);
713     put_be32(pb, av_get_bits_per_sample(st->codec->codec_id));
714 }
715
716 static void mxf_write_wav_common_desc(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
717 {
718     ByteIOContext *pb = s->pb;
719
720     mxf_write_generic_sound_desc(s, st, key, size);
721
722     mxf_write_local_tag(pb, 2, 0x3D0A);
723     put_be16(pb, st->codec->block_align);
724
725     // avg bytes per sec
726     mxf_write_local_tag(pb, 4, 0x3D09);
727     put_be32(pb, st->codec->block_align*st->codec->sample_rate);
728 }
729
730 static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st)
731 {
732     mxf_write_wav_common_desc(s, st, mxf_wav_descriptor_key, 107);
733 }
734
735 static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st)
736 {
737     mxf_write_wav_common_desc(s, st, mxf_aes3_descriptor_key, 107);
738 }
739
740 static void mxf_write_package(AVFormatContext *s, enum MXFMetadataSetType type)
741 {
742     ByteIOContext *pb = s->pb;
743     int i;
744
745     if (type == MaterialPackage) {
746         mxf_write_metadata_key(pb, 0x013600);
747         PRINT_KEY(s, "Material Package key", pb->buf_ptr - 16);
748         klv_encode_ber_length(pb, 92 + 16 * s->nb_streams);
749     } else {
750         mxf_write_metadata_key(pb, 0x013700);
751         PRINT_KEY(s, "Source Package key", pb->buf_ptr - 16);
752         klv_encode_ber_length(pb, 112 + 16 * s->nb_streams); // 20 bytes length for descriptor reference
753     }
754
755     // write uid
756     mxf_write_local_tag(pb, 16, 0x3C0A);
757     mxf_write_uuid(pb, type, 0);
758     av_log(s,AV_LOG_DEBUG, "package type:%d\n", type);
759     PRINT_KEY(s, "package uid", pb->buf_ptr - 16);
760
761     // write package umid
762     mxf_write_local_tag(pb, 32, 0x4401);
763     mxf_write_umid(pb, type, 0);
764     PRINT_KEY(s, "package umid second part", pb->buf_ptr - 16);
765
766     // write create date
767     mxf_write_local_tag(pb, 8, 0x4405);
768     put_be64(pb, 0);
769
770     // write modified date
771     mxf_write_local_tag(pb, 8, 0x4404);
772     put_be64(pb, 0);
773
774     // write track refs
775     mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x4403);
776     mxf_write_refs_count(pb, s->nb_streams);
777     for (i = 0; i < s->nb_streams; i++)
778         mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, i);
779
780     // write multiple descriptor reference
781     if (type == SourcePackage) {
782         mxf_write_local_tag(pb, 16, 0x4701);
783         if (s->nb_streams > 1) {
784             mxf_write_uuid(pb, MultipleDescriptor, 0);
785             mxf_write_multi_descriptor(s);
786         } else
787             mxf_write_uuid(pb, SubDescriptor, 0);
788     }
789
790     for (i = 0; i < s->nb_streams; i++) {
791         AVStream *st = s->streams[i];
792         mxf_write_track(s, st, type);
793         mxf_write_sequence(s, st, type);
794         mxf_write_structural_component(s, st, type);
795
796         if (type == SourcePackage) {
797             MXFStreamContext *sc = st->priv_data;
798             mxf_essence_container_uls[sc->index].write_desc(s, st);
799         }
800     }
801 }
802
803 static int mxf_write_essence_container_data(AVFormatContext *s)
804 {
805     ByteIOContext *pb = s->pb;
806
807     mxf_write_metadata_key(pb, 0x012300);
808     klv_encode_ber_length(pb, 72);
809
810     mxf_write_local_tag(pb, 16, 0x3C0A); // Instance UID
811     mxf_write_uuid(pb, EssenceContainerData, 0);
812
813     mxf_write_local_tag(pb, 32, 0x2701); // Linked Package UID
814     mxf_write_umid(pb, SourcePackage, 0);
815
816     mxf_write_local_tag(pb, 4, 0x3F07); // BodySID
817     put_be32(pb, 1);
818
819     mxf_write_local_tag(pb, 4, 0x3F06); // IndexSID
820     put_be32(pb, 2);
821
822     return 0;
823 }
824
825 static int mxf_write_header_metadata_sets(AVFormatContext *s)
826 {
827     mxf_write_preface(s);
828     mxf_write_identification(s);
829     mxf_write_content_storage(s);
830     mxf_write_package(s, MaterialPackage);
831     mxf_write_package(s, SourcePackage);
832     mxf_write_essence_container_data(s);
833     return 0;
834 }
835
836 static int mxf_write_index_table_segment(AVFormatContext *s)
837 {
838     MXFContext *mxf = s->priv_data;
839     ByteIOContext *pb = s->pb;
840     int i, j, k, ret, key_offset = 0;
841     int temporal_reordering = 0;
842
843     av_log(s, AV_LOG_DEBUG, "edit units count %d\n", mxf->edit_units_count);
844
845     put_buffer(pb, index_table_segment_key, 16);
846     ret = klv_encode_ber_length(pb, 109 + s->nb_streams*6 +
847                                 mxf->edit_units_count*(11+(s->nb_streams-1)*4));
848
849     // instance id
850     mxf_write_local_tag(pb, 16, 0x3C0A);
851     mxf_write_uuid(pb, IndexTableSegment, 0);
852
853     // index edit rate
854     mxf_write_local_tag(pb, 8, 0x3F0B);
855     put_be32(pb, mxf->time_base.num);
856     put_be32(pb, mxf->time_base.den);
857
858     // index start position
859     mxf_write_local_tag(pb, 8, 0x3F0C);
860     put_be64(pb, 0);
861
862     // index duration
863     mxf_write_local_tag(pb, 8, 0x3F0D);
864     put_be64(pb, mxf->edit_units_count);
865
866     // edit unit byte count
867     mxf_write_local_tag(pb, 4, 0x3F05);
868     put_be32(pb, 0);
869
870     // index sid
871     mxf_write_local_tag(pb, 4, 0x3F06);
872     put_be32(pb, 2);
873
874     // body sid
875     mxf_write_local_tag(pb, 4, 0x3F07);
876     put_be32(pb, 1);
877
878     // slice count - 1
879     mxf_write_local_tag(pb, 1, 0x3F08);
880     put_byte(pb, s->nb_streams-1);
881
882     // delta entry array
883     mxf_write_local_tag(pb, 8 + s->nb_streams*6, 0x3F09);
884     put_be32(pb, s->nb_streams); // num of entries
885     put_be32(pb, 6);             // size of one entry
886     for (i = 0; i < s->nb_streams; i++) {
887         AVStream *st = s->streams[i];
888         MXFStreamContext *sc = st->priv_data;
889         put_byte(pb, sc->temporal_reordering);
890         if (sc->temporal_reordering)
891             temporal_reordering = 1;
892         put_byte(pb, i);
893         put_be32(pb, 0); // element delta
894     }
895
896     mxf_write_local_tag(pb, 8 + mxf->edit_units_count*(11+(s->nb_streams-1)*4), 0x3F0A);
897     put_be32(pb, mxf->edit_units_count);  // num of entries
898     put_be32(pb, 11+(s->nb_streams-1)*4); // size of one entry
899     for (i = 0; i < mxf->edit_units_count; i++) {
900         if (mxf->index_entries[i].flags & 0x40)
901             key_offset = 0;
902         if (temporal_reordering) {
903             int temporal_offset = 0;
904             for (j = i+1; j < mxf->edit_units_count; j++) {
905                 temporal_offset++;
906                 if (mxf->index_entries[j].flags & 0x10) { // backward prediction
907                     // next is not b, so is reordered
908                     if (!(mxf->index_entries[i+1].flags & 0x10)) {
909                         if ((mxf->index_entries[i].flags & 0x11) == 0) // i frame
910                             temporal_offset = 0;
911                         else
912                             temporal_offset = -temporal_offset;
913                     }
914                     break;
915                 }
916             }
917             put_byte(pb, temporal_offset);
918         } else
919             put_byte(pb, 0);
920         put_byte(pb, key_offset);
921         put_byte(pb, mxf->index_entries[i].flags);
922         // stream offset
923         put_be64(pb, mxf->index_entries[i].offset - mxf->index_entries[0].offset);
924         for (k = 0; k < s->nb_streams; k++) {
925             if (mxf->index_entries[i].slice_offset[k])
926                 put_be32(pb, mxf->index_entries[i].slice_offset[k]);
927         }
928         key_offset--;
929     }
930
931     return ret;
932 }
933
934 static void mxf_write_partition(AVFormatContext *s, int bodysid,
935                                 int indexsid, unsigned index_byte_count,
936                                 const uint8_t *key, int write_metadata)
937 {
938     MXFContext *mxf = s->priv_data;
939     ByteIOContext *pb = s->pb;
940     int64_t header_byte_count_offset;
941
942     // write klv
943     put_buffer(pb, key, 16);
944
945     klv_encode_ber_length(pb, 88 + 16 * mxf->essence_container_count);
946
947     // write partition value
948     put_be16(pb, 1); // majorVersion
949     put_be16(pb, 2); // minorVersion
950     put_be32(pb, 1); // kagSize
951
952     put_be64(pb, url_ftell(pb) - 25); // thisPartition
953     put_be64(pb, 0); // previousPartition
954
955     put_be64(pb, mxf->footer_partition_offset); // footerPartition
956
957     // set offset
958     header_byte_count_offset = url_ftell(pb);
959     put_be64(pb, 0); // headerByteCount, update later
960
961     // indexTable
962     put_be64(pb, index_byte_count); // indexByteCount
963     put_be32(pb, indexsid); // indexSID
964     put_be64(pb, 0); // bodyOffset
965
966     put_be32(pb, bodysid); // bodySID
967     put_buffer(pb, op1a_ul, 16); // operational pattern
968
969     // essence container
970     mxf_write_essence_container_refs(s);
971
972     if (write_metadata) {
973         // mark the start of the headermetadata and calculate metadata size
974         int64_t pos, start = url_ftell(s->pb);
975         mxf_write_primer_pack(s);
976         mxf_write_header_metadata_sets(s);
977         pos = url_ftell(s->pb);
978         // update header_byte_count
979         url_fseek(pb, header_byte_count_offset, SEEK_SET);
980         put_be64(pb, pos - start);
981         url_fseek(pb, pos, SEEK_SET);
982     }
983
984     put_flush_packet(pb);
985 }
986
987 static const UID mxf_mpeg2_codec_uls[] = {
988     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x10,0x00 }, // MP-ML I-Frame
989     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, // MP-ML Long GOP
990     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, // 422P-ML I-Frame
991     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, // 422P-ML Long GOP
992     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x02,0x00 }, // MP-HL I-Frame
993     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, // MP-HL Long GOP
994     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, // 422P-HL I-Frame
995     { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, // 422P-HL Long GOP
996 };
997
998 static const UID *mxf_get_mpeg2_codec_ul(AVCodecContext *avctx)
999 {
1000     if (avctx->profile == 4) { // Main
1001         if (avctx->level == 8) // Main
1002             return avctx->gop_size ?
1003                 &mxf_mpeg2_codec_uls[1] :
1004                 &mxf_mpeg2_codec_uls[0];
1005         else if (avctx->level == 4) // High
1006             return avctx->gop_size ?
1007                 &mxf_mpeg2_codec_uls[5] :
1008                 &mxf_mpeg2_codec_uls[4];
1009     } else if (avctx->profile == 0) { // 422
1010         if (avctx->level == 5) // Main
1011             return avctx->gop_size ?
1012                 &mxf_mpeg2_codec_uls[3] :
1013                 &mxf_mpeg2_codec_uls[2];
1014         else if (avctx->level == 2) // High
1015             return avctx->gop_size ?
1016                 &mxf_mpeg2_codec_uls[7] :
1017                 &mxf_mpeg2_codec_uls[6];
1018     }
1019     return NULL;
1020 }
1021
1022 static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
1023 {
1024     MXFContext *mxf = s->priv_data;
1025     MXFStreamContext *sc = st->priv_data;
1026     uint32_t c = -1;
1027     int i;
1028
1029     mxf->index_entries[mxf->edit_units_count].flags = 0;
1030
1031     for(i = 0; i < pkt->size - 4; i++) {
1032         c = (c<<8) + pkt->data[i];
1033         if (c == 0x1B5) {
1034             if (i + 2 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x10) { // seq ext
1035                 st->codec->profile = pkt->data[i+1] & 0x07;
1036                 st->codec->level   = pkt->data[i+2] >> 4;
1037             } else if (i + 5 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x80) { // pict coding ext
1038                 sc->interlaced = !(pkt->data[i+5] & 0x80); // progressive frame
1039                 break;
1040             }
1041         } else if (c == 0x1b8) { // gop
1042             if (i + 4 < pkt->size && pkt->data[i+4]>>6 & 0x01) // closed
1043                 mxf->index_entries[mxf->edit_units_count].flags |= 0x80; // random access
1044         } else if (c == 0x1b3) { // seq
1045             mxf->index_entries[mxf->edit_units_count].flags |= 0x40;
1046         } else if (c == 0x100) { // pic
1047             int pict_type = (pkt->data[i+2]>>3) & 0x07;
1048             if (pict_type == 2) { // P frame
1049                 mxf->index_entries[mxf->edit_units_count].flags |= 0x22;
1050                 st->codec->gop_size = 1;
1051             } else if (pict_type == 3) { // B frame
1052                 mxf->index_entries[mxf->edit_units_count].flags |= 0x33;
1053                 sc->temporal_reordering = -1;
1054             } else if (!pict_type) {
1055                 av_log(s, AV_LOG_ERROR, "error parsing mpeg2 frame\n");
1056                 return 0;
1057             }
1058         }
1059     }
1060     sc->codec_ul = mxf_get_mpeg2_codec_ul(st->codec);
1061     return !!sc->codec_ul;
1062 }
1063
1064 static int ff_audio_interleave_init(AVFormatContext *s,
1065                                     const int *samples_per_frame,
1066                                     AVRational time_base)
1067 {
1068     int i;
1069
1070     if (!samples_per_frame)
1071         return -1;
1072
1073     for (i = 0; i < s->nb_streams; i++) {
1074         AVStream *st = s->streams[i];
1075         AudioInterleaveContext *aic = st->priv_data;
1076
1077         if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1078             aic->sample_size = (st->codec->channels *
1079                                 av_get_bits_per_sample(st->codec->codec_id)) / 8;
1080             if (!aic->sample_size) {
1081                 av_log(s, AV_LOG_ERROR, "could not compute sample size\n");
1082                 return -1;
1083             }
1084             aic->samples_per_frame = samples_per_frame;
1085             aic->samples = aic->samples_per_frame;
1086             aic->time_base = time_base;
1087
1088             av_fifo_init(&aic->fifo, 100 * *aic->samples);
1089         }
1090     }
1091
1092     return 0;
1093 }
1094
1095 static void ff_audio_interleave_close(AVFormatContext *s)
1096 {
1097     int i;
1098     for (i = 0; i < s->nb_streams; i++) {
1099         AVStream *st = s->streams[i];
1100         AudioInterleaveContext *aic = st->priv_data;
1101
1102         if (st->codec->codec_type == CODEC_TYPE_AUDIO)
1103             av_fifo_free(&aic->fifo);
1104     }
1105 }
1106
1107 static int mxf_write_header(AVFormatContext *s)
1108 {
1109     MXFContext *mxf = s->priv_data;
1110     int i;
1111     uint8_t present[FF_ARRAY_ELEMS(mxf_essence_container_uls)] = {0};
1112     const int *samples_per_frame = NULL;
1113
1114     if (s->nb_streams > 17) {
1115         av_log(s, AV_LOG_ERROR, "error, mxf muxer supports 17 tracks maximum\n");
1116         return -1;
1117     }
1118
1119     for (i = 0; i < s->nb_streams; i++) {
1120         AVStream *st = s->streams[i];
1121         MXFStreamContext *sc = av_mallocz(sizeof(*sc));
1122         if (!sc)
1123             return AVERROR(ENOMEM);
1124         st->priv_data = sc;
1125
1126         if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1127             if (fabs(av_q2d(st->codec->time_base) - 1/25.0) < 0.0001) {
1128                 samples_per_frame = PAL_samples_per_frame;
1129                 mxf->time_base = (AVRational){ 1, 25 };
1130             } else if (fabs(av_q2d(st->codec->time_base) - 1001/30000.0) < 0.0001) {
1131                 samples_per_frame = NTSC_samples_per_frame;
1132                 mxf->time_base = (AVRational){ 1001, 30000 };
1133             } else {
1134                 av_log(s, AV_LOG_ERROR, "unsupported video frame rate\n");
1135                 return -1;
1136             }
1137             mxf->edit_unit_start = st->index;
1138             av_set_pts_info(st, 64, mxf->time_base.num, mxf->time_base.den);
1139         } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1140             if (st->codec->sample_rate != 48000) {
1141                 av_log(s, AV_LOG_ERROR, "only 48khz is implemented\n");
1142                 return -1;
1143             }
1144             av_set_pts_info(st, 64, 1, st->codec->sample_rate);
1145         }
1146         sc->duration = -1;
1147
1148         sc->index = mxf_get_essence_container_ul_index(st->codec->codec_id);
1149         if (sc->index == -1) {
1150             av_log(s, AV_LOG_ERROR, "track %d: could not find essence container ul, "
1151                    "codec not currently supported in container\n", i);
1152             return -1;
1153         }
1154
1155         sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
1156
1157         if (!present[sc->index]) {
1158             mxf->essence_containers_indices[mxf->essence_container_count++] = sc->index;
1159             present[sc->index] = 1;
1160         } else
1161             present[sc->index]++;
1162         memcpy(sc->track_essence_element_key, mxf_essence_container_uls[sc->index].element_ul, 15);
1163         sc->track_essence_element_key[15] = present[sc->index];
1164         PRINT_KEY(s, "track essence element key", sc->track_essence_element_key);
1165     }
1166
1167     for (i = 0; i < s->nb_streams; i++) {
1168         MXFStreamContext *sc = s->streams[i]->priv_data;
1169         // update element count
1170         sc->track_essence_element_key[13] = present[sc->index];
1171         sc->order = AV_RB32(sc->track_essence_element_key+12);
1172     }
1173
1174     if (!samples_per_frame)
1175         samples_per_frame = PAL_samples_per_frame;
1176
1177     if (ff_audio_interleave_init(s, samples_per_frame, mxf->time_base) < 0)
1178         return -1;
1179
1180     return 0;
1181 }
1182
1183 static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
1184 {
1185     MXFContext *mxf = s->priv_data;
1186     ByteIOContext *pb = s->pb;
1187     AVStream *st = s->streams[pkt->stream_index];
1188     MXFStreamContext *sc = st->priv_data;
1189
1190     if (!(mxf->edit_units_count % MXF_INDEX_CLUSTER_SIZE)) {
1191         mxf->index_entries = av_realloc(mxf->index_entries,
1192             (mxf->edit_units_count + MXF_INDEX_CLUSTER_SIZE)*
1193              sizeof(*mxf->index_entries));
1194         if (!mxf->index_entries) {
1195             av_log(s, AV_LOG_ERROR, "could not allocate index entries\n");
1196             return -1;
1197         }
1198     }
1199
1200     if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO) {
1201         if (!mxf_parse_mpeg2_frame(s, st, pkt)) {
1202             av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
1203             return -1;
1204         }
1205     }
1206
1207     if (!mxf->header_written) {
1208         mxf_write_partition(s, 1, 0, 0, header_open_partition_key, 1);
1209         mxf->header_written = 1;
1210     }
1211
1212     if (st->index == mxf->edit_unit_start) {
1213         mxf->index_entries[mxf->edit_units_count].offset = url_ftell(pb);
1214         mxf->index_entries[mxf->edit_units_count].slice_offset[st->index] = 0;
1215         mxf->edit_units_count++;
1216     } else {
1217         mxf->index_entries[mxf->edit_units_count-1].slice_offset[st->index] =
1218             url_ftell(pb) - mxf->index_entries[mxf->edit_units_count-1].offset;
1219     }
1220
1221     put_buffer(pb, sc->track_essence_element_key, 16); // write key
1222     klv_encode_ber_length(pb, pkt->size); // write length
1223     put_buffer(pb, pkt->data, pkt->size); // write value
1224
1225     sc->duration = FFMAX(pkt->pts + pkt->duration, sc->duration);
1226
1227     put_flush_packet(pb);
1228     return 0;
1229 }
1230
1231 static void mxf_write_random_index_pack(AVFormatContext *s)
1232 {
1233     MXFContext *mxf = s->priv_data;
1234     ByteIOContext *pb = s->pb;
1235     uint64_t pos = url_ftell(pb);
1236
1237     put_buffer(pb, random_index_pack_key, 16);
1238     klv_encode_ber_length(pb, 28);
1239
1240     put_be32(pb, 1); // BodySID of header partition
1241     put_be64(pb, 0); // offset of header partition
1242
1243     put_be32(pb, 0); // BodySID of footer partition
1244     put_be64(pb, mxf->footer_partition_offset);
1245
1246     put_be32(pb, url_ftell(pb) - pos + 4);
1247 }
1248
1249 static int mxf_write_footer(AVFormatContext *s)
1250 {
1251     MXFContext *mxf = s->priv_data;
1252     ByteIOContext *pb = s->pb;
1253     unsigned index_byte_count =
1254         109 + s->nb_streams*6 +
1255         mxf->edit_units_count*(11+(s->nb_streams-1)*4);
1256
1257     // add encoded ber length
1258     index_byte_count += 16 +
1259         (index_byte_count < 128 ? 1 : (av_log2(index_byte_count) >> 3) + 2);
1260
1261     mxf->footer_partition_offset = url_ftell(pb);
1262     mxf_write_partition(s, 0, 2, index_byte_count, footer_partition_key, 0);
1263
1264     mxf_write_index_table_segment(s);
1265
1266     mxf_write_random_index_pack(s);
1267
1268     if (!url_is_streamed(s->pb)) {
1269         url_fseek(pb, 0, SEEK_SET);
1270         mxf_write_partition(s, 1, 0, 0, header_closed_partition_key, 1);
1271     }
1272
1273     ff_audio_interleave_close(s);
1274
1275     mxf_free(s);
1276     return 0;
1277 }
1278
1279 static int mxf_interleave_new_audio_packet(AVFormatContext *s, AVPacket *pkt,
1280                                            int stream_index, int flush)
1281 {
1282     AVStream *st = s->streams[stream_index];
1283     AudioInterleaveContext *aic = st->priv_data;
1284
1285     int size = FFMIN(av_fifo_size(&aic->fifo), *aic->samples * aic->sample_size);
1286     if (!size || (!flush && size == av_fifo_size(&aic->fifo)))
1287         return 0;
1288
1289     av_new_packet(pkt, size);
1290     av_fifo_read(&aic->fifo, pkt->data, size);
1291
1292     pkt->dts = pkt->pts = aic->dts;
1293     pkt->duration = av_rescale_q(*aic->samples, st->time_base, aic->time_base);
1294     pkt->stream_index = stream_index;
1295     aic->dts += pkt->duration;
1296
1297     aic->samples++;
1298     if (!*aic->samples)
1299         aic->samples = aic->samples_per_frame;
1300
1301     return size;
1302 }
1303
1304 static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1305 {
1306     AVPacketList *pktl;
1307     int stream_count = 0;
1308     int streams[MAX_STREAMS];
1309
1310     memset(streams, 0, sizeof(streams));
1311     pktl = s->packet_buffer;
1312     while (pktl) {
1313         //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
1314         if (!streams[pktl->pkt.stream_index])
1315             stream_count++;
1316         streams[pktl->pkt.stream_index]++;
1317         pktl = pktl->next;
1318     }
1319
1320     if (stream_count && (s->nb_streams == stream_count || flush)) {
1321         pktl = s->packet_buffer;
1322         if (s->nb_streams != stream_count) {
1323             MXFContext *mxf = s->priv_data;
1324             AVPacketList *first = NULL;
1325             // find first packet in edit unit
1326             while (pktl) {
1327                 AVStream *st = s->streams[pktl->pkt.stream_index];
1328                 if (st->index == mxf->edit_unit_start)
1329                     break;
1330                 else if (!first)
1331                     first = pktl;
1332                 pktl = pktl->next;
1333             }
1334             // purge packet queue
1335             while (pktl) {
1336                 AVPacketList *next = pktl->next;
1337                 av_free_packet(&pktl->pkt);
1338                 av_freep(&pktl);
1339                 pktl = next;
1340             }
1341             if (!first)
1342                 goto out;
1343             pktl = first;
1344         }
1345
1346         *out = pktl->pkt;
1347         //av_log(s, AV_LOG_DEBUG, "out st:%d dts:%lld\n", (*out).stream_index, (*out).dts);
1348         s->packet_buffer = pktl->next;
1349         av_freep(&pktl);
1350         return 1;
1351     } else {
1352     out:
1353         av_init_packet(out);
1354         return 0;
1355     }
1356 }
1357
1358 static int mxf_compare_timestamps(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
1359 {
1360     MXFStreamContext *sc  = s->streams[pkt ->stream_index]->priv_data;
1361     MXFStreamContext *sc2 = s->streams[next->stream_index]->priv_data;
1362
1363     return next->dts > pkt->dts ||
1364         (next->dts == pkt->dts && sc->order < sc2->order);
1365 }
1366
1367 static int mxf_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1368 {
1369     int i;
1370
1371     if (pkt) {
1372         AVStream *st = s->streams[pkt->stream_index];
1373         AudioInterleaveContext *aic = st->priv_data;
1374         if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1375             av_fifo_generic_write(&aic->fifo, pkt->data, pkt->size, NULL);
1376         } else {
1377             // rewrite pts and dts to be decoded time line position
1378             pkt->pts = pkt->dts = aic->dts;
1379             aic->dts += pkt->duration;
1380             ff_interleave_add_packet(s, pkt, mxf_compare_timestamps);
1381         }
1382         pkt = NULL;
1383     }
1384
1385     for (i = 0; i < s->nb_streams; i++) {
1386         AVStream *st = s->streams[i];
1387         if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1388             AVPacket new_pkt;
1389             while (mxf_interleave_new_audio_packet(s, &new_pkt, i, flush))
1390                 ff_interleave_add_packet(s, &new_pkt, mxf_compare_timestamps);
1391         }
1392     }
1393
1394     return mxf_interleave_get_packet(s, out, pkt, flush);
1395 }
1396
1397 AVOutputFormat mxf_muxer = {
1398     "mxf",
1399     NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1400     NULL,
1401     "mxf",
1402     sizeof(MXFContext),
1403     CODEC_ID_PCM_S16LE,
1404     CODEC_ID_MPEG2VIDEO,
1405     mxf_write_header,
1406     mxf_write_packet,
1407     mxf_write_footer,
1408     AVFMT_NOTIMESTAMPS,
1409     NULL,
1410     mxf_interleave,
1411 };