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