Statistics
| Branch: | Revision:

ffmpeg / libavformat / mxfenc.c @ a784cc67

History | View | Annotate | Download (54 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 "libavcodec/bytestream.h"
40
#include "audiointerleave.h"
41
#include "avformat.h"
42
#include "mxf.h"
43

    
44
static const int NTSC_samples_per_frame[] = { 1602, 1601, 1602, 1601, 1602, 0 };
45
static const int PAL_samples_per_frame[]  = { 1920, 0 };
46

    
47
#define MXF_INDEX_CLUSTER_SIZE 4096
48
#define KAG_SIZE 512
49

    
50
typedef struct {
51
    int local_tag;
52
    UID uid;
53
} MXFLocalTagPair;
54

    
55
typedef struct {
56
    uint8_t flags;
57
    uint64_t offset;
58
    unsigned slice_offset; ///< offset of audio slice
59
} MXFIndexEntry;
60

    
61
typedef struct {
62
    AudioInterleaveContext aic;
63
    UID track_essence_element_key;
64
    int index;            ///< index in mxf_essence_container_uls table
65
    const UID *codec_ul;
66
    int64_t duration;
67
    int order;            ///< interleaving order if dts are equal
68
    int interlaced;       ///< wether picture is interlaced
69
    int temporal_reordering;
70
} MXFStreamContext;
71

    
72
typedef struct {
73
    UID container_ul;
74
    UID element_ul;
75
    UID codec_ul;
76
    void (*write_desc)();
77
} MXFContainerEssenceEntry;
78

    
79
static const struct {
80
    enum CodecID id;
81
    int index;
82
} mxf_essence_mappings[] = {
83
    { CODEC_ID_MPEG2VIDEO, 0 },
84
    { CODEC_ID_PCM_S24LE,  1 },
85
    { CODEC_ID_PCM_S16LE,  1 },
86
    { 0 }
87
};
88

    
89
static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st);
90
static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st);
91
static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st);
92

    
93
static const MXFContainerEssenceEntry mxf_essence_container_uls[] = {
94
    { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x02,0x0D,0x01,0x03,0x01,0x02,0x04,0x60,0x01 },
95
      { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x15,0x01,0x05,0x00 },
96
      { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x00,0x00,0x00 },
97
      mxf_write_mpegvideo_desc },
98
    { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x03,0x00 },
99
      { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x03,0x00 },
100
      { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
101
      mxf_write_aes3_desc },
102
    { { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x03,0x01,0x02,0x06,0x01,0x00 },
103
      { 0x06,0x0E,0x2B,0x34,0x01,0x02,0x01,0x01,0x0D,0x01,0x03,0x01,0x16,0x01,0x01,0x00 },
104
      { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x04,0x02,0x02,0x01,0x00,0x00,0x00,0x00 },
105
      mxf_write_wav_desc },
106
    { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
107
      { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
108
      { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
109
      NULL },
110
};
111

    
112
typedef struct MXFContext {
113
    int64_t footer_partition_offset;
114
    int essence_container_count;
115
    uint8_t essence_containers_indices[FF_ARRAY_ELEMS(mxf_essence_container_uls)];
116
    AVRational time_base;
117
    int header_written;
118
    MXFIndexEntry *index_entries;
119
    unsigned edit_units_count;
120
    uint64_t timestamp;   ///< timestamp, as year(16),month(8),day(8),hour(8),minutes(8),msec/4(8)
121
    uint8_t slice_count;  ///< index slice count minus 1 (1 if no audio, 0 otherwise)
122
} MXFContext;
123

    
124
static const uint8_t uuid_base[]            = { 0xAD,0xAB,0x44,0x24,0x2f,0x25,0x4d,0xc7,0x92,0xff,0x29,0xbd };
125
static const uint8_t umid_base[]            = { 0x06,0x0A,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x01,0x0D,0x00,0x13,0x00,0x00,0x00 };
126

    
127
/**
128
 * complete key for operation pattern, partitions, and primer pack
129
 */
130
static const uint8_t op1a_ul[]                     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x01,0x01,0x00 };
131
static const uint8_t footer_partition_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }; // ClosedComplete
132
static const uint8_t primer_pack_key[]             = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x05,0x01,0x00 };
133
static const uint8_t index_table_segment_key[]     = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 };
134
static const uint8_t random_index_pack_key[]       = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x02,0x01,0x01,0x11,0x01,0x00 };
135
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
136
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
137
static const uint8_t klv_fill_key[]                = { 0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x03,0x01,0x02,0x10,0x01,0x00,0x00,0x00 };
138

    
139
/**
140
 * partial key for header metadata
141
 */
142
static const uint8_t header_metadata_key[]  = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01 };
143
static const uint8_t multiple_desc_ul[]     = { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x0D,0x01,0x03,0x01,0x02,0x7F,0x01,0x00 };
144

    
145
/**
146
 * SMPTE RP210 http://www.smpte-ra.org/mdd/index.html
147
 */
148
static const MXFLocalTagPair mxf_local_tag_batch[] = {
149
    // preface set
150
    { 0x3C0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x02,0x00,0x00,0x00,0x00}}, /* Instance UID */
151
    { 0x3B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x04,0x00,0x00}}, /* Last Modified Date */
152
    { 0x3B05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x03,0x01,0x02,0x01,0x05,0x00,0x00,0x00}}, /* Version */
153
    { 0x3B06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x04,0x00,0x00}}, /* Identifications reference */
154
    { 0x3B03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x01,0x00,0x00}}, /* Content Storage reference */
155
    { 0x3B09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x03,0x00,0x00,0x00,0x00}}, /* Operational Pattern UL */
156
    { 0x3B0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x01,0x00,0x00}}, /* Essence Containers UL batch */
157
    { 0x3B0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x01,0x02,0x02,0x10,0x02,0x02,0x00,0x00}}, /* DM Schemes UL batch */
158
    // Identification
159
    { 0x3C09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x01,0x00,0x00,0x00}}, /* This Generation UID */
160
    { 0x3C01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x02,0x01,0x00,0x00}}, /* Company Name */
161
    { 0x3C02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x03,0x01,0x00,0x00}}, /* Product Name */
162
    { 0x3C04, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x05,0x01,0x00,0x00}}, /* Version String */
163
    { 0x3C05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x20,0x07,0x01,0x07,0x00,0x00,0x00}}, /* Product ID */
164
    { 0x3C06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x03,0x00,0x00}}, /* Modification Date */
165
    // Content Storage
166
    { 0x1901, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x01,0x00,0x00}}, /* Package strong reference batch */
167
    { 0x1902, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x05,0x02,0x00,0x00}}, /* Package strong reference batch */
168
    // Essence Container Data
169
    { 0x2701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x06,0x01,0x00,0x00,0x00}}, /* Linked Package UID */
170
    { 0x3F07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x04,0x00,0x00,0x00,0x00}}, /* BodySID */
171
    // Package
172
    { 0x4401, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x01,0x01,0x15,0x10,0x00,0x00,0x00,0x00}}, /* Package UID */
173
    { 0x4405, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x01,0x03,0x00,0x00}}, /* Package Creation Date */
174
    { 0x4404, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x10,0x02,0x05,0x00,0x00}}, /* Package Modified Date */
175
    { 0x4403, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x05,0x00,0x00}}, /* Tracks Strong reference array */
176
    { 0x4701, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x03,0x00,0x00}}, /* Descriptor */
177
    // Track
178
    { 0x4801, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x07,0x01,0x01,0x00,0x00,0x00,0x00}}, /* Track ID */
179
    { 0x4804, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x01,0x04,0x01,0x03,0x00,0x00,0x00,0x00}}, /* Track Number */
180
    { 0x4B01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x05,0x30,0x04,0x05,0x00,0x00,0x00,0x00}}, /* Edit Rate */
181
    { 0x4B02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x03,0x00,0x00}}, /* Origin */
182
    { 0x4803, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x02,0x04,0x00,0x00}}, /* Sequence reference */
183
    // Sequence
184
    { 0x0201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x07,0x01,0x00,0x00,0x00,0x00,0x00}}, /* Data Definition UL */
185
    { 0x0202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x02,0x01,0x01,0x03,0x00,0x00}}, /* Duration */
186
    { 0x1001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x06,0x09,0x00,0x00}}, /* Structural Components reference array */
187
    // Source Clip
188
    { 0x1201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x07,0x02,0x01,0x03,0x01,0x04,0x00,0x00}}, /* Start position */
189
    { 0x1101, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x01,0x00,0x00,0x00}}, /* SourcePackageID */
190
    { 0x1102, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x03,0x02,0x00,0x00,0x00}}, /* SourceTrackID */
191
    // File Descriptor
192
    { 0x3F01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x04,0x06,0x0B,0x00,0x00}}, /* Sub Descriptors reference array */
193
    { 0x3006, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x06,0x01,0x01,0x03,0x05,0x00,0x00,0x00}}, /* Linked Track ID */
194
    { 0x3001, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x06,0x01,0x01,0x00,0x00,0x00,0x00}}, /* SampleRate */
195
    { 0x3004, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x06,0x01,0x01,0x04,0x01,0x02,0x00,0x00}}, /* Essence Container */
196
    // Generic Picture Essence Descriptor
197
    { 0x320C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Frame Layout */
198
    { 0x320D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x03,0x02,0x05,0x00,0x00,0x00}}, /* Video Line Map */
199
    { 0x3203, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x02,0x00,0x00,0x00}}, /* Stored Width */
200
    { 0x3202, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x02,0x01,0x00,0x00,0x00}}, /* Stored Height */
201
    { 0x3209, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0C,0x00,0x00,0x00}}, /* Display Width */
202
    { 0x3208, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x0B,0x00,0x00,0x00}}, /* Display Height */
203
    { 0x320E, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x01,0x01,0x01,0x00,0x00,0x00}}, /* Aspect Ratio */
204
    { 0x3201, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x06,0x01,0x00,0x00,0x00,0x00}}, /* Picture Essence Coding */
205
    // CDCI Picture Essence Descriptor
206
    { 0x3301, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x01,0x05,0x03,0x0A,0x00,0x00,0x00}}, /* Component Depth */
207
    { 0x3302, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x01,0x04,0x01,0x05,0x01,0x05,0x00,0x00,0x00}}, /* Horizontal Subsampling */
208
    // Generic Sound Essence Descriptor
209
    { 0x3D02, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x01,0x04,0x00,0x00,0x00}}, /* Locked/Unlocked */
210
    { 0x3D03, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x01,0x01,0x01,0x00,0x00}}, /* Audio sampling rate */
211
    { 0x3D07, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x01,0x01,0x04,0x00,0x00,0x00}}, /* ChannelCount */
212
    { 0x3D01, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x02,0x03,0x03,0x04,0x00,0x00,0x00}}, /* Quantization bits */
213
    { 0x3D06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x02,0x04,0x02,0x04,0x02,0x00,0x00,0x00,0x00}}, /* Sound Essence Compression */
214
    // Index Table Segment
215
    { 0x3F0B, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x05,0x30,0x04,0x06,0x00,0x00,0x00,0x00}}, /* Index Edit Rate */
216
    { 0x3F0C, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x01,0x03,0x01,0x0A,0x00,0x00}}, /* Index Start Position */
217
    { 0x3F0D, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x07,0x02,0x02,0x01,0x01,0x02,0x00,0x00}}, /* Index Duration */
218
    { 0x3F05, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x06,0x02,0x01,0x00,0x00,0x00,0x00}}, /* Edit Unit Byte Count */
219
    { 0x3F06, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x01,0x03,0x04,0x05,0x00,0x00,0x00,0x00}}, /* IndexSID */
220
    { 0x3F08, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x04,0x04,0x04,0x04,0x01,0x01,0x00,0x00,0x00}}, /* Slice Count */
221
    { 0x3F09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x01,0x06,0x00,0x00,0x00}}, /* Delta Entry Array */
222
    { 0x3F0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x04,0x04,0x02,0x05,0x00,0x00,0x00}}, /* Index Entry Array */
223
    // MPEG video Descriptor
224
    { 0x8000, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x01,0x06,0x02,0x01,0x0B,0x00,0x00}}, /* BitRate */
225
    // Wave Audio Essence Descriptor
226
    { 0x3D09, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x03,0x05,0x00,0x00,0x00}}, /* Average Bytes Per Second */
227
    { 0x3D0A, {0x06,0x0E,0x2B,0x34,0x01,0x01,0x01,0x05,0x04,0x02,0x03,0x02,0x01,0x00,0x00,0x00}}, /* Block Align */
228
};
229

    
230
static void mxf_write_uuid(ByteIOContext *pb, enum MXFMetadataSetType type, int value)
231
{
232
    put_buffer(pb, uuid_base, 12);
233
    put_be16(pb, type);
234
    put_be16(pb, value);
235
}
236

    
237
static void mxf_write_umid(ByteIOContext *pb, enum MXFMetadataSetType type, int value)
238
{
239
    put_buffer(pb, umid_base, 16);
240
    mxf_write_uuid(pb, type, value);
241
}
242

    
243
static void mxf_write_refs_count(ByteIOContext *pb, int ref_count)
244
{
245
    put_be32(pb, ref_count);
246
    put_be32(pb, 16);
247
}
248

    
249
static int klv_ber_length(uint64_t len)
250
{
251
    if (len < 128)
252
        return 1;
253
    else
254
        return (av_log2(len) >> 3) + 2;
255
}
256

    
257
static int klv_encode_ber_length(ByteIOContext *pb, uint64_t len)
258
{
259
    // Determine the best BER size
260
    int size;
261
    if (len < 128) {
262
        //short form
263
        put_byte(pb, len);
264
        return 1;
265
    }
266

    
267
    size = (av_log2(len) >> 3) + 1;
268

    
269
    // long form
270
    put_byte(pb, 0x80 + size);
271
    while(size) {
272
        size--;
273
        put_byte(pb, len >> 8 * size & 0xff);
274
    }
275
    return 0;
276
}
277

    
278
/*
279
 * Get essence container ul index
280
 */
281
static int mxf_get_essence_container_ul_index(enum CodecID id)
282
{
283
    int i;
284
    for (i = 0; mxf_essence_mappings[i].id; i++)
285
        if (mxf_essence_mappings[i].id == id)
286
            return mxf_essence_mappings[i].index;
287
    return -1;
288
}
289

    
290
static void mxf_write_primer_pack(AVFormatContext *s)
291
{
292
    ByteIOContext *pb = s->pb;
293
    int local_tag_number, i = 0;
294

    
295
    local_tag_number = FF_ARRAY_ELEMS(mxf_local_tag_batch);
296

    
297
    put_buffer(pb, primer_pack_key, 16);
298
    klv_encode_ber_length(pb, local_tag_number * 18 + 8);
299

    
300
    put_be32(pb, local_tag_number); // local_tag num
301
    put_be32(pb, 18); // item size, always 18 according to the specs
302

    
303
    for (i = 0; i < local_tag_number; i++) {
304
        put_be16(pb, mxf_local_tag_batch[i].local_tag);
305
        put_buffer(pb, mxf_local_tag_batch[i].uid, 16);
306
    }
307
}
308

    
309
static void mxf_write_local_tag(ByteIOContext *pb, int size, int tag)
310
{
311
    put_be16(pb, tag);
312
    put_be16(pb, size);
313
}
314

    
315
static void mxf_write_metadata_key(ByteIOContext *pb, unsigned int value)
316
{
317
    put_buffer(pb, header_metadata_key, 13);
318
    put_be24(pb, value);
319
}
320

    
321
static void mxf_free(AVFormatContext *s)
322
{
323
    int i;
324

    
325
    for (i = 0; i < s->nb_streams; i++) {
326
        AVStream *st = s->streams[i];
327
        av_freep(&st->priv_data);
328
    }
329
}
330

    
331
static const MXFCodecUL *mxf_get_data_definition_ul(int type)
332
{
333
    const MXFCodecUL *uls = ff_mxf_data_definition_uls;
334
    while (uls->uid[0]) {
335
        if (type == uls->id)
336
            break;
337
        uls++;
338
    }
339
    return uls;
340
}
341

    
342
static void mxf_write_essence_container_refs(AVFormatContext *s)
343
{
344
    MXFContext *c = s->priv_data;
345
    ByteIOContext *pb = s->pb;
346
    int i;
347

    
348
    mxf_write_refs_count(pb, c->essence_container_count);
349
    av_log(s,AV_LOG_DEBUG, "essence container count:%d\n", c->essence_container_count);
350
    for (i = 0; i < c->essence_container_count; i++) {
351
        put_buffer(pb, mxf_essence_container_uls[c->essence_containers_indices[i]].container_ul, 16);
352
        PRINT_KEY(s, "essence container ul:\n", mxf_essence_container_uls[c->essence_containers_indices[i]].container_ul);
353
    }
354
}
355

    
356
static void mxf_write_preface(AVFormatContext *s)
357
{
358
    MXFContext *mxf = s->priv_data;
359
    ByteIOContext *pb = s->pb;
360

    
361
    mxf_write_metadata_key(pb, 0x012f00);
362
    PRINT_KEY(s, "preface key", pb->buf_ptr - 16);
363
    klv_encode_ber_length(pb, 130 + 16 * mxf->essence_container_count);
364

    
365
    // write preface set uid
366
    mxf_write_local_tag(pb, 16, 0x3C0A);
367
    mxf_write_uuid(pb, Preface, 0);
368
    PRINT_KEY(s, "preface uid", pb->buf_ptr - 16);
369

    
370
    // last modified date
371
    mxf_write_local_tag(pb, 8, 0x3B02);
372
    put_be64(pb, mxf->timestamp);
373

    
374
    // write version
375
    mxf_write_local_tag(pb, 2, 0x3B05);
376
    put_be16(pb, 1);
377

    
378
    // write identification_refs
379
    mxf_write_local_tag(pb, 16 + 8, 0x3B06);
380
    mxf_write_refs_count(pb, 1);
381
    mxf_write_uuid(pb, Identification, 0);
382

    
383
    // write content_storage_refs
384
    mxf_write_local_tag(pb, 16, 0x3B03);
385
    mxf_write_uuid(pb, ContentStorage, 0);
386

    
387
    // operational pattern
388
    mxf_write_local_tag(pb, 16, 0x3B09);
389
    if (s->nb_streams > 1) {
390
        put_buffer(pb, op1a_ul, 14);
391
        put_be16(pb, 0x0900); // multi track
392
    } else {
393
        put_buffer(pb, op1a_ul, 16);
394
    }
395

    
396
    // write essence_container_refs
397
    mxf_write_local_tag(pb, 8 + 16 * mxf->essence_container_count, 0x3B0A);
398
    mxf_write_essence_container_refs(s);
399

    
400
    // write dm_scheme_refs
401
    mxf_write_local_tag(pb, 8, 0x3B0B);
402
    put_be64(pb, 0);
403
}
404

    
405
/*
406
 * Write a local tag containing an ascii string as utf-16
407
 */
408
static void mxf_write_local_tag_utf16(ByteIOContext *pb, int tag, const char *value)
409
{
410
    int i, size = strlen(value);
411
    mxf_write_local_tag(pb, size*2, tag);
412
    for (i = 0; i < size; i++)
413
        put_be16(pb, value[i]);
414
}
415

    
416
static void mxf_write_identification(AVFormatContext *s)
417
{
418
    MXFContext *mxf = s->priv_data;
419
    ByteIOContext *pb = s->pb;
420
    const char *company = "FFmpeg";
421
    const char *product = "OP1a Muxer";
422
    const char *version;
423
    int length;
424

    
425
    mxf_write_metadata_key(pb, 0x013000);
426
    PRINT_KEY(s, "identification key", pb->buf_ptr - 16);
427

    
428
    version = s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT ?
429
        "0.0.0" : AV_STRINGIFY(LIBAVFORMAT_VERSION);
430
    length = 84 + (strlen(company)+strlen(product)+strlen(version))*2; // utf-16
431
    klv_encode_ber_length(pb, length);
432

    
433
    // write uid
434
    mxf_write_local_tag(pb, 16, 0x3C0A);
435
    mxf_write_uuid(pb, Identification, 0);
436
    PRINT_KEY(s, "identification uid", pb->buf_ptr - 16);
437

    
438
    // write generation uid
439
    mxf_write_local_tag(pb, 16, 0x3C09);
440
    mxf_write_uuid(pb, Identification, 1);
441

    
442
    mxf_write_local_tag_utf16(pb, 0x3C01, company); // Company Name
443
    mxf_write_local_tag_utf16(pb, 0x3C02, product); // Product Name
444
    mxf_write_local_tag_utf16(pb, 0x3C04, version); // Version String
445

    
446
    // write product uid
447
    mxf_write_local_tag(pb, 16, 0x3C05);
448
    mxf_write_uuid(pb, Identification, 2);
449

    
450
    // modification date
451
    mxf_write_local_tag(pb, 8, 0x3C06);
452
    put_be64(pb, mxf->timestamp);
453
}
454

    
455
static void mxf_write_content_storage(AVFormatContext *s)
456
{
457
    ByteIOContext *pb = s->pb;
458

    
459
    mxf_write_metadata_key(pb, 0x011800);
460
    PRINT_KEY(s, "content storage key", pb->buf_ptr - 16);
461
    klv_encode_ber_length(pb, 92);
462

    
463
    // write uid
464
    mxf_write_local_tag(pb, 16, 0x3C0A);
465
    mxf_write_uuid(pb, ContentStorage, 0);
466
    PRINT_KEY(s, "content storage uid", pb->buf_ptr - 16);
467

    
468
    // write package reference
469
    mxf_write_local_tag(pb, 16 * 2 + 8, 0x1901);
470
    mxf_write_refs_count(pb, 2);
471
    mxf_write_uuid(pb, MaterialPackage, 0);
472
    mxf_write_uuid(pb, SourcePackage, 0);
473

    
474
    // write essence container data
475
    mxf_write_local_tag(pb, 8 + 16, 0x1902);
476
    mxf_write_refs_count(pb, 1);
477
    mxf_write_uuid(pb, EssenceContainerData, 0);
478
}
479

    
480
static void mxf_write_track(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
481
{
482
    MXFContext *mxf = s->priv_data;
483
    ByteIOContext *pb = s->pb;
484
    MXFStreamContext *sc = st->priv_data;
485

    
486
    mxf_write_metadata_key(pb, 0x013b00);
487
    PRINT_KEY(s, "track key", pb->buf_ptr - 16);
488
    klv_encode_ber_length(pb, 80);
489

    
490
    // write track uid
491
    mxf_write_local_tag(pb, 16, 0x3C0A);
492
    mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, st->index);
493
    PRINT_KEY(s, "track uid", pb->buf_ptr - 16);
494

    
495
    // write track id
496
    mxf_write_local_tag(pb, 4, 0x4801);
497
    put_be32(pb, st->index);
498

    
499
    // write track number
500
    mxf_write_local_tag(pb, 4, 0x4804);
501
    if (type == MaterialPackage)
502
        put_be32(pb, 0); // track number of material package is 0
503
    else
504
        put_buffer(pb, sc->track_essence_element_key + 12, 4);
505

    
506
    mxf_write_local_tag(pb, 8, 0x4B01);
507
    put_be32(pb, mxf->time_base.den);
508
    put_be32(pb, mxf->time_base.num);
509

    
510
    // write origin
511
    mxf_write_local_tag(pb, 8, 0x4B02);
512
    put_be64(pb, 0);
513

    
514
    // write sequence refs
515
    mxf_write_local_tag(pb, 16, 0x4803);
516
    mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
517
}
518

    
519
static void mxf_write_common_fields(ByteIOContext *pb, AVStream *st)
520
{
521
    const MXFCodecUL *data_def_ul = mxf_get_data_definition_ul(st->codec->codec_type);
522
    MXFStreamContext *sc = st->priv_data;
523

    
524
    // find data define uls
525
    mxf_write_local_tag(pb, 16, 0x0201);
526
    put_buffer(pb, data_def_ul->uid, 16);
527

    
528
    // write duration
529
    mxf_write_local_tag(pb, 8, 0x0202);
530
    put_be64(pb, sc->duration);
531
}
532

    
533
static void mxf_write_sequence(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
534
{
535
    ByteIOContext *pb = s->pb;
536

    
537
    mxf_write_metadata_key(pb, 0x010f00);
538
    PRINT_KEY(s, "sequence key", pb->buf_ptr - 16);
539
    klv_encode_ber_length(pb, 80);
540

    
541
    mxf_write_local_tag(pb, 16, 0x3C0A);
542
    mxf_write_uuid(pb, type == MaterialPackage ? Sequence: Sequence + TypeBottom, st->index);
543

    
544
    PRINT_KEY(s, "sequence uid", pb->buf_ptr - 16);
545
    mxf_write_common_fields(pb, st);
546

    
547
    // write structural component
548
    mxf_write_local_tag(pb, 16 + 8, 0x1001);
549
    mxf_write_refs_count(pb, 1);
550
    mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
551
}
552

    
553
static void mxf_write_structural_component(AVFormatContext *s, AVStream *st, enum MXFMetadataSetType type)
554
{
555
    ByteIOContext *pb = s->pb;
556
    int i;
557

    
558
    mxf_write_metadata_key(pb, 0x011100);
559
    PRINT_KEY(s, "sturctural component key", pb->buf_ptr - 16);
560
    klv_encode_ber_length(pb, 108);
561

    
562
    // write uid
563
    mxf_write_local_tag(pb, 16, 0x3C0A);
564
    mxf_write_uuid(pb, type == MaterialPackage ? SourceClip: SourceClip + TypeBottom, st->index);
565

    
566
    PRINT_KEY(s, "structural component uid", pb->buf_ptr - 16);
567
    mxf_write_common_fields(pb, st);
568

    
569
    // write start_position
570
    mxf_write_local_tag(pb, 8, 0x1201);
571
    put_be64(pb, 0);
572

    
573
    // write source package uid, end of the reference
574
    mxf_write_local_tag(pb, 32, 0x1101);
575
    if (type == SourcePackage) {
576
        for (i = 0; i < 4; i++)
577
            put_be64(pb, 0);
578
    } else
579
        mxf_write_umid(pb, SourcePackage, 0);
580

    
581
    // write source track id
582
    mxf_write_local_tag(pb, 4, 0x1102);
583
    if (type == SourcePackage)
584
        put_be32(pb, 0);
585
    else
586
        put_be32(pb, st->index);
587
}
588

    
589
static void mxf_write_multi_descriptor(AVFormatContext *s)
590
{
591
    MXFContext *mxf = s->priv_data;
592
    ByteIOContext *pb = s->pb;
593
    int i;
594

    
595
    mxf_write_metadata_key(pb, 0x014400);
596
    PRINT_KEY(s, "multiple descriptor key", pb->buf_ptr - 16);
597
    klv_encode_ber_length(pb, 64 + 16 * s->nb_streams);
598

    
599
    mxf_write_local_tag(pb, 16, 0x3C0A);
600
    mxf_write_uuid(pb, MultipleDescriptor, 0);
601
    PRINT_KEY(s, "multi_desc uid", pb->buf_ptr - 16);
602

    
603
    // write sample rate
604
    mxf_write_local_tag(pb, 8, 0x3001);
605
    put_be32(pb, mxf->time_base.den);
606
    put_be32(pb, mxf->time_base.num);
607

    
608
    // write essence container ul
609
    mxf_write_local_tag(pb, 16, 0x3004);
610
    put_buffer(pb, multiple_desc_ul, 16);
611

    
612
    // write sub descriptor refs
613
    mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x3F01);
614
    mxf_write_refs_count(pb, s->nb_streams);
615
    for (i = 0; i < s->nb_streams; i++)
616
        mxf_write_uuid(pb, SubDescriptor, i);
617
}
618

    
619
static void mxf_write_generic_desc(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
620
{
621
    MXFContext *mxf = s->priv_data;
622
    MXFStreamContext *sc = st->priv_data;
623
    ByteIOContext *pb = s->pb;
624

    
625
    put_buffer(pb, key, 16);
626
    klv_encode_ber_length(pb, size);
627

    
628
    mxf_write_local_tag(pb, 16, 0x3C0A);
629
    mxf_write_uuid(pb, SubDescriptor, st->index);
630

    
631
    mxf_write_local_tag(pb, 4, 0x3006);
632
    put_be32(pb, st->index);
633

    
634
    mxf_write_local_tag(pb, 8, 0x3001);
635
    put_be32(pb, mxf->time_base.den);
636
    put_be32(pb, mxf->time_base.num);
637

    
638
    mxf_write_local_tag(pb, 16, 0x3004);
639
    put_buffer(pb, mxf_essence_container_uls[sc->index].container_ul, 16);
640
}
641

    
642
static const UID mxf_mpegvideo_descriptor_key = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 };
643
static const UID mxf_wav_descriptor_key       = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 };
644
static const UID mxf_aes3_descriptor_key      = { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 };
645

    
646
static void mxf_write_mpegvideo_desc(AVFormatContext *s, AVStream *st)
647
{
648
    MXFStreamContext *sc = st->priv_data;
649
    ByteIOContext *pb = s->pb;
650
    int stored_height = (st->codec->height+15)/16*16;
651
    AVRational dar;
652
    int f1, f2;
653

    
654
    mxf_write_generic_desc(s, st, mxf_mpegvideo_descriptor_key, 169+sc->interlaced*4);
655

    
656
    mxf_write_local_tag(pb, 4, 0x3203);
657
    put_be32(pb, st->codec->width);
658

    
659
    mxf_write_local_tag(pb, 4, 0x3202);
660
    put_be32(pb, stored_height>>sc->interlaced);
661

    
662
    mxf_write_local_tag(pb, 4, 0x3209);
663
    put_be32(pb, st->codec->width);
664

    
665
    mxf_write_local_tag(pb, 4, 0x3208);
666
    put_be32(pb, st->codec->height>>sc->interlaced);
667

    
668
    // component depth
669
    mxf_write_local_tag(pb, 4, 0x3301);
670
    put_be32(pb, 8);
671

    
672
    // horizontal subsampling
673
    mxf_write_local_tag(pb, 4, 0x3302);
674
    put_be32(pb, 2);
675

    
676
    // bit rate
677
    mxf_write_local_tag(pb, 4, 0x8000);
678
    put_be32(pb, st->codec->bit_rate);
679

    
680
    // frame layout
681
    mxf_write_local_tag(pb, 1, 0x320C);
682
    put_byte(pb, sc->interlaced);
683

    
684
    // video line map
685
    switch (st->codec->height) {
686
    case  576: f1 = 23; f2 = 336; break;
687
    case  608: f1 =  7; f2 = 320; break;
688
    case  480: f1 = 20; f2 = 283; break;
689
    case  512: f1 =  7; f2 = 270; break;
690
    case  720: f1 = 26; f2 =   0; break; // progressive
691
    case 1080: f1 = 21; f2 = 584; break;
692
    default:   f1 =  0; f2 =   0; break;
693
    }
694

    
695
    if (!sc->interlaced) {
696
        f2  = 0;
697
        f1 *= 2;
698
    }
699

    
700
    mxf_write_local_tag(pb, 12+sc->interlaced*4, 0x320D);
701
    put_be32(pb, sc->interlaced ? 2 : 1);
702
    put_be32(pb, 4);
703
    put_be32(pb, f1);
704
    if (sc->interlaced)
705
        put_be32(pb, f2);
706

    
707
    av_reduce(&dar.num, &dar.den,
708
              st->codec->width*st->codec->sample_aspect_ratio.num,
709
              st->codec->height*st->codec->sample_aspect_ratio.den,
710
              1024*1024);
711

    
712
    mxf_write_local_tag(pb, 8, 0x320E);
713
    put_be32(pb, dar.num);
714
    put_be32(pb, dar.den);
715

    
716
    mxf_write_local_tag(pb, 16, 0x3201);
717
    put_buffer(pb, *sc->codec_ul, 16);
718
}
719

    
720
static void mxf_write_generic_sound_desc(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
721
{
722
    ByteIOContext *pb = s->pb;
723

    
724
    mxf_write_generic_desc(s, st, key, size);
725

    
726
    // audio locked
727
    mxf_write_local_tag(pb, 1, 0x3D02);
728
    put_byte(pb, 1);
729

    
730
    // write audio sampling rate
731
    mxf_write_local_tag(pb, 8, 0x3D03);
732
    put_be32(pb, st->codec->sample_rate);
733
    put_be32(pb, 1);
734

    
735
    mxf_write_local_tag(pb, 4, 0x3D07);
736
    put_be32(pb, st->codec->channels);
737

    
738
    mxf_write_local_tag(pb, 4, 0x3D01);
739
    put_be32(pb, av_get_bits_per_sample(st->codec->codec_id));
740
}
741

    
742
static void mxf_write_wav_common_desc(AVFormatContext *s, AVStream *st, const UID key, unsigned size)
743
{
744
    ByteIOContext *pb = s->pb;
745

    
746
    mxf_write_generic_sound_desc(s, st, key, size);
747

    
748
    mxf_write_local_tag(pb, 2, 0x3D0A);
749
    put_be16(pb, st->codec->block_align);
750

    
751
    // avg bytes per sec
752
    mxf_write_local_tag(pb, 4, 0x3D09);
753
    put_be32(pb, st->codec->block_align*st->codec->sample_rate);
754
}
755

    
756
static void mxf_write_wav_desc(AVFormatContext *s, AVStream *st)
757
{
758
    mxf_write_wav_common_desc(s, st, mxf_wav_descriptor_key, 107);
759
}
760

    
761
static void mxf_write_aes3_desc(AVFormatContext *s, AVStream *st)
762
{
763
    mxf_write_wav_common_desc(s, st, mxf_aes3_descriptor_key, 107);
764
}
765

    
766
static void mxf_write_package(AVFormatContext *s, enum MXFMetadataSetType type)
767
{
768
    MXFContext *mxf = s->priv_data;
769
    ByteIOContext *pb = s->pb;
770
    int i;
771

    
772
    if (type == MaterialPackage) {
773
        mxf_write_metadata_key(pb, 0x013600);
774
        PRINT_KEY(s, "Material Package key", pb->buf_ptr - 16);
775
        klv_encode_ber_length(pb, 92 + 16 * s->nb_streams);
776
    } else {
777
        mxf_write_metadata_key(pb, 0x013700);
778
        PRINT_KEY(s, "Source Package key", pb->buf_ptr - 16);
779
        klv_encode_ber_length(pb, 112 + 16 * s->nb_streams); // 20 bytes length for descriptor reference
780
    }
781

    
782
    // write uid
783
    mxf_write_local_tag(pb, 16, 0x3C0A);
784
    mxf_write_uuid(pb, type, 0);
785
    av_log(s,AV_LOG_DEBUG, "package type:%d\n", type);
786
    PRINT_KEY(s, "package uid", pb->buf_ptr - 16);
787

    
788
    // write package umid
789
    mxf_write_local_tag(pb, 32, 0x4401);
790
    mxf_write_umid(pb, type, 0);
791
    PRINT_KEY(s, "package umid second part", pb->buf_ptr - 16);
792

    
793
    // package creation date
794
    mxf_write_local_tag(pb, 8, 0x4405);
795
    put_be64(pb, mxf->timestamp);
796

    
797
    // package modified date
798
    mxf_write_local_tag(pb, 8, 0x4404);
799
    put_be64(pb, mxf->timestamp);
800

    
801
    // write track refs
802
    mxf_write_local_tag(pb, s->nb_streams * 16 + 8, 0x4403);
803
    mxf_write_refs_count(pb, s->nb_streams);
804
    for (i = 0; i < s->nb_streams; i++)
805
        mxf_write_uuid(pb, type == MaterialPackage ? Track : Track + TypeBottom, i);
806

    
807
    // write multiple descriptor reference
808
    if (type == SourcePackage) {
809
        mxf_write_local_tag(pb, 16, 0x4701);
810
        if (s->nb_streams > 1) {
811
            mxf_write_uuid(pb, MultipleDescriptor, 0);
812
            mxf_write_multi_descriptor(s);
813
        } else
814
            mxf_write_uuid(pb, SubDescriptor, 0);
815
    }
816

    
817
    for (i = 0; i < s->nb_streams; i++) {
818
        AVStream *st = s->streams[i];
819
        mxf_write_track(s, st, type);
820
        mxf_write_sequence(s, st, type);
821
        mxf_write_structural_component(s, st, type);
822

    
823
        if (type == SourcePackage) {
824
            MXFStreamContext *sc = st->priv_data;
825
            mxf_essence_container_uls[sc->index].write_desc(s, st);
826
        }
827
    }
828
}
829

    
830
static int mxf_write_essence_container_data(AVFormatContext *s)
831
{
832
    ByteIOContext *pb = s->pb;
833

    
834
    mxf_write_metadata_key(pb, 0x012300);
835
    klv_encode_ber_length(pb, 72);
836

    
837
    mxf_write_local_tag(pb, 16, 0x3C0A); // Instance UID
838
    mxf_write_uuid(pb, EssenceContainerData, 0);
839

    
840
    mxf_write_local_tag(pb, 32, 0x2701); // Linked Package UID
841
    mxf_write_umid(pb, SourcePackage, 0);
842

    
843
    mxf_write_local_tag(pb, 4, 0x3F07); // BodySID
844
    put_be32(pb, 1);
845

    
846
    mxf_write_local_tag(pb, 4, 0x3F06); // IndexSID
847
    put_be32(pb, 2);
848

    
849
    return 0;
850
}
851

    
852
static int mxf_write_header_metadata_sets(AVFormatContext *s)
853
{
854
    mxf_write_preface(s);
855
    mxf_write_identification(s);
856
    mxf_write_content_storage(s);
857
    mxf_write_package(s, MaterialPackage);
858
    mxf_write_package(s, SourcePackage);
859
    mxf_write_essence_container_data(s);
860
    return 0;
861
}
862

    
863
static unsigned klv_fill_size(uint64_t size)
864
{
865
    unsigned pad = KAG_SIZE - (size & (KAG_SIZE-1));
866
    if (pad < 17) // smallest fill item possible
867
        return pad + KAG_SIZE;
868
    else
869
        return pad & (KAG_SIZE-1);
870
}
871

    
872
static void mxf_write_index_table_segment(AVFormatContext *s)
873
{
874
    MXFContext *mxf = s->priv_data;
875
    ByteIOContext *pb = s->pb;
876
    int i, j;
877
    int temporal_reordering = 0;
878
    int last_key_index = 0, key_index = 0;
879

    
880
    av_log(s, AV_LOG_DEBUG, "edit units count %d\n", mxf->edit_units_count);
881

    
882
    put_buffer(pb, index_table_segment_key, 16);
883
    klv_encode_ber_length(pb, 109 + (s->nb_streams+1)*6 +
884
                          mxf->edit_units_count*(11+mxf->slice_count*4));
885

    
886
    // instance id
887
    mxf_write_local_tag(pb, 16, 0x3C0A);
888
    mxf_write_uuid(pb, IndexTableSegment, 0);
889

    
890
    // index edit rate
891
    mxf_write_local_tag(pb, 8, 0x3F0B);
892
    put_be32(pb, mxf->time_base.num);
893
    put_be32(pb, mxf->time_base.den);
894

    
895
    // index start position
896
    mxf_write_local_tag(pb, 8, 0x3F0C);
897
    put_be64(pb, 0);
898

    
899
    // index duration
900
    mxf_write_local_tag(pb, 8, 0x3F0D);
901
    put_be64(pb, mxf->edit_units_count);
902

    
903
    // edit unit byte count
904
    mxf_write_local_tag(pb, 4, 0x3F05);
905
    put_be32(pb, 0);
906

    
907
    // index sid
908
    mxf_write_local_tag(pb, 4, 0x3F06);
909
    put_be32(pb, 2);
910

    
911
    // body sid
912
    mxf_write_local_tag(pb, 4, 0x3F07);
913
    put_be32(pb, 1);
914

    
915
    // real slice count - 1
916
    mxf_write_local_tag(pb, 1, 0x3F08);
917
    put_byte(pb, mxf->slice_count);
918

    
919
    // delta entry array
920
    mxf_write_local_tag(pb, 8 + (s->nb_streams+1)*6, 0x3F09);
921
    put_be32(pb, s->nb_streams+1); // num of entries
922
    put_be32(pb, 6);             // size of one entry
923
    // write system item delta entry
924
    put_byte(pb, 0);
925
    put_byte(pb, 0); // slice entry
926
    put_be32(pb, 0); // element delta
927
    for (i = 0; i < s->nb_streams; i++) {
928
        AVStream *st = s->streams[i];
929
        MXFStreamContext *sc = st->priv_data;
930
        put_byte(pb, sc->temporal_reordering);
931
        if (sc->temporal_reordering)
932
            temporal_reordering = 1;
933
        // slice number
934
        if (i == 0) { // video track
935
            put_byte(pb, 0); // slice number
936
            put_be32(pb, KAG_SIZE); // system item size including klv fill
937
        } else { // audio track
938
            unsigned audio_frame_size = sc->aic.samples[0]*sc->aic.sample_size;
939
            audio_frame_size += klv_fill_size(audio_frame_size);
940
            put_byte(pb, 1);
941
            put_be32(pb, (i-1)*audio_frame_size); // element delta
942
        }
943
    }
944

    
945
    mxf_write_local_tag(pb, 8 + mxf->edit_units_count*(11+mxf->slice_count*4), 0x3F0A);
946
    put_be32(pb, mxf->edit_units_count);  // num of entries
947
    put_be32(pb, 11+mxf->slice_count*4);  // size of one entry
948
    for (i = 0; i < mxf->edit_units_count; i++) {
949
        if (temporal_reordering) {
950
            int temporal_offset = 0;
951
            for (j = i+1; j < mxf->edit_units_count; j++) {
952
                temporal_offset++;
953
                if (mxf->index_entries[j].flags & 0x10) { // backward prediction
954
                    // next is not b, so is reordered
955
                    if (!(mxf->index_entries[i+1].flags & 0x10)) {
956
                        if ((mxf->index_entries[i].flags & 0x11) == 0) // i frame
957
                            temporal_offset = 0;
958
                        else
959
                            temporal_offset = -temporal_offset;
960
                    }
961
                    break;
962
                }
963
            }
964
            put_byte(pb, temporal_offset);
965
        } else
966
            put_byte(pb, 0);
967
        if (!(mxf->index_entries[i].flags & 0x33)) { // I frame
968
            last_key_index = key_index;
969
            key_index = i;
970
        }
971
        if (mxf->index_entries[i].flags & 0x10 && // backward prediction
972
            !(mxf->index_entries[key_index].flags & 0x80)) { // open gop
973
            put_byte(pb, last_key_index - i);
974
        } else {
975
            put_byte(pb, key_index - i); // key frame offset
976
            if ((mxf->index_entries[i].flags & 0x20) == 0x20) // only forward
977
                last_key_index = key_index;
978
        }
979
        put_byte(pb, mxf->index_entries[i].flags);
980
        // stream offset
981
        put_be64(pb, mxf->index_entries[i].offset - mxf->index_entries[0].offset);
982
        if (s->nb_streams > 1)
983
            put_be32(pb, mxf->index_entries[i].slice_offset);
984
    }
985
}
986

    
987
static void mxf_write_klv_fill(AVFormatContext *s)
988
{
989
    unsigned pad = klv_fill_size(url_ftell(s->pb));
990
    if (pad) {
991
        put_buffer(s->pb, klv_fill_key, 16);
992
        pad -= 16;
993
        pad -= klv_ber_length(pad);
994
        klv_encode_ber_length(s->pb, pad);
995
        for (; pad > 7; pad -= 8)
996
            put_be64(s->pb, 0);
997
        for (; pad; pad--)
998
            put_byte(s->pb, 0);
999
        assert(!(url_ftell(s->pb) & (KAG_SIZE-1)));
1000
    }
1001
}
1002

    
1003
static void mxf_write_partition(AVFormatContext *s, int bodysid,
1004
                                int indexsid, unsigned index_byte_count,
1005
                                const uint8_t *key, int write_metadata)
1006
{
1007
    MXFContext *mxf = s->priv_data;
1008
    ByteIOContext *pb = s->pb;
1009
    int64_t header_byte_count_offset;
1010

    
1011
    // write klv
1012
    put_buffer(pb, key, 16);
1013

    
1014
    klv_encode_ber_length(pb, 88 + 16 * mxf->essence_container_count);
1015

    
1016
    // write partition value
1017
    put_be16(pb, 1); // majorVersion
1018
    put_be16(pb, 2); // minorVersion
1019
    put_be32(pb, KAG_SIZE); // KAGSize
1020

    
1021
    put_be64(pb, url_ftell(pb) - 25); // thisPartition
1022
    put_be64(pb, 0); // previousPartition
1023

    
1024
    put_be64(pb, mxf->footer_partition_offset); // footerPartition
1025

    
1026
    // set offset
1027
    header_byte_count_offset = url_ftell(pb);
1028
    put_be64(pb, 0); // headerByteCount, update later
1029

    
1030
    // indexTable
1031
    put_be64(pb, index_byte_count); // indexByteCount
1032
    put_be32(pb, indexsid); // indexSID
1033
    put_be64(pb, 0); // bodyOffset
1034

    
1035
    put_be32(pb, bodysid); // bodySID
1036

    
1037
    // operational pattern
1038
    if (s->nb_streams > 1) {
1039
        put_buffer(pb, op1a_ul, 14);
1040
        put_be16(pb, 0x0900); // multi track
1041
    } else {
1042
        put_buffer(pb, op1a_ul, 16);
1043
    }
1044

    
1045
    // essence container
1046
    mxf_write_essence_container_refs(s);
1047

    
1048
    if (write_metadata) {
1049
        // mark the start of the headermetadata and calculate metadata size
1050
        int64_t pos, start;
1051
        unsigned header_byte_count;
1052

    
1053
        mxf_write_klv_fill(s);
1054
        start = url_ftell(s->pb);
1055
        mxf_write_primer_pack(s);
1056
        mxf_write_header_metadata_sets(s);
1057
        pos = url_ftell(s->pb);
1058
        header_byte_count = pos - start + klv_fill_size(pos);
1059

    
1060
        // update header_byte_count
1061
        url_fseek(pb, header_byte_count_offset, SEEK_SET);
1062
        put_be64(pb, header_byte_count);
1063
        url_fseek(pb, pos, SEEK_SET);
1064
    }
1065

    
1066
    put_flush_packet(pb);
1067
}
1068

    
1069
static const UID mxf_mpeg2_codec_uls[] = {
1070
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x10,0x00 }, // MP-ML I-Frame
1071
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x01,0x11,0x00 }, // MP-ML Long GOP
1072
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x02,0x00 }, // 422P-ML I-Frame
1073
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x02,0x03,0x00 }, // 422P-ML Long GOP
1074
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x02,0x00 }, // MP-HL I-Frame
1075
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x03,0x03,0x00 }, // MP-HL Long GOP
1076
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x02,0x00 }, // 422P-HL I-Frame
1077
    { 0x06,0x0E,0x2B,0x34,0x04,0x01,0x01,0x03,0x04,0x01,0x02,0x02,0x01,0x04,0x03,0x00 }, // 422P-HL Long GOP
1078
};
1079

    
1080
static const UID *mxf_get_mpeg2_codec_ul(AVCodecContext *avctx)
1081
{
1082
    if (avctx->profile == 4) { // Main
1083
        if (avctx->level == 8) // Main
1084
            return avctx->gop_size ?
1085
                &mxf_mpeg2_codec_uls[1] :
1086
                &mxf_mpeg2_codec_uls[0];
1087
        else if (avctx->level == 4) // High
1088
            return avctx->gop_size ?
1089
                &mxf_mpeg2_codec_uls[5] :
1090
                &mxf_mpeg2_codec_uls[4];
1091
    } else if (avctx->profile == 0) { // 422
1092
        if (avctx->level == 5) // Main
1093
            return avctx->gop_size ?
1094
                &mxf_mpeg2_codec_uls[3] :
1095
                &mxf_mpeg2_codec_uls[2];
1096
        else if (avctx->level == 2) // High
1097
            return avctx->gop_size ?
1098
                &mxf_mpeg2_codec_uls[7] :
1099
                &mxf_mpeg2_codec_uls[6];
1100
    }
1101
    return NULL;
1102
}
1103

    
1104
static int mxf_parse_mpeg2_frame(AVFormatContext *s, AVStream *st, AVPacket *pkt)
1105
{
1106
    MXFContext *mxf = s->priv_data;
1107
    MXFStreamContext *sc = st->priv_data;
1108
    uint32_t c = -1;
1109
    int i;
1110

    
1111
    mxf->index_entries[mxf->edit_units_count].flags = 0;
1112

    
1113
    for(i = 0; i < pkt->size - 4; i++) {
1114
        c = (c<<8) + pkt->data[i];
1115
        if (c == 0x1B5) {
1116
            if (i + 2 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x10) { // seq ext
1117
                st->codec->profile = pkt->data[i+1] & 0x07;
1118
                st->codec->level   = pkt->data[i+2] >> 4;
1119
            } else if (i + 5 < pkt->size && (pkt->data[i+1] & 0xf0) == 0x80) { // pict coding ext
1120
                sc->interlaced = !(pkt->data[i+5] & 0x80); // progressive frame
1121
                break;
1122
            }
1123
        } else if (c == 0x1b8) { // gop
1124
            if (i + 4 < pkt->size && pkt->data[i+4]>>6 & 0x01) // closed
1125
                mxf->index_entries[mxf->edit_units_count].flags |= 0x80; // random access
1126
        } else if (c == 0x1b3) { // seq
1127
            mxf->index_entries[mxf->edit_units_count].flags |= 0x40;
1128
        } else if (c == 0x100) { // pic
1129
            int pict_type = (pkt->data[i+2]>>3) & 0x07;
1130
            if (pict_type == 2) { // P frame
1131
                mxf->index_entries[mxf->edit_units_count].flags |= 0x22;
1132
                st->codec->gop_size = 1;
1133
            } else if (pict_type == 3) { // B frame
1134
                mxf->index_entries[mxf->edit_units_count].flags |= 0x33;
1135
                sc->temporal_reordering = -1;
1136
            } else if (!pict_type) {
1137
                av_log(s, AV_LOG_ERROR, "error parsing mpeg2 frame\n");
1138
                return 0;
1139
            }
1140
        }
1141
    }
1142
    sc->codec_ul = mxf_get_mpeg2_codec_ul(st->codec);
1143
    return !!sc->codec_ul;
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 (i != 0) {
1178
                av_log(s, AV_LOG_ERROR, "video stream must be first track\n");
1179
                return -1;
1180
            }
1181
            if (fabs(av_q2d(st->codec->time_base) - 1/25.0) < 0.0001) {
1182
                samples_per_frame = PAL_samples_per_frame;
1183
                mxf->time_base = (AVRational){ 1, 25 };
1184
            } else if (fabs(av_q2d(st->codec->time_base) - 1001/30000.0) < 0.0001) {
1185
                samples_per_frame = NTSC_samples_per_frame;
1186
                mxf->time_base = (AVRational){ 1001, 30000 };
1187
            } else {
1188
                av_log(s, AV_LOG_ERROR, "unsupported video frame rate\n");
1189
                return -1;
1190
            }
1191
            av_set_pts_info(st, 64, mxf->time_base.num, mxf->time_base.den);
1192
        } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
1193
            if (st->codec->sample_rate != 48000) {
1194
                av_log(s, AV_LOG_ERROR, "only 48khz is implemented\n");
1195
                return -1;
1196
            }
1197
            av_set_pts_info(st, 64, 1, st->codec->sample_rate);
1198
            mxf->slice_count = 1;
1199
        }
1200
        sc->duration = -1;
1201

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

    
1209
        sc->codec_ul = &mxf_essence_container_uls[sc->index].codec_ul;
1210

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

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

    
1228
    mxf->timestamp = mxf_parse_timestamp(s->timestamp);
1229

    
1230
    if (!samples_per_frame)
1231
        samples_per_frame = PAL_samples_per_frame;
1232

    
1233
    if (ff_audio_interleave_init(s, samples_per_frame, mxf->time_base) < 0)
1234
        return -1;
1235

    
1236
    return 0;
1237
}
1238

    
1239
static const uint8_t system_metadata_pack_key[]        = { 0x06,0x0E,0x2B,0x34,0x02,0x05,0x01,0x01,0x0D,0x01,0x03,0x01,0x04,0x01,0x01,0x00 };
1240
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 };
1241

    
1242
static uint32_t ff_framenum_to_12m_time_code(unsigned frame, int drop, int fps)
1243
{
1244
    return (0                                    << 31) | // color frame flag
1245
           (0                                    << 30) | // drop  frame flag
1246
           ( ((frame % fps) / 10)                << 28) | // tens  of frames
1247
           ( ((frame % fps) % 10)                << 24) | // units of frames
1248
           (0                                    << 23) | // field phase (NTSC), b0 (PAL)
1249
           ((((frame / fps) % 60) / 10)          << 20) | // tens  of seconds
1250
           ((((frame / fps) % 60) % 10)          << 16) | // units of seconds
1251
           (0                                    << 15) | // b0 (NTSC), b2 (PAL)
1252
           ((((frame / (fps * 60)) % 60) / 10)   << 12) | // tens  of minutes
1253
           ((((frame / (fps * 60)) % 60) % 10)   <<  8) | // units of minutes
1254
           (0                                    <<  7) | // b1
1255
           (0                                    <<  6) | // b2 (NSC), field phase (PAL)
1256
           ((((frame / (fps * 3600) % 24)) / 10) <<  4) | // tens  of hours
1257
           (  (frame / (fps * 3600) % 24)) % 10;          // units of hours
1258
}
1259

    
1260
static void mxf_write_system_item(AVFormatContext *s)
1261
{
1262
    MXFContext *mxf = s->priv_data;
1263
    ByteIOContext *pb = s->pb;
1264
    unsigned fps, frame;
1265
    uint32_t time_code;
1266

    
1267
    frame = mxf->edit_units_count;
1268

    
1269
    // write system metadata pack
1270
    put_buffer(pb, system_metadata_pack_key, 16);
1271
    klv_encode_ber_length(pb, 57);
1272
    put_byte(pb, 0x5c); // UL, user date/time stamp, picture and sound item present
1273
    put_byte(pb, 0x04); // content package rate
1274
    put_byte(pb, 0x00); // content package type
1275
    put_be16(pb, 0x00); // channel handle
1276
    put_be16(pb, frame); // continuity count
1277
    if (mxf->essence_container_count > 1)
1278
        put_buffer(pb, multiple_desc_ul, 16);
1279
    else
1280
        put_buffer(pb, mxf_essence_container_uls[mxf->essence_containers_indices[0]].container_ul, 16);
1281
    put_byte(pb, 0);
1282
    put_be64(pb, 0);
1283
    put_be64(pb, 0); // creation date/time stamp
1284

    
1285
    // XXX drop frame
1286
    if (mxf->time_base.den == 30000) fps = 30;
1287
    else                             fps = 25;
1288

    
1289
    put_byte(pb, 0x81); // SMPTE 12M time code
1290
    time_code = ff_framenum_to_12m_time_code(frame, 0, fps);
1291
    put_be32(pb, time_code);
1292
    put_be32(pb, 0); // binary group data
1293
    put_be64(pb, 0);
1294

    
1295
    // write system metadata package set
1296
    put_buffer(pb, system_metadata_package_set_key, 16);
1297
    klv_encode_ber_length(pb, 35);
1298
    put_byte(pb, 0x83); // UMID
1299
    put_be16(pb, 0x20);
1300
    mxf_write_umid(pb, SourcePackage, 0);
1301
}
1302

    
1303
static int mxf_write_packet(AVFormatContext *s, AVPacket *pkt)
1304
{
1305
    MXFContext *mxf = s->priv_data;
1306
    ByteIOContext *pb = s->pb;
1307
    AVStream *st = s->streams[pkt->stream_index];
1308
    MXFStreamContext *sc = st->priv_data;
1309

    
1310
    if (!(mxf->edit_units_count % MXF_INDEX_CLUSTER_SIZE)) {
1311
        mxf->index_entries = av_realloc(mxf->index_entries,
1312
            (mxf->edit_units_count + MXF_INDEX_CLUSTER_SIZE)*
1313
             sizeof(*mxf->index_entries));
1314
        if (!mxf->index_entries) {
1315
            av_log(s, AV_LOG_ERROR, "could not allocate index entries\n");
1316
            return -1;
1317
        }
1318
    }
1319

    
1320
    if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO) {
1321
        if (!mxf_parse_mpeg2_frame(s, st, pkt)) {
1322
            av_log(s, AV_LOG_ERROR, "could not get mpeg2 profile and level\n");
1323
            return -1;
1324
        }
1325
    }
1326

    
1327
    if (!mxf->header_written) {
1328
        mxf_write_partition(s, 1, 0, 0, header_open_partition_key, 1);
1329
        mxf->header_written = 1;
1330
    }
1331

    
1332
    if (st->index == 0) {
1333
        mxf_write_klv_fill(s);
1334
        mxf->index_entries[mxf->edit_units_count].offset = url_ftell(pb);
1335
        mxf_write_system_item(s);
1336

    
1337
        mxf->edit_units_count++;
1338
    } else if (st->index == 1) {
1339
        mxf->index_entries[mxf->edit_units_count-1].slice_offset =
1340
            url_ftell(pb) - mxf->index_entries[mxf->edit_units_count-1].offset;
1341
    }
1342

    
1343
    mxf_write_klv_fill(s);
1344
    put_buffer(pb, sc->track_essence_element_key, 16); // write key
1345
    klv_encode_ber_length(pb, pkt->size); // write length
1346
    put_buffer(pb, pkt->data, pkt->size); // write value
1347

    
1348
    sc->duration = FFMAX(pkt->pts + pkt->duration, sc->duration);
1349

    
1350
    put_flush_packet(pb);
1351
    return 0;
1352
}
1353

    
1354
static void mxf_write_random_index_pack(AVFormatContext *s)
1355
{
1356
    MXFContext *mxf = s->priv_data;
1357
    ByteIOContext *pb = s->pb;
1358
    uint64_t pos = url_ftell(pb);
1359

    
1360
    put_buffer(pb, random_index_pack_key, 16);
1361
    klv_encode_ber_length(pb, 28);
1362

    
1363
    put_be32(pb, 1); // BodySID of header partition
1364
    put_be64(pb, 0); // offset of header partition
1365

    
1366
    put_be32(pb, 0); // BodySID of footer partition
1367
    put_be64(pb, mxf->footer_partition_offset);
1368

    
1369
    put_be32(pb, url_ftell(pb) - pos + 4);
1370
}
1371

    
1372
static int mxf_write_footer(AVFormatContext *s)
1373
{
1374
    MXFContext *mxf = s->priv_data;
1375
    ByteIOContext *pb = s->pb;
1376
    unsigned index_byte_count =
1377
        109 + (s->nb_streams+1)*6 +
1378
        mxf->edit_units_count*(11+mxf->slice_count*4);
1379

    
1380
    // add encoded ber length
1381
    index_byte_count += 16 + klv_ber_length(index_byte_count);
1382
    index_byte_count += klv_fill_size(index_byte_count);
1383

    
1384
    mxf_write_klv_fill(s);
1385
    mxf->footer_partition_offset = url_ftell(pb);
1386
    mxf_write_partition(s, 0, 2, index_byte_count, footer_partition_key, 0);
1387

    
1388
    mxf_write_klv_fill(s);
1389
    mxf_write_index_table_segment(s);
1390

    
1391
    mxf_write_klv_fill(s);
1392
    mxf_write_random_index_pack(s);
1393

    
1394
    if (!url_is_streamed(s->pb)) {
1395
        url_fseek(pb, 0, SEEK_SET);
1396
        mxf_write_partition(s, 1, 0, 0, header_closed_partition_key, 1);
1397
    }
1398

    
1399
    ff_audio_interleave_close(s);
1400

    
1401
    av_freep(&mxf->index_entries);
1402

    
1403
    mxf_free(s);
1404
    return 0;
1405
}
1406

    
1407
static int mxf_interleave_get_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1408
{
1409
    AVPacketList *pktl;
1410
    int stream_count = 0;
1411
    int streams[MAX_STREAMS];
1412

    
1413
    memset(streams, 0, sizeof(streams));
1414
    pktl = s->packet_buffer;
1415
    while (pktl) {
1416
        //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
1417
        if (!streams[pktl->pkt.stream_index])
1418
            stream_count++;
1419
        streams[pktl->pkt.stream_index]++;
1420
        pktl = pktl->next;
1421
    }
1422

    
1423
    if (stream_count && (s->nb_streams == stream_count || flush)) {
1424
        pktl = s->packet_buffer;
1425
        if (s->nb_streams != stream_count) {
1426
            AVPacketList *first = NULL;
1427
            // find first packet in edit unit
1428
            while (pktl) {
1429
                AVStream *st = s->streams[pktl->pkt.stream_index];
1430
                if (st->index == 0)
1431
                    break;
1432
                else if (!first)
1433
                    first = pktl;
1434
                pktl = pktl->next;
1435
            }
1436
            // purge packet queue
1437
            while (pktl) {
1438
                AVPacketList *next = pktl->next;
1439
                av_free_packet(&pktl->pkt);
1440
                av_freep(&pktl);
1441
                pktl = next;
1442
            }
1443
            if (!first)
1444
                goto out;
1445
            pktl = first;
1446
        }
1447

    
1448
        *out = pktl->pkt;
1449
        //av_log(s, AV_LOG_DEBUG, "out st:%d dts:%lld\n", (*out).stream_index, (*out).dts);
1450
        s->packet_buffer = pktl->next;
1451
        av_freep(&pktl);
1452
        return 1;
1453
    } else {
1454
    out:
1455
        av_init_packet(out);
1456
        return 0;
1457
    }
1458
}
1459

    
1460
static int mxf_compare_timestamps(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
1461
{
1462
    MXFStreamContext *sc  = s->streams[pkt ->stream_index]->priv_data;
1463
    MXFStreamContext *sc2 = s->streams[next->stream_index]->priv_data;
1464

    
1465
    return next->dts > pkt->dts ||
1466
        (next->dts == pkt->dts && sc->order < sc2->order);
1467
}
1468

    
1469
static int mxf_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
1470
{
1471
    return ff_audio_rechunk_interleave(s, out, pkt, flush,
1472
                               mxf_interleave_get_packet, mxf_compare_timestamps);
1473
}
1474

    
1475
AVOutputFormat mxf_muxer = {
1476
    "mxf",
1477
    NULL_IF_CONFIG_SMALL("Material eXchange Format"),
1478
    NULL,
1479
    "mxf",
1480
    sizeof(MXFContext),
1481
    CODEC_ID_PCM_S16LE,
1482
    CODEC_ID_MPEG2VIDEO,
1483
    mxf_write_header,
1484
    mxf_write_packet,
1485
    mxf_write_footer,
1486
    AVFMT_NOTIMESTAMPS,
1487
    NULL,
1488
    mxf_interleave,
1489
};