Statistics
| Branch: | Revision:

ffmpeg / libavformat / mxfenc.c @ 85d0d114

History | View | Annotate | Download (53 KB)

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*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*6, 0x3F09);
911
    put_be32(pb, s->nb_streams); // num of entries
912
    put_be32(pb, 6);             // size of one entry
913
    for (i = 0; i < s->nb_streams; i++) {
914
        AVStream *st = s->streams[i];
915
        MXFStreamContext *sc = st->priv_data;
916
        put_byte(pb, sc->temporal_reordering);
917
        if (sc->temporal_reordering)
918
            temporal_reordering = 1;
919
        put_byte(pb, i);
920
        put_be32(pb, 0); // element delta
921
    }
922

    
923
    mxf_write_local_tag(pb, 8 + mxf->edit_units_count*(11+(s->nb_streams-1)*4), 0x3F0A);
924
    put_be32(pb, mxf->edit_units_count);  // num of entries
925
    put_be32(pb, 11+(s->nb_streams-1)*4); // size of one entry
926
    for (i = 0; i < mxf->edit_units_count; i++) {
927
        if (temporal_reordering) {
928
            int temporal_offset = 0;
929
            for (j = i+1; j < mxf->edit_units_count; j++) {
930
                temporal_offset++;
931
                if (mxf->index_entries[j].flags & 0x10) { // backward prediction
932
                    // next is not b, so is reordered
933
                    if (!(mxf->index_entries[i+1].flags & 0x10)) {
934
                        if ((mxf->index_entries[i].flags & 0x11) == 0) // i frame
935
                            temporal_offset = 0;
936
                        else
937
                            temporal_offset = -temporal_offset;
938
                    }
939
                    break;
940
                }
941
            }
942
            put_byte(pb, temporal_offset);
943
        } else
944
            put_byte(pb, 0);
945
        if (!(mxf->index_entries[i].flags & 0x33)) { // I frame
946
            last_key_index = key_index;
947
            key_index = i;
948
        }
949
        if (mxf->index_entries[i].flags & 0x10 && // backward prediction
950
            !(mxf->index_entries[key_index].flags & 0x80)) { // open gop
951
            put_byte(pb, last_key_index - i);
952
        } else {
953
            put_byte(pb, key_index - i); // key frame offset
954
            if ((mxf->index_entries[i].flags & 0x20) == 0x20) // only forward
955
                last_key_index = key_index;
956
        }
957
        put_byte(pb, mxf->index_entries[i].flags);
958
        // stream offset
959
        put_be64(pb, mxf->index_entries[i].offset - mxf->index_entries[0].offset);
960
        for (k = 0; k < s->nb_streams; k++) {
961
            if (mxf->index_entries[i].slice_offset[k])
962
                put_be32(pb, mxf->index_entries[i].slice_offset[k]);
963
        }
964
    }
965

    
966
    return ret;
967
}
968

    
969
static void mxf_write_partition(AVFormatContext *s, int bodysid,
970
                                int indexsid, unsigned index_byte_count,
971
                                const uint8_t *key, int write_metadata)
972
{
973
    MXFContext *mxf = s->priv_data;
974
    ByteIOContext *pb = s->pb;
975
    int64_t header_byte_count_offset;
976

    
977
    // write klv
978
    put_buffer(pb, key, 16);
979

    
980
    klv_encode_ber_length(pb, 88 + 16 * mxf->essence_container_count);
981

    
982
    // write partition value
983
    put_be16(pb, 1); // majorVersion
984
    put_be16(pb, 2); // minorVersion
985
    put_be32(pb, KAG_SIZE); // KAGSize
986

    
987
    put_be64(pb, url_ftell(pb) - 25); // thisPartition
988
    put_be64(pb, 0); // previousPartition
989

    
990
    put_be64(pb, mxf->footer_partition_offset); // footerPartition
991

    
992
    // set offset
993
    header_byte_count_offset = url_ftell(pb);
994
    put_be64(pb, 0); // headerByteCount, update later
995

    
996
    // indexTable
997
    put_be64(pb, index_byte_count); // indexByteCount
998
    put_be32(pb, indexsid); // indexSID
999
    put_be64(pb, 0); // bodyOffset
1000

    
1001
    put_be32(pb, bodysid); // bodySID
1002
    put_buffer(pb, op1a_ul, 16); // operational pattern
1003

    
1004
    // essence container
1005
    mxf_write_essence_container_refs(s);
1006

    
1007
    if (write_metadata) {
1008
        // mark the start of the headermetadata and calculate metadata size
1009
        int64_t pos, start = url_ftell(s->pb);
1010
        unsigned header_byte_count;
1011

    
1012
        mxf_write_primer_pack(s);
1013
        mxf_write_header_metadata_sets(s);
1014
        pos = url_ftell(s->pb);
1015
        header_byte_count = pos - start + klv_fill_size(s);
1016

    
1017
        // update header_byte_count
1018
        url_fseek(pb, header_byte_count_offset, SEEK_SET);
1019
        put_be64(pb, header_byte_count);
1020
        url_fseek(pb, pos, SEEK_SET);
1021
    }
1022

    
1023
    put_flush_packet(pb);
1024
}
1025

    
1026
static const UID mxf_mpeg2_codec_uls[] = {
1027
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x10,0x00 }, // MP-ML I-Frame
1028
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, // MP-ML Long GOP
1029
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, // 422P-ML I-Frame
1030
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, // 422P-ML Long GOP
1031
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x02,0x00 }, // MP-HL I-Frame
1032
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, // MP-HL Long GOP
1033
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, // 422P-HL I-Frame
1034
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, // 422P-HL Long GOP
1035
};
1036

    
1037
static const UID *mxf_get_mpeg2_codec_ul(AVCodecContext *avctx)
1038
{
1039
    if (avctx->profile == 4) { // Main
1040
        if (avctx->level == 8) // Main
1041
            return avctx->gop_size ?
1042
                &mxf_mpeg2_codec_uls[1] :
1043
                &mxf_mpeg2_codec_uls[0];
1044
        else if (avctx->level == 4) // High
1045
            return avctx->gop_size ?
1046
                &mxf_mpeg2_codec_uls[5] :
1047
                &mxf_mpeg2_codec_uls[4];
1048
    } else if (avctx->profile == 0) { // 422
1049
        if (avctx->level == 5) // Main
1050
            return avctx->gop_size ?
1051
                &mxf_mpeg2_codec_uls[3] :
1052
                &mxf_mpeg2_codec_uls[2];
1053
        else if (avctx->level == 2) // High
1054
            return avctx->gop_size ?
1055
                &mxf_mpeg2_codec_uls[7] :
1056
                &mxf_mpeg2_codec_uls[6];
1057
    }
1058
    return NULL;
1059
}
1060

    
1061
static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
1062
{
1063
    MXFContext *mxf = s->priv_data;
1064
    MXFStreamContext *sc = st->priv_data;
1065
    uint32_t c = -1;
1066
    int i;
1067

    
1068
    mxf->index_entries[mxf->edit_units_count].flags = 0;
1069

    
1070
    for(i = 0; i < pkt->size - 4; i++) {
1071
        c = (c<<8) + pkt->data[i];
1072
        if (c == 0x1B5) {
1073
            if (i + 2 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x10) { // seq ext
1074
                st->codec->profile = pkt->data[i+1] & 0x07;
1075
                st->codec->level   = pkt->data[i+2] >> 4;
1076
            } else if (i + 5 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x80) { // pict coding ext
1077
                sc->interlaced = !(pkt->data[i+5] & 0x80); // progressive frame
1078
                break;
1079
            }
1080
        } else if (c == 0x1b8) { // gop
1081
            if (i + 4 < pkt->size && pkt->data[i+4]>>6 & 0x01) // closed
1082
                mxf->index_entries[mxf->edit_units_count].flags |= 0x80; // random access
1083
        } else if (c == 0x1b3) { // seq
1084
            mxf->index_entries[mxf->edit_units_count].flags |= 0x40;
1085
        } else if (c == 0x100) { // pic
1086
            int pict_type = (pkt->data[i+2]>>3) & 0x07;
1087
            if (pict_type == 2) { // P frame
1088
                mxf->index_entries[mxf->edit_units_count].flags |= 0x22;
1089
                st->codec->gop_size = 1;
1090
            } else if (pict_type == 3) { // B frame
1091
                mxf->index_entries[mxf->edit_units_count].flags |= 0x33;
1092
                sc->temporal_reordering = -1;
1093
            } else if (!pict_type) {
1094
                av_log(s, AV_LOG_ERROR, "error parsing mpeg2 frame\n");
1095
                return 0;
1096
            }
1097
        }
1098
    }
1099
    sc->codec_ul = mxf_get_mpeg2_codec_ul(st->codec);
1100
    return !!sc->codec_ul;
1101
}
1102

    
1103
static int ff_audio_interleave_init(AVFormatContext *s,
1104
                                    const int *samples_per_frame,
1105
                                    AVRational time_base)
1106
{
1107
    int i;
1108

    
1109
    if (!samples_per_frame)
1110
        return -1;
1111

    
1112
    for (i = 0; i < s->nb_streams; i++) {
1113
        AVStream *st = s->streams[i];
1114
        AudioInterleaveContext *aic = st->priv_data;
1115

    
1116
        if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1117
            aic->sample_size = (st->codec->channels *
1118
                                av_get_bits_per_sample(st->codec->codec_id)) / 8;
1119
            if (!aic->sample_size) {
1120
                av_log(s, AV_LOG_ERROR, "could not compute sample size\n");
1121
                return -1;
1122
            }
1123
            aic->samples_per_frame = samples_per_frame;
1124
            aic->samples = aic->samples_per_frame;
1125
            aic->time_base = time_base;
1126

    
1127
            av_fifo_init(&aic->fifo, 100 * *aic->samples);
1128
        }
1129
    }
1130

    
1131
    return 0;
1132
}
1133

    
1134
static void ff_audio_interleave_close(AVFormatContext *s)
1135
{
1136
    int i;
1137
    for (i = 0; i < s->nb_streams; i++) {
1138
        AVStream *st = s->streams[i];
1139
        AudioInterleaveContext *aic = st->priv_data;
1140

    
1141
        if (st->codec->codec_type == CODEC_TYPE_AUDIO)
1142
            av_fifo_free(&aic->fifo);
1143
    }
1144
}
1145

    
1146
static uint64_t mxf_parse_timestamp(time_t timestamp)
1147
{
1148
    struct tm *time = localtime(&timestamp);
1149
    return (uint64_t)(time->tm_year+1900) << 48 |
1150
           (uint64_t)(time->tm_mon+1)     << 40 |
1151
           (uint64_t) time->tm_mday       << 32 |
1152
                      time->tm_hour       << 24 |
1153
                      time->tm_min        << 16 |
1154
                      time->tm_sec        << 8;
1155
}
1156

    
1157
static int mxf_write_header(AVFormatContext *s)
1158
{
1159
    MXFContext *mxf = s->priv_data;
1160
    int i;
1161
    uint8_t present[FF_ARRAY_ELEMS(mxf_essence_container_uls)] = {0};
1162
    const int *samples_per_frame = NULL;
1163

    
1164
    if (s->nb_streams > 17) {
1165
        av_log(s, AV_LOG_ERROR, "error, mxf muxer supports 17 tracks maximum\n");
1166
        return -1;
1167
    }
1168

    
1169
    for (i = 0; i < s->nb_streams; i++) {
1170
        AVStream *st = s->streams[i];
1171
        MXFStreamContext *sc = av_mallocz(sizeof(*sc));
1172
        if (!sc)
1173
            return AVERROR(ENOMEM);
1174
        st->priv_data = sc;
1175

    
1176
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1177
            if (fabs(av_q2d(st->codec->time_base) - 1/25.0) < 0.0001) {
1178
                samples_per_frame = PAL_samples_per_frame;
1179
                mxf->time_base = (AVRational){ 1, 25 };
1180
            } else if (fabs(av_q2d(st->codec->time_base) - 1001/30000.0) < 0.0001) {
1181
                samples_per_frame = NTSC_samples_per_frame;
1182
                mxf->time_base = (AVRational){ 1001, 30000 };
1183
            } else {
1184
                av_log(s, AV_LOG_ERROR, "unsupported video frame rate\n");
1185
                return -1;
1186
            }
1187
            mxf->edit_unit_start = st->index;
1188
            av_set_pts_info(st, 64, mxf->time_base.num, mxf->time_base.den);
1189
        } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1190
            if (st->codec->sample_rate != 48000) {
1191
                av_log(s, AV_LOG_ERROR, "only 48khz is implemented\n");
1192
                return -1;
1193
            }
1194
            av_set_pts_info(st, 64, 1, st->codec->sample_rate);
1195
        }
1196
        sc->duration = -1;
1197

    
1198
        sc->index = mxf_get_essence_container_ul_index(st->codec->codec_id);
1199
        if (sc->index == -1) {
1200
            av_log(s, AV_LOG_ERROR, "track %d: could not find essence container ul, "
1201
                   "codec not currently supported in container\n", i);
1202
            return -1;
1203
        }
1204

    
1205
        sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
1206

    
1207
        if (!present[sc->index]) {
1208
            mxf->essence_containers_indices[mxf->essence_container_count++] = sc->index;
1209
            present[sc->index] = 1;
1210
        } else
1211
            present[sc->index]++;
1212
        memcpy(sc->track_essence_element_key, mxf_essence_container_uls[sc->index].element_ul, 15);
1213
        sc->track_essence_element_key[15] = present[sc->index];
1214
        PRINT_KEY(s, "track essence element key", sc->track_essence_element_key);
1215
    }
1216

    
1217
    for (i = 0; i < s->nb_streams; i++) {
1218
        MXFStreamContext *sc = s->streams[i]->priv_data;
1219
        // update element count
1220
        sc->track_essence_element_key[13] = present[sc->index];
1221
        sc->order = AV_RB32(sc->track_essence_element_key+12);
1222
    }
1223

    
1224
    mxf->timestamp = mxf_parse_timestamp(s->timestamp);
1225

    
1226
    if (!samples_per_frame)
1227
        samples_per_frame = PAL_samples_per_frame;
1228

    
1229
    if (ff_audio_interleave_init(s, samples_per_frame, mxf->time_base) < 0)
1230
        return -1;
1231

    
1232
    return 0;
1233
}
1234

    
1235
static void mxf_write_klv_fill(AVFormatContext *s)
1236
{
1237
    unsigned pad = klv_fill_size(s);
1238
    if (pad) {
1239
        put_buffer(s->pb, klv_fill_key, 16);
1240
        pad -= 16;
1241
        pad -= klv_ber_length(pad);
1242
        klv_encode_ber_length(s->pb, pad);
1243
        for (; pad > 7; pad -= 8)
1244
            put_be64(s->pb, 0);
1245
        for (; pad; pad--)
1246
            put_byte(s->pb, 0);
1247
        assert(!(url_ftell(s->pb) & (KAG_SIZE-1)));
1248
    }
1249
}
1250

    
1251
static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
1252
{
1253
    MXFContext *mxf = s->priv_data;
1254
    ByteIOContext *pb = s->pb;
1255
    AVStream *st = s->streams[pkt->stream_index];
1256
    MXFStreamContext *sc = st->priv_data;
1257

    
1258
    if (!(mxf->edit_units_count % MXF_INDEX_CLUSTER_SIZE)) {
1259
        mxf->index_entries = av_realloc(mxf->index_entries,
1260
            (mxf->edit_units_count + MXF_INDEX_CLUSTER_SIZE)*
1261
             sizeof(*mxf->index_entries));
1262
        if (!mxf->index_entries) {
1263
            av_log(s, AV_LOG_ERROR, "could not allocate index entries\n");
1264
            return -1;
1265
        }
1266
    }
1267

    
1268
    if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO) {
1269
        if (!mxf_parse_mpeg2_frame(s, st, pkt)) {
1270
            av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
1271
            return -1;
1272
        }
1273
    }
1274

    
1275
    if (!mxf->header_written) {
1276
        mxf_write_partition(s, 1, 0, 0, header_open_partition_key, 1);
1277
        mxf->header_written = 1;
1278
    }
1279

    
1280
    mxf_write_klv_fill(s);
1281

    
1282
    if (st->index == mxf->edit_unit_start) {
1283
        mxf->index_entries[mxf->edit_units_count].offset = url_ftell(pb);
1284
        mxf->index_entries[mxf->edit_units_count].slice_offset[st->index] = 0;
1285
        mxf->edit_units_count++;
1286
    } else {
1287
        mxf->index_entries[mxf->edit_units_count-1].slice_offset[st->index] =
1288
            url_ftell(pb) - mxf->index_entries[mxf->edit_units_count-1].offset;
1289
    }
1290

    
1291
    put_buffer(pb, sc->track_essence_element_key, 16); // write key
1292
    klv_encode_ber_length(pb, pkt->size); // write length
1293
    put_buffer(pb, pkt->data, pkt->size); // write value
1294

    
1295
    sc->duration = FFMAX(pkt->pts + pkt->duration, sc->duration);
1296

    
1297
    put_flush_packet(pb);
1298
    return 0;
1299
}
1300

    
1301
static void mxf_write_random_index_pack(AVFormatContext *s)
1302
{
1303
    MXFContext *mxf = s->priv_data;
1304
    ByteIOContext *pb = s->pb;
1305
    uint64_t pos = url_ftell(pb);
1306

    
1307
    put_buffer(pb, random_index_pack_key, 16);
1308
    klv_encode_ber_length(pb, 28);
1309

    
1310
    put_be32(pb, 1); // BodySID of header partition
1311
    put_be64(pb, 0); // offset of header partition
1312

    
1313
    put_be32(pb, 0); // BodySID of footer partition
1314
    put_be64(pb, mxf->footer_partition_offset);
1315

    
1316
    put_be32(pb, url_ftell(pb) - pos + 4);
1317
}
1318

    
1319
static int mxf_write_footer(AVFormatContext *s)
1320
{
1321
    MXFContext *mxf = s->priv_data;
1322
    ByteIOContext *pb = s->pb;
1323
    unsigned index_byte_count =
1324
        109 + s->nb_streams*6 +
1325
        mxf->edit_units_count*(11+(s->nb_streams-1)*4);
1326

    
1327
    // add encoded ber length
1328
    index_byte_count += 16 + klv_ber_length(index_byte_count);
1329

    
1330
    mxf_write_klv_fill(s);
1331

    
1332
    mxf->footer_partition_offset = url_ftell(pb);
1333
    mxf_write_partition(s, 0, 2, index_byte_count, footer_partition_key, 0);
1334

    
1335
    mxf_write_index_table_segment(s);
1336

    
1337
    mxf_write_random_index_pack(s);
1338

    
1339
    if (!url_is_streamed(s->pb)) {
1340
        url_fseek(pb, 0, SEEK_SET);
1341
        mxf_write_partition(s, 1, 0, 0, header_closed_partition_key, 1);
1342
    }
1343

    
1344
    ff_audio_interleave_close(s);
1345

    
1346
    mxf_free(s);
1347
    return 0;
1348
}
1349

    
1350
static int mxf_interleave_new_audio_packet(AVFormatContext *s, AVPacket *pkt,
1351
                                           int stream_index, int flush)
1352
{
1353
    AVStream *st = s->streams[stream_index];
1354
    AudioInterleaveContext *aic = st->priv_data;
1355

    
1356
    int size = FFMIN(av_fifo_size(&aic->fifo), *aic->samples * aic->sample_size);
1357
    if (!size || (!flush && size == av_fifo_size(&aic->fifo)))
1358
        return 0;
1359

    
1360
    av_new_packet(pkt, size);
1361
    av_fifo_read(&aic->fifo, pkt->data, size);
1362

    
1363
    pkt->dts = pkt->pts = aic->dts;
1364
    pkt->duration = av_rescale_q(*aic->samples, st->time_base, aic->time_base);
1365
    pkt->stream_index = stream_index;
1366
    aic->dts += pkt->duration;
1367

    
1368
    aic->samples++;
1369
    if (!*aic->samples)
1370
        aic->samples = aic->samples_per_frame;
1371

    
1372
    return size;
1373
}
1374

    
1375
static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1376
{
1377
    AVPacketList *pktl;
1378
    int stream_count = 0;
1379
    int streams[MAX_STREAMS];
1380

    
1381
    memset(streams, 0, sizeof(streams));
1382
    pktl = s->packet_buffer;
1383
    while (pktl) {
1384
        //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
1385
        if (!streams[pktl->pkt.stream_index])
1386
            stream_count++;
1387
        streams[pktl->pkt.stream_index]++;
1388
        pktl = pktl->next;
1389
    }
1390

    
1391
    if (stream_count && (s->nb_streams == stream_count || flush)) {
1392
        pktl = s->packet_buffer;
1393
        if (s->nb_streams != stream_count) {
1394
            MXFContext *mxf = s->priv_data;
1395
            AVPacketList *first = NULL;
1396
            // find first packet in edit unit
1397
            while (pktl) {
1398
                AVStream *st = s->streams[pktl->pkt.stream_index];
1399
                if (st->index == mxf->edit_unit_start)
1400
                    break;
1401
                else if (!first)
1402
                    first = pktl;
1403
                pktl = pktl->next;
1404
            }
1405
            // purge packet queue
1406
            while (pktl) {
1407
                AVPacketList *next = pktl->next;
1408
                av_free_packet(&pktl->pkt);
1409
                av_freep(&pktl);
1410
                pktl = next;
1411
            }
1412
            if (!first)
1413
                goto out;
1414
            pktl = first;
1415
        }
1416

    
1417
        *out = pktl->pkt;
1418
        //av_log(s, AV_LOG_DEBUG, "out st:%d dts:%lld\n", (*out).stream_index, (*out).dts);
1419
        s->packet_buffer = pktl->next;
1420
        av_freep(&pktl);
1421
        return 1;
1422
    } else {
1423
    out:
1424
        av_init_packet(out);
1425
        return 0;
1426
    }
1427
}
1428

    
1429
static int mxf_compare_timestamps(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
1430
{
1431
    MXFStreamContext *sc  = s->streams[pkt ->stream_index]->priv_data;
1432
    MXFStreamContext *sc2 = s->streams[next->stream_index]->priv_data;
1433

    
1434
    return next->dts > pkt->dts ||
1435
        (next->dts == pkt->dts && sc->order < sc2->order);
1436
}
1437

    
1438
static int mxf_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1439
{
1440
    int i;
1441

    
1442
    if (pkt) {
1443
        AVStream *st = s->streams[pkt->stream_index];
1444
        AudioInterleaveContext *aic = st->priv_data;
1445
        if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1446
            av_fifo_generic_write(&aic->fifo, pkt->data, pkt->size, NULL);
1447
        } else {
1448
            // rewrite pts and dts to be decoded time line position
1449
            pkt->pts = pkt->dts = aic->dts;
1450
            aic->dts += pkt->duration;
1451
            ff_interleave_add_packet(s, pkt, mxf_compare_timestamps);
1452
        }
1453
        pkt = NULL;
1454
    }
1455

    
1456
    for (i = 0; i < s->nb_streams; i++) {
1457
        AVStream *st = s->streams[i];
1458
        if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1459
            AVPacket new_pkt;
1460
            while (mxf_interleave_new_audio_packet(s, &new_pkt, i, flush))
1461
                ff_interleave_add_packet(s, &new_pkt, mxf_compare_timestamps);
1462
        }
1463
    }
1464

    
1465
    return mxf_interleave_get_packet(s, out, pkt, flush);
1466
}
1467

    
1468
AVOutputFormat mxf_muxer = {
1469
    "mxf",
1470
    NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1471
    NULL,
1472
    "mxf",
1473
    sizeof(MXFContext),
1474
    CODEC_ID_PCM_S16LE,
1475
    CODEC_ID_MPEG2VIDEO,
1476
    mxf_write_header,
1477
    mxf_write_packet,
1478
    mxf_write_footer,
1479
    AVFMT_NOTIMESTAMPS,
1480
    NULL,
1481
    mxf_interleave,
1482
};