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