]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavformat/gxfenc.c
67ee79650a753eb0cb0e5d75d864474590de9e84
[frescor/ffmpeg.git] / libavformat / gxfenc.c
1 /*
2  * GXF muxer.
3  * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "libavutil/fifo.h"
23 #include "avformat.h"
24 #include "gxf.h"
25 #include "riff.h"
26 #include "audiointerleave.h"
27
28 #define GXF_AUDIO_PACKET_SIZE 65536
29
30 typedef struct GXFStreamContext {
31     AudioInterleaveContext aic;
32     uint32_t track_type;
33     uint32_t sample_size;
34     uint32_t sample_rate;
35     uint16_t media_type;
36     uint16_t media_info;
37     int frame_rate_index;
38     int lines_index;
39     int fields;
40     int iframes;
41     int pframes;
42     int bframes;
43     int p_per_gop;
44     int b_per_i_or_p; ///< number of B frames per I frame or P frame
45     int first_gop_closed;
46     unsigned order;   ///< interleaving order
47 } GXFStreamContext;
48
49 typedef struct GXFContext {
50     uint32_t nb_fields;
51     uint16_t audio_tracks;
52     uint16_t mpeg_tracks;
53     int64_t creation_time;
54     uint32_t umf_start_offset;
55     uint32_t umf_track_offset;
56     uint32_t umf_media_offset;
57     uint32_t umf_length;
58     uint16_t umf_track_size;
59     uint16_t umf_media_size;
60     AVRational time_base;
61     int flags;
62     GXFStreamContext timecode_track;
63     unsigned *flt_entries;    ///< offsets of packets /1024, starts after 2nd video field
64     unsigned flt_entries_nb;
65     uint64_t *map_offsets;    ///< offset of map packets
66     unsigned map_offsets_nb;
67     unsigned packet_count;
68 } GXFContext;
69
70 static const struct {
71     int height, index;
72 } gxf_lines_tab[] = {
73     { 480,  1 }, /* NTSC */
74     { 512,  1 }, /* NTSC + VBI */
75     { 576,  2 }, /* PAL */
76     { 608,  2 }, /* PAL + VBI */
77     { 1080, 4 },
78     { 720,  6 },
79 };
80
81 static const AVCodecTag gxf_media_types[] = {
82     { CODEC_ID_MJPEG     ,   3 }, /* NTSC */
83     { CODEC_ID_MJPEG     ,   4 }, /* PAL */
84     { CODEC_ID_PCM_S24LE ,   9 },
85     { CODEC_ID_PCM_S16LE ,  10 },
86     { CODEC_ID_MPEG2VIDEO,  11 }, /* NTSC */
87     { CODEC_ID_MPEG2VIDEO,  12 }, /* PAL */
88     { CODEC_ID_DVVIDEO   ,  13 }, /* NTSC */
89     { CODEC_ID_DVVIDEO   ,  14 }, /* PAL */
90     { CODEC_ID_DVVIDEO   ,  15 }, /* 50M NTSC */
91     { CODEC_ID_DVVIDEO   ,  16 }, /* 50M PAL */
92     { CODEC_ID_AC3       ,  17 },
93     //{ CODEC_ID_NONE,  ,   18 }, /* Non compressed 24 bit audio */
94     { CODEC_ID_MPEG2VIDEO,  20 }, /* MPEG HD */
95     { CODEC_ID_MPEG1VIDEO,  22 }, /* NTSC */
96     { CODEC_ID_MPEG1VIDEO,  23 }, /* PAL */
97     { 0, 0 },
98 };
99
100 #define SERVER_PATH "EXT:/PDR/default/"
101 #define ES_NAME_PATTERN "EXT:/PDR/default/ES."
102
103 static int gxf_find_lines_index(AVStream *st)
104 {
105     GXFStreamContext *sc = st->priv_data;
106     int i;
107
108     for (i = 0; i < 6; ++i) {
109         if (st->codec->height == gxf_lines_tab[i].height) {
110             sc->lines_index = gxf_lines_tab[i].index;
111             return 0;
112         }
113     }
114     return -1;
115 }
116
117 static void gxf_write_padding(ByteIOContext *pb, int64_t to_pad)
118 {
119     for (; to_pad > 0; to_pad--) {
120         put_byte(pb, 0);
121     }
122 }
123
124 static int64_t updatePacketSize(ByteIOContext *pb, int64_t pos)
125 {
126     int64_t curpos;
127     int size;
128
129     size = url_ftell(pb) - pos;
130     if (size % 4) {
131         gxf_write_padding(pb, 4 - size % 4);
132         size = url_ftell(pb) - pos;
133     }
134     curpos = url_ftell(pb);
135     url_fseek(pb, pos + 6, SEEK_SET);
136     put_be32(pb, size);
137     url_fseek(pb, curpos, SEEK_SET);
138     return curpos - pos;
139 }
140
141 static int64_t updateSize(ByteIOContext *pb, int64_t pos)
142 {
143     int64_t curpos;
144
145     curpos = url_ftell(pb);
146     url_fseek(pb, pos, SEEK_SET);
147     put_be16(pb, curpos - pos - 2);
148     url_fseek(pb, curpos, SEEK_SET);
149     return curpos - pos;
150 }
151
152 static void gxf_write_packet_header(ByteIOContext *pb, GXFPktType type)
153 {
154     put_be32(pb, 0); /* packet leader for synchro */
155     put_byte(pb, 1);
156     put_byte(pb, type); /* map packet */
157     put_be32(pb, 0); /* size */
158     put_be32(pb, 0); /* reserved */
159     put_byte(pb, 0xE1); /* trailer 1 */
160     put_byte(pb, 0xE2); /* trailer 2 */
161 }
162
163 static int gxf_write_mpeg_auxiliary(ByteIOContext *pb, AVStream *st)
164 {
165     GXFStreamContext *sc = st->priv_data;
166     char buffer[1024];
167     int size, starting_line;
168
169     if (sc->iframes) {
170         sc->p_per_gop = sc->pframes / sc->iframes;
171         if (sc->pframes % sc->iframes)
172             sc->p_per_gop++;
173         if (sc->pframes) {
174             sc->b_per_i_or_p = sc->bframes / sc->pframes;
175             if (sc->bframes % sc->pframes)
176                 sc->b_per_i_or_p++;
177         }
178         if (sc->p_per_gop > 9)
179             sc->p_per_gop = 9; /* ensure value won't take more than one char */
180         if (sc->b_per_i_or_p > 9)
181             sc->b_per_i_or_p = 9; /* ensure value won't take more than one char */
182     }
183     if (st->codec->height == 512 || st->codec->height == 608)
184         starting_line = 7; // VBI
185     else if (st->codec->height == 480)
186         starting_line = 20;
187     else
188         starting_line = 23; // default PAL
189
190     size = snprintf(buffer, 1024, "Ver 1\nBr %.6f\nIpg 1\nPpi %d\nBpiop %d\n"
191                     "Pix 0\nCf %d\nCg %d\nSl %d\nnl16 %d\nVi 1\nf1 1\n",
192                     (float)st->codec->bit_rate, sc->p_per_gop, sc->b_per_i_or_p,
193                     st->codec->pix_fmt == PIX_FMT_YUV422P ? 2 : 1, sc->first_gop_closed == 1,
194                     starting_line, st->codec->height / 16);
195     put_byte(pb, TRACK_MPG_AUX);
196     put_byte(pb, size + 1);
197     put_buffer(pb, (uint8_t *)buffer, size + 1);
198     return size + 3;
199 }
200
201 static int gxf_write_timecode_auxiliary(ByteIOContext *pb, GXFStreamContext *sc)
202 {
203     put_byte(pb, 0); /* fields */
204     put_byte(pb, 0);  /* seconds */
205     put_byte(pb, 0); /* minutes */
206     put_byte(pb, 0); /* flags + hours */
207     /* reserved */
208     put_be32(pb, 0);
209     return 8;
210 }
211
212 static int gxf_write_track_description(AVFormatContext *s, GXFStreamContext *sc, int index)
213 {
214     ByteIOContext *pb = s->pb;
215     int64_t pos;
216     int mpeg = sc->track_type == 4 || sc->track_type == 9;
217
218     /* track description section */
219     put_byte(pb, sc->media_type + 0x80);
220     put_byte(pb, index + 0xC0);
221
222     pos = url_ftell(pb);
223     put_be16(pb, 0); /* size */
224
225     /* media file name */
226     put_byte(pb, TRACK_NAME);
227     put_byte(pb, strlen(ES_NAME_PATTERN) + 3);
228     put_tag(pb, ES_NAME_PATTERN);
229     put_be16(pb, sc->media_info);
230     put_byte(pb, 0);
231
232     if (!mpeg) {
233         /* auxiliary information */
234         put_byte(pb, TRACK_AUX);
235         put_byte(pb, 8);
236         if (sc->track_type == 3)
237             gxf_write_timecode_auxiliary(pb, sc);
238         else
239             put_le64(pb, 0);
240     }
241
242     /* file system version */
243     put_byte(pb, TRACK_VER);
244     put_byte(pb, 4);
245     put_be32(pb, 0);
246
247     if (mpeg)
248         gxf_write_mpeg_auxiliary(pb, s->streams[index]);
249
250     /* frame rate */
251     put_byte(pb, TRACK_FPS);
252     put_byte(pb, 4);
253     put_be32(pb, sc->frame_rate_index);
254
255     /* lines per frame */
256     put_byte(pb, TRACK_LINES);
257     put_byte(pb, 4);
258     put_be32(pb, sc->lines_index);
259
260     /* fields per frame */
261     put_byte(pb, TRACK_FPF);
262     put_byte(pb, 4);
263     put_be32(pb, sc->fields);
264
265     return updateSize(pb, pos);
266 }
267
268 static int gxf_write_material_data_section(AVFormatContext *s)
269 {
270     GXFContext *gxf = s->priv_data;
271     ByteIOContext *pb = s->pb;
272     int64_t pos;
273     const char *filename = strrchr(s->filename, '/');
274
275     pos = url_ftell(pb);
276     put_be16(pb, 0); /* size */
277
278     /* name */
279     if (filename)
280         filename++;
281     else
282         filename = s->filename;
283     put_byte(pb, MAT_NAME);
284     put_byte(pb, strlen(SERVER_PATH) + strlen(filename) + 1);
285     put_tag(pb, SERVER_PATH);
286     put_tag(pb, filename);
287     put_byte(pb, 0);
288
289     /* first field */
290     put_byte(pb, MAT_FIRST_FIELD);
291     put_byte(pb, 4);
292     put_be32(pb, 0);
293
294     /* last field */
295     put_byte(pb, MAT_LAST_FIELD);
296     put_byte(pb, 4);
297     put_be32(pb, gxf->nb_fields);
298
299     /* reserved */
300     put_byte(pb, MAT_MARK_IN);
301     put_byte(pb, 4);
302     put_be32(pb, 0);
303
304     put_byte(pb, MAT_MARK_OUT);
305     put_byte(pb, 4);
306     put_be32(pb, gxf->nb_fields);
307
308     /* estimated size */
309     put_byte(pb, MAT_SIZE);
310     put_byte(pb, 4);
311     put_be32(pb, url_fsize(pb) / 1024);
312
313     return updateSize(pb, pos);
314 }
315
316 static int gxf_write_track_description_section(AVFormatContext *s)
317 {
318     GXFContext *gxf = s->priv_data;
319     ByteIOContext *pb = s->pb;
320     int64_t pos;
321     int i;
322
323     pos = url_ftell(pb);
324     put_be16(pb, 0); /* size */
325     for (i = 0; i < s->nb_streams; ++i)
326         gxf_write_track_description(s, s->streams[i]->priv_data, i);
327
328     gxf_write_track_description(s, &gxf->timecode_track, s->nb_streams);
329
330     return updateSize(pb, pos);
331 }
332
333 static int gxf_write_map_packet(AVFormatContext *s, int rewrite)
334 {
335     GXFContext *gxf = s->priv_data;
336     ByteIOContext *pb = s->pb;
337     int64_t pos = url_ftell(pb);
338
339     if (!rewrite) {
340         if (!(gxf->map_offsets_nb % 30)) {
341             gxf->map_offsets = av_realloc(gxf->map_offsets,
342                                           (gxf->map_offsets_nb+30)*sizeof(*gxf->map_offsets));
343             if (!gxf->map_offsets) {
344                 av_log(s, AV_LOG_ERROR, "could not realloc map offsets\n");
345                 return -1;
346             }
347         }
348         gxf->map_offsets[gxf->map_offsets_nb++] = pos; // do not increment here
349     }
350
351     gxf_write_packet_header(pb, PKT_MAP);
352
353     /* preamble */
354     put_byte(pb, 0xE0); /* version */
355     put_byte(pb, 0xFF); /* reserved */
356
357     gxf_write_material_data_section(s);
358     gxf_write_track_description_section(s);
359
360     return updatePacketSize(pb, pos);
361 }
362
363 static int gxf_write_flt_packet(AVFormatContext *s)
364 {
365     GXFContext *gxf = s->priv_data;
366     ByteIOContext *pb = s->pb;
367     int64_t pos = url_ftell(pb);
368     int fields_per_flt = (gxf->nb_fields+1) / 1000 + 1;
369     int flt_entries = gxf->nb_fields / fields_per_flt - 1;
370     int i = 0;
371
372     gxf_write_packet_header(pb, PKT_FLT);
373
374     put_le32(pb, fields_per_flt); /* number of fields */
375     put_le32(pb, flt_entries); /* number of active flt entries */
376
377     if (gxf->flt_entries) {
378         for (i = 0; i < flt_entries; i++)
379             put_le32(pb, gxf->flt_entries[(i*fields_per_flt)>>1]);
380     }
381
382     for (; i < 1000; i++)
383         put_le32(pb, 0);
384
385     return updatePacketSize(pb, pos);
386 }
387
388 static int gxf_write_umf_material_description(AVFormatContext *s)
389 {
390     GXFContext *gxf = s->priv_data;
391     ByteIOContext *pb = s->pb;
392     int timecode_base = gxf->time_base.den == 60000 ? 60 : 50;
393
394     // XXX drop frame
395     uint32_t timecode =
396         gxf->nb_fields / (timecode_base * 3600) % 24 << 24 | // hours
397         gxf->nb_fields / (timecode_base * 60) % 60   << 16 | // minutes
398         gxf->nb_fields /  timecode_base % 60         <<  8 | // seconds
399         gxf->nb_fields %  timecode_base;                     // fields
400
401     put_le32(pb, gxf->flags);
402     put_le32(pb, gxf->nb_fields); /* length of the longest track */
403     put_le32(pb, gxf->nb_fields); /* length of the shortest track */
404     put_le32(pb, 0); /* mark in */
405     put_le32(pb, gxf->nb_fields); /* mark out */
406     put_le32(pb, 0); /* timecode mark in */
407     put_le32(pb, timecode); /* timecode mark out */
408     put_le64(pb, s->timestamp); /* modification time */
409     put_le64(pb, s->timestamp); /* creation time */
410     put_le16(pb, 0); /* reserved */
411     put_le16(pb, 0); /* reserved */
412     put_le16(pb, gxf->audio_tracks);
413     put_le16(pb, 1); /* timecode track count */
414     put_le16(pb, 0); /* reserved */
415     put_le16(pb, gxf->mpeg_tracks);
416     return 48;
417 }
418
419 static int gxf_write_umf_payload(AVFormatContext *s)
420 {
421     GXFContext *gxf = s->priv_data;
422     ByteIOContext *pb = s->pb;
423
424     put_le32(pb, gxf->umf_length); /* total length of the umf data */
425     put_le32(pb, 3); /* version */
426     put_le32(pb, s->nb_streams+1);
427     put_le32(pb, gxf->umf_track_offset); /* umf track section offset */
428     put_le32(pb, gxf->umf_track_size);
429     put_le32(pb, s->nb_streams+1);
430     put_le32(pb, gxf->umf_media_offset);
431     put_le32(pb, gxf->umf_media_size);
432     put_le32(pb, gxf->umf_length); /* user data offset */
433     put_le32(pb, 0); /* user data size */
434     put_le32(pb, 0); /* reserved */
435     put_le32(pb, 0); /* reserved */
436     return 48;
437 }
438
439 static int gxf_write_umf_track_description(AVFormatContext *s)
440 {
441     ByteIOContext *pb = s->pb;
442     GXFContext *gxf = s->priv_data;
443     int64_t pos = url_ftell(pb);
444     int i;
445
446     gxf->umf_track_offset = pos - gxf->umf_start_offset;
447     for (i = 0; i < s->nb_streams; ++i) {
448         GXFStreamContext *sc = s->streams[i]->priv_data;
449         put_le16(pb, sc->media_info);
450         put_le16(pb, 1);
451     }
452
453     put_le16(pb, gxf->timecode_track.media_info);
454     put_le16(pb, 1);
455
456     return url_ftell(pb) - pos;
457 }
458
459 static int gxf_write_umf_media_mpeg(ByteIOContext *pb, AVStream *st)
460 {
461     GXFStreamContext *sc = st->priv_data;
462
463     if (st->codec->pix_fmt == PIX_FMT_YUV422P)
464         put_le32(pb, 2);
465     else
466         put_le32(pb, 1); /* default to 420 */
467     put_le32(pb, sc->first_gop_closed == 1); /* closed = 1, open = 0, unknown = 255 */
468     put_le32(pb, 3); /* top = 1, bottom = 2, frame = 3, unknown = 0 */
469     put_le32(pb, 1); /* I picture per GOP */
470     put_le32(pb, sc->p_per_gop);
471     put_le32(pb, sc->b_per_i_or_p);
472     if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO)
473         put_le32(pb, 2);
474     else if (st->codec->codec_id == CODEC_ID_MPEG1VIDEO)
475         put_le32(pb, 1);
476     else
477         put_le32(pb, 0);
478     put_le32(pb, 0); /* reserved */
479     return 32;
480 }
481
482 static int gxf_write_umf_media_timecode(ByteIOContext *pb, GXFStreamContext *sc)
483 {
484     put_le32(pb, 1); /* non drop frame */
485     put_le32(pb, 0); /* reserved */
486     put_le32(pb, 0); /* reserved */
487     put_le32(pb, 0); /* reserved */
488     put_le32(pb, 0); /* reserved */
489     put_le32(pb, 0); /* reserved */
490     put_le32(pb, 0); /* reserved */
491     put_le32(pb, 0); /* reserved */
492     return 32;
493 }
494
495 static int gxf_write_umf_media_dv(ByteIOContext *pb, GXFStreamContext *sc)
496 {
497     int i;
498
499     for (i = 0; i < 8; i++) {
500         put_be32(pb, 0);
501     }
502     return 32;
503 }
504
505 static int gxf_write_umf_media_audio(ByteIOContext *pb, GXFStreamContext *sc)
506 {
507     put_le64(pb, av_dbl2int(1)); /* sound level to begin to */
508     put_le64(pb, av_dbl2int(1)); /* sound level to begin to */
509     put_le32(pb, 0); /* number of fields over which to ramp up sound level */
510     put_le32(pb, 0); /* number of fields over which to ramp down sound level */
511     put_le32(pb, 0); /* reserved */
512     put_le32(pb, 0); /* reserved */
513     return 32;
514 }
515
516 #if 0
517 static int gxf_write_umf_media_mjpeg(ByteIOContext *pb, GXFStreamContext *sc)
518 {
519     put_be64(pb, 0); /* FIXME FLOAT max chroma quant level */
520     put_be64(pb, 0); /* FIXME FLOAT max luma quant level */
521     put_be64(pb, 0); /* FIXME FLOAT min chroma quant level */
522     put_be64(pb, 0); /* FIXME FLOAT min luma quant level */
523     return 32;
524 }
525 #endif
526
527 static int gxf_write_umf_media_description(AVFormatContext *s)
528 {
529     GXFContext *gxf = s->priv_data;
530     ByteIOContext *pb = s->pb;
531     int64_t pos;
532     int i, j;
533
534     pos = url_ftell(pb);
535     gxf->umf_media_offset = pos - gxf->umf_start_offset;
536     for (i = 0; i <= s->nb_streams; ++i) {
537         GXFStreamContext *sc;
538         int64_t startpos, curpos;
539
540         if (i == s->nb_streams)
541             sc = &gxf->timecode_track;
542         else
543             sc = s->streams[i]->priv_data;
544
545         startpos = url_ftell(pb);
546         put_le16(pb, 0); /* length */
547         put_le16(pb, sc->media_info);
548         put_le16(pb, 0); /* reserved */
549         put_le16(pb, 0); /* reserved */
550         put_le32(pb, gxf->nb_fields);
551         put_le32(pb, 0); /* attributes rw, ro */
552         put_le32(pb, 0); /* mark in */
553         put_le32(pb, gxf->nb_fields); /* mark out */
554         put_buffer(pb, ES_NAME_PATTERN, sizeof(ES_NAME_PATTERN));
555         put_be16(pb, sc->media_info);
556         for (j = sizeof(ES_NAME_PATTERN)+2; j < 88; j++)
557             put_byte(pb, 0);
558         put_le32(pb, sc->track_type);
559         put_le32(pb, sc->sample_rate);
560         put_le32(pb, sc->sample_size);
561         put_le32(pb, 0); /* reserved */
562
563         if (sc == &gxf->timecode_track)
564             gxf_write_umf_media_timecode(pb, sc); /* 8 0bytes */
565         else {
566             AVStream *st = s->streams[i];
567             switch (st->codec->codec_id) {
568             case CODEC_ID_MPEG2VIDEO:
569                 gxf_write_umf_media_mpeg(pb, st);
570                 break;
571             case CODEC_ID_PCM_S16LE:
572                 gxf_write_umf_media_audio(pb, sc);
573                 break;
574             case CODEC_ID_DVVIDEO:
575                 gxf_write_umf_media_dv(pb, sc);
576                 break;
577             }
578         }
579
580         curpos = url_ftell(pb);
581         url_fseek(pb, startpos, SEEK_SET);
582         put_le16(pb, curpos - startpos);
583         url_fseek(pb, curpos, SEEK_SET);
584     }
585     return url_ftell(pb) - pos;
586 }
587
588 static int gxf_write_umf_packet(AVFormatContext *s)
589 {
590     GXFContext *gxf = s->priv_data;
591     ByteIOContext *pb = s->pb;
592     int64_t pos = url_ftell(pb);
593
594     gxf_write_packet_header(pb, PKT_UMF);
595
596     /* preamble */
597     put_byte(pb, 3); /* first and last (only) packet */
598     put_be32(pb, gxf->umf_length); /* data length */
599
600     gxf->umf_start_offset = url_ftell(pb);
601     gxf_write_umf_payload(s);
602     gxf_write_umf_material_description(s);
603     gxf->umf_track_size = gxf_write_umf_track_description(s);
604     gxf->umf_media_size = gxf_write_umf_media_description(s);
605     gxf->umf_length = url_ftell(pb) - gxf->umf_start_offset;
606     return updatePacketSize(pb, pos);
607 }
608
609 static const int GXF_samples_per_frame[] = { 32768, 0 };
610
611 static void gxf_init_timecode_track(GXFStreamContext *sc, GXFStreamContext *vsc)
612 {
613     if (!vsc)
614         return;
615
616     sc->media_type = vsc->sample_rate == 60 ? 7 : 8;
617     sc->sample_rate = vsc->sample_rate;
618     sc->media_info = ('T'<<8) | '0';
619     sc->track_type = 3;
620     sc->frame_rate_index = vsc->frame_rate_index;
621     sc->lines_index = vsc->lines_index;
622     sc->sample_size = 16;
623     sc->fields = vsc->fields;
624 }
625
626 static int gxf_write_header(AVFormatContext *s)
627 {
628     ByteIOContext *pb = s->pb;
629     GXFContext *gxf = s->priv_data;
630     GXFStreamContext *vsc = NULL;
631     uint8_t tracks[255] = {0};
632     int i, media_info = 0;
633
634     if (url_is_streamed(pb)) {
635         av_log(s, AV_LOG_ERROR, "gxf muxer does not support streamed output, patch welcome");
636         return -1;
637     }
638
639     gxf->flags |= 0x00080000; /* material is simple clip */
640     for (i = 0; i < s->nb_streams; ++i) {
641         AVStream *st = s->streams[i];
642         GXFStreamContext *sc = av_mallocz(sizeof(*sc));
643         if (!sc)
644             return AVERROR(ENOMEM);
645         st->priv_data = sc;
646
647         sc->media_type = codec_get_tag(gxf_media_types, st->codec->codec_id);
648         if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
649             if (st->codec->codec_id != CODEC_ID_PCM_S16LE) {
650                 av_log(s, AV_LOG_ERROR, "only 16 BIT PCM LE allowed for now\n");
651                 return -1;
652             }
653             if (st->codec->sample_rate != 48000) {
654                 av_log(s, AV_LOG_ERROR, "only 48000hz sampling rate is allowed\n");
655                 return -1;
656             }
657             if (st->codec->channels != 1) {
658                 av_log(s, AV_LOG_ERROR, "only mono tracks are allowed\n");
659                 return -1;
660             }
661             sc->track_type = 2;
662             sc->sample_rate = st->codec->sample_rate;
663             av_set_pts_info(st, 64, 1, sc->sample_rate);
664             sc->sample_size = 16;
665             sc->frame_rate_index = -2;
666             sc->lines_index = -2;
667             sc->fields = -2;
668             gxf->audio_tracks++;
669             gxf->flags |= 0x04000000; /* audio is 16 bit pcm */
670             media_info = 'A';
671         } else if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
672             if (i != 0) {
673                 av_log(s, AV_LOG_ERROR, "video stream must be the first track\n");
674                 return -1;
675             }
676             /* FIXME check from time_base ? */
677             if (st->codec->height == 480 || st->codec->height == 512) { /* NTSC or NTSC+VBI */
678                 sc->frame_rate_index = 5;
679                 sc->sample_rate = 60;
680                 gxf->flags |= 0x00000080;
681                 gxf->time_base = (AVRational){ 1001, 60000 };
682             } else { /* assume PAL */
683                 sc->frame_rate_index = 6;
684                 sc->media_type++;
685                 sc->sample_rate = 50;
686                 gxf->flags |= 0x00000040;
687                 gxf->time_base = (AVRational){ 1, 50 };
688             }
689             av_set_pts_info(st, 64, gxf->time_base.num, gxf->time_base.den);
690             if (gxf_find_lines_index(st) < 0)
691                 sc->lines_index = -1;
692             sc->sample_size = st->codec->bit_rate;
693             sc->fields = 2; /* interlaced */
694
695             vsc = sc;
696
697             switch (st->codec->codec_id) {
698             case CODEC_ID_MJPEG:
699                 sc->track_type = 1;
700                 gxf->flags |= 0x00004000;
701                 media_info = 'J';
702                 break;
703             case CODEC_ID_MPEG1VIDEO:
704                 sc->track_type = 9;
705                 gxf->mpeg_tracks++;
706                 media_info = 'L';
707                 break;
708             case CODEC_ID_MPEG2VIDEO:
709                 sc->first_gop_closed = -1;
710                 sc->track_type = 4;
711                 gxf->mpeg_tracks++;
712                 gxf->flags |= 0x00008000;
713                 media_info = 'M';
714                 break;
715             case CODEC_ID_DVVIDEO:
716                 if (st->codec->pix_fmt == PIX_FMT_YUV422P) {
717                     sc->media_type += 2;
718                     sc->track_type = 6;
719                     gxf->flags |= 0x00002000;
720                     media_info = 'E';
721                 } else {
722                     sc->track_type = 5;
723                     gxf->flags |= 0x00001000;
724                     media_info = 'D';
725                 }
726                 break;
727             default:
728                 av_log(s, AV_LOG_ERROR, "video codec not supported\n");
729                 return -1;
730             }
731         }
732         /* FIXME first 10 audio tracks are 0 to 9 next 22 are A to V */
733         sc->media_info = media_info<<8 | ('0'+tracks[media_info]++);
734         sc->order = s->nb_streams - st->index;
735     }
736
737     if (ff_audio_interleave_init(s, GXF_samples_per_frame, (AVRational){ 1, 48000 }) < 0)
738         return -1;
739
740     gxf_init_timecode_track(&gxf->timecode_track, vsc);
741     gxf->flags |= 0x200000; // time code track is non-drop frame
742
743     gxf_write_map_packet(s, 0);
744     gxf_write_flt_packet(s);
745     gxf_write_umf_packet(s);
746
747     gxf->packet_count = 3;
748
749     put_flush_packet(pb);
750     return 0;
751 }
752
753 static int gxf_write_eos_packet(ByteIOContext *pb)
754 {
755     int64_t pos = url_ftell(pb);
756
757     gxf_write_packet_header(pb, PKT_EOS);
758     return updatePacketSize(pb, pos);
759 }
760
761 static int gxf_write_trailer(AVFormatContext *s)
762 {
763     GXFContext *gxf = s->priv_data;
764     ByteIOContext *pb = s->pb;
765     int64_t end;
766     int i;
767
768     ff_audio_interleave_close(s);
769
770     gxf_write_eos_packet(pb);
771     end = url_ftell(pb);
772     url_fseek(pb, 0, SEEK_SET);
773     /* overwrite map, flt and umf packets with new values */
774     gxf_write_map_packet(s, 1);
775     gxf_write_flt_packet(s);
776     gxf_write_umf_packet(s);
777     put_flush_packet(pb);
778     /* update duration in all map packets */
779     for (i = 1; i < gxf->map_offsets_nb; i++) {
780         url_fseek(pb, gxf->map_offsets[i], SEEK_SET);
781         gxf_write_map_packet(s, 1);
782         put_flush_packet(pb);
783     }
784
785     url_fseek(pb, end, SEEK_SET);
786
787     av_freep(&gxf->flt_entries);
788     av_freep(&gxf->map_offsets);
789
790     return 0;
791 }
792
793 static int gxf_parse_mpeg_frame(GXFStreamContext *sc, const uint8_t *buf, int size)
794 {
795     uint32_t c=-1;
796     int i;
797     for(i=0; i<size-4 && c!=0x100; i++){
798         c = (c<<8) + buf[i];
799         if(c == 0x1B8 && sc->first_gop_closed == -1) /* GOP start code */
800             sc->first_gop_closed= (buf[i+4]>>6)&1;
801     }
802     return (buf[i+1]>>3)&7;
803 }
804
805 static int gxf_write_media_preamble(AVFormatContext *s, AVPacket *pkt, int size)
806 {
807     GXFContext *gxf = s->priv_data;
808     ByteIOContext *pb = s->pb;
809     AVStream *st = s->streams[pkt->stream_index];
810     GXFStreamContext *sc = st->priv_data;
811     unsigned field_nb;
812     /* If the video is frame-encoded, the frame numbers shall be represented by
813      * even field numbers.
814      * see SMPTE360M-2004  6.4.2.1.3 Media field number */
815     if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
816         field_nb = gxf->nb_fields;
817     } else {
818         field_nb = av_rescale_rnd(pkt->dts, gxf->time_base.den,
819                                   (int64_t)48000*gxf->time_base.num, AV_ROUND_UP);
820     }
821
822     put_byte(pb, sc->media_type);
823     put_byte(pb, st->index);
824     put_be32(pb, field_nb);
825     if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
826         put_be16(pb, 0);
827         put_be16(pb, size / 2);
828     } else if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO) {
829         int frame_type = gxf_parse_mpeg_frame(sc, pkt->data, pkt->size);
830         if (frame_type == FF_I_TYPE) {
831             put_byte(pb, 0x0d);
832             sc->iframes++;
833         } else if (frame_type == FF_B_TYPE) {
834             put_byte(pb, 0x0f);
835             sc->bframes++;
836         } else {
837             put_byte(pb, 0x0e);
838             sc->pframes++;
839         }
840         put_be24(pb, size);
841     } else if (st->codec->codec_id == CODEC_ID_DVVIDEO) {
842         put_byte(pb, size / 4096);
843         put_be24(pb, 0);
844     } else
845         put_be32(pb, size);
846     put_be32(pb, field_nb);
847     put_byte(pb, 1); /* flags */
848     put_byte(pb, 0); /* reserved */
849     return 16;
850 }
851
852 static int gxf_write_packet(AVFormatContext *s, AVPacket *pkt)
853 {
854     GXFContext *gxf = s->priv_data;
855     ByteIOContext *pb = s->pb;
856     AVStream *st = s->streams[pkt->stream_index];
857     int64_t pos = url_ftell(pb);
858     int padding = 0;
859
860     gxf_write_packet_header(pb, PKT_MEDIA);
861     if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO && pkt->size % 4) /* MPEG-2 frames must be padded */
862         padding = 4 - pkt->size % 4;
863     else if (st->codec->codec_type == CODEC_TYPE_AUDIO)
864         padding = GXF_AUDIO_PACKET_SIZE - pkt->size;
865     gxf_write_media_preamble(s, pkt, pkt->size + padding);
866     put_buffer(pb, pkt->data, pkt->size);
867     gxf_write_padding(pb, padding);
868
869     if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
870         if (!(gxf->flt_entries_nb % 500)) {
871             gxf->flt_entries = av_realloc(gxf->flt_entries,
872                                           (gxf->flt_entries_nb+500)*sizeof(*gxf->flt_entries));
873             if (!gxf->flt_entries) {
874                 av_log(s, AV_LOG_ERROR, "could not reallocate flt entries\n");
875                 return -1;
876             }
877         }
878         gxf->flt_entries[gxf->flt_entries_nb++] = url_ftell(pb) / 1024;
879         gxf->nb_fields += 2; // count fields
880     }
881
882     updatePacketSize(pb, pos);
883
884     gxf->packet_count++;
885     if (gxf->packet_count == 100) {
886         gxf_write_map_packet(s, 0);
887         gxf->packet_count = 0;
888     }
889
890     put_flush_packet(pb);
891
892     return 0;
893 }
894
895 static int gxf_compare_field_nb(AVFormatContext *s, AVPacket *next, AVPacket *cur)
896 {
897     GXFContext *gxf = s->priv_data;
898     AVPacket *pkt[2] = { cur, next };
899     int i, field_nb[2];
900     GXFStreamContext *sc[2];
901
902     for (i = 0; i < 2; i++) {
903         AVStream *st = s->streams[pkt[i]->stream_index];
904         sc[i] = st->priv_data;
905         if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
906             field_nb[i] = av_rescale_rnd(pkt[i]->dts, gxf->time_base.den,
907                                          (int64_t)48000*gxf->time_base.num, AV_ROUND_UP);
908             field_nb[i] &= ~1; // compare against even field number because audio must be before video
909         } else
910             field_nb[i] = pkt[i]->dts; // dts are field based
911     }
912
913     return field_nb[1] > field_nb[0] ||
914         (field_nb[1] == field_nb[0] && sc[1]->order > sc[0]->order);
915 }
916
917 static int gxf_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush)
918 {
919     if (pkt && s->streams[pkt->stream_index]->codec->codec_type == CODEC_TYPE_VIDEO)
920         pkt->duration = 2; // enforce 2 fields
921     return ff_audio_rechunk_interleave(s, out, pkt, flush,
922                                av_interleave_packet_per_dts, gxf_compare_field_nb);
923 }
924
925 AVOutputFormat gxf_muxer = {
926     "gxf",
927     NULL_IF_CONFIG_SMALL("GXF format"),
928     NULL,
929     "gxf",
930     sizeof(GXFContext),
931     CODEC_ID_PCM_S16LE,
932     CODEC_ID_MPEG2VIDEO,
933     gxf_write_header,
934     gxf_write_packet,
935     gxf_write_trailer,
936     0,
937     NULL,
938     gxf_interleave_packet,
939 };