OSDN Git Service

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