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