]> git.sesse.net Git - ffmpeg/blob - libavformat/dvenc.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavformat / dvenc.c
1 /*
2  * General DV muxer/demuxer
3  * Copyright (c) 2003 Roman Shaposhnik
4  *
5  * Many thanks to Dan Dennedy <dan@dennedy.org> for providing wealth
6  * of DV technical info.
7  *
8  * Raw DV format
9  * Copyright (c) 2002 Fabrice Bellard
10  *
11  * 50 Mbps (DVCPRO50) support
12  * Copyright (c) 2006 Daniel Maas <dmaas@maasdigital.com>
13  *
14  * This file is part of FFmpeg.
15  *
16  * FFmpeg is free software; you can redistribute it and/or
17  * modify it under the terms of the GNU Lesser General Public
18  * License as published by the Free Software Foundation; either
19  * version 2.1 of the License, or (at your option) any later version.
20  *
21  * FFmpeg is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
24  * Lesser General Public License for more details.
25  *
26  * You should have received a copy of the GNU Lesser General Public
27  * License along with FFmpeg; if not, write to the Free Software
28  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29  */
30 #include <time.h>
31 #include <stdarg.h>
32
33 #include "avformat.h"
34 #include "internal.h"
35 #include "libavcodec/dvdata.h"
36 #include "dv.h"
37 #include "libavutil/fifo.h"
38 #include "libavutil/mathematics.h"
39 #include "libavutil/intreadwrite.h"
40 #include "libavutil/opt.h"
41 #include "libavutil/timecode.h"
42
43 struct DVMuxContext {
44     AVClass          *av_class;
45     const DVprofile*  sys;           /* current DV profile, e.g.: 525/60, 625/50 */
46     int               n_ast;         /* number of stereo audio streams (up to 2) */
47     AVStream         *ast[2];        /* stereo audio streams */
48     AVFifoBuffer     *audio_data[2]; /* FIFO for storing excessive amounts of PCM */
49     int               frames;        /* current frame number */
50     int64_t           start_time;    /* recording start time */
51     int               has_audio;     /* frame under contruction has audio */
52     int               has_video;     /* frame under contruction has video */
53     uint8_t           frame_buf[DV_MAX_FRAME_SIZE]; /* frame under contruction */
54     char             *tc_opt_str;    /* timecode option string */
55     AVTimecode        tc;            /* timecode context */
56 };
57
58 static const int dv_aaux_packs_dist[12][9] = {
59     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
60     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
61     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
62     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
63     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
64     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
65     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
66     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
67     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
68     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
69     { 0xff, 0xff, 0xff, 0x50, 0x51, 0x52, 0x53, 0xff, 0xff },
70     { 0x50, 0x51, 0x52, 0x53, 0xff, 0xff, 0xff, 0xff, 0xff },
71 };
72
73 static int dv_audio_frame_size(const DVprofile* sys, int frame)
74 {
75     return sys->audio_samples_dist[frame % (sizeof(sys->audio_samples_dist) /
76                                             sizeof(sys->audio_samples_dist[0]))];
77 }
78
79 static int dv_write_pack(enum dv_pack_type pack_id, DVMuxContext *c, uint8_t* buf, ...)
80 {
81     struct tm tc;
82     time_t ct;
83     uint32_t timecode;
84     va_list ap;
85
86     buf[0] = (uint8_t)pack_id;
87     switch (pack_id) {
88     case dv_timecode:
89         timecode  = av_timecode_get_smpte_from_framenum(&c->tc, c->frames);
90         timecode |= 1<<23 | 1<<15 | 1<<7 | 1<<6; // biphase and binary group flags
91         AV_WB32(buf + 1, timecode);
92         break;
93     case dv_audio_source:  /* AAUX source pack */
94         va_start(ap, buf);
95         buf[1] = (1 << 7) | /* locked mode -- SMPTE only supports locked mode */
96                  (1 << 6) | /* reserved -- always 1 */
97                  (dv_audio_frame_size(c->sys, c->frames) -
98                   c->sys->audio_min_samples[0]);
99                             /* # of samples      */
100         buf[2] = (0 << 7) | /* multi-stereo      */
101                  (0 << 5) | /* #of audio channels per block: 0 -- 1 channel */
102                  (0 << 4) | /* pair bit: 0 -- one pair of channels */
103                  !!va_arg(ap, int); /* audio mode        */
104         buf[3] = (1 << 7) | /* res               */
105                  (1 << 6) | /* multi-language flag */
106                  (c->sys->dsf << 5) | /*  system: 60fields/50fields */
107                  (c->sys->n_difchan & 2); /* definition: 0 -- 25Mbps, 2 -- 50Mbps */
108         buf[4] = (1 << 7) | /* emphasis: 1 -- off */
109                  (0 << 6) | /* emphasis time constant: 0 -- reserved */
110                  (0 << 3) | /* frequency: 0 -- 48kHz, 1 -- 44,1kHz, 2 -- 32kHz */
111                   0;        /* quantization: 0 -- 16bit linear, 1 -- 12bit nonlinear */
112         va_end(ap);
113         break;
114     case dv_audio_control:
115         buf[1] = (0 << 6) | /* copy protection: 0 -- unrestricted */
116                  (1 << 4) | /* input source: 1 -- digital input */
117                  (3 << 2) | /* compression: 3 -- no information */
118                   0;        /* misc. info/SMPTE emphasis off */
119         buf[2] = (1 << 7) | /* recording start point: 1 -- no */
120                  (1 << 6) | /* recording end point: 1 -- no */
121                  (1 << 3) | /* recording mode: 1 -- original */
122                   7;
123         buf[3] = (1 << 7) | /* direction: 1 -- forward */
124                  (c->sys->pix_fmt == PIX_FMT_YUV420P ? 0x20 : /* speed */
125                                                        c->sys->ltc_divisor * 4);
126         buf[4] = (1 << 7) | /* reserved -- always 1 */
127                   0x7f;     /* genre category */
128         break;
129     case dv_audio_recdate:
130     case dv_video_recdate:  /* VAUX recording date */
131         ct = c->start_time + av_rescale_rnd(c->frames, c->sys->time_base.num,
132                                             c->sys->time_base.den, AV_ROUND_DOWN);
133         ff_brktimegm(ct, &tc);
134         buf[1] = 0xff; /* ds, tm, tens of time zone, units of time zone */
135                        /* 0xff is very likely to be "unknown" */
136         buf[2] = (3 << 6) | /* reserved -- always 1 */
137                  ((tc.tm_mday / 10) << 4) | /* Tens of day */
138                  (tc.tm_mday % 10);         /* Units of day */
139         buf[3] = /* we set high 4 bits to 0, shouldn't we set them to week? */
140                  ((tc.tm_mon / 10) << 4) |    /* Tens of month */
141                  (tc.tm_mon  % 10);           /* Units of month */
142         buf[4] = (((tc.tm_year % 100) / 10) << 4) | /* Tens of year */
143                  (tc.tm_year % 10);                 /* Units of year */
144         break;
145     case dv_audio_rectime:  /* AAUX recording time */
146     case dv_video_rectime:  /* VAUX recording time */
147         ct = c->start_time + av_rescale_rnd(c->frames, c->sys->time_base.num,
148                                                        c->sys->time_base.den, AV_ROUND_DOWN);
149         ff_brktimegm(ct, &tc);
150         buf[1] = (3 << 6) | /* reserved -- always 1 */
151                  0x3f; /* tens of frame, units of frame: 0x3f - "unknown" ? */
152         buf[2] = (1 << 7) | /* reserved -- always 1 */
153                  ((tc.tm_sec / 10) << 4) | /* Tens of seconds */
154                  (tc.tm_sec % 10);         /* Units of seconds */
155         buf[3] = (1 << 7) | /* reserved -- always 1 */
156                  ((tc.tm_min / 10) << 4) | /* Tens of minutes */
157                  (tc.tm_min % 10);         /* Units of minutes */
158         buf[4] = (3 << 6) | /* reserved -- always 1 */
159                  ((tc.tm_hour / 10) << 4) | /* Tens of hours */
160                  (tc.tm_hour % 10);         /* Units of hours */
161         break;
162     default:
163         buf[1] = buf[2] = buf[3] = buf[4] = 0xff;
164     }
165     return 5;
166 }
167
168 static void dv_inject_audio(DVMuxContext *c, int channel, uint8_t* frame_ptr)
169 {
170     int i, j, d, of, size;
171     size = 4 * dv_audio_frame_size(c->sys, c->frames);
172     frame_ptr += channel * c->sys->difseg_size * 150 * 80;
173     for (i = 0; i < c->sys->difseg_size; i++) {
174         frame_ptr += 6 * 80; /* skip DIF segment header */
175         for (j = 0; j < 9; j++) {
176             dv_write_pack(dv_aaux_packs_dist[i][j], c, &frame_ptr[3], i >= c->sys->difseg_size/2);
177             for (d = 8; d < 80; d+=2) {
178                 of = c->sys->audio_shuffle[i][j] + (d - 8)/2 * c->sys->audio_stride;
179                 if (of*2 >= size)
180                     continue;
181
182                 frame_ptr[d]   = *av_fifo_peek2(c->audio_data[channel], of*2+1); // FIXME: maybe we have to admit
183                 frame_ptr[d+1] = *av_fifo_peek2(c->audio_data[channel], of*2);   //        that DV is a big-endian PCM
184             }
185             frame_ptr += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */
186         }
187     }
188 }
189
190 static void dv_inject_metadata(DVMuxContext *c, uint8_t* frame)
191 {
192     int j, k;
193     uint8_t* buf;
194
195     for (buf = frame; buf < frame + c->sys->frame_size; buf += 150 * 80) {
196         /* DV subcode: 2nd and 3d DIFs */
197         for (j = 80; j < 80 * 3; j += 80) {
198             for (k = 6; k < 6 * 8; k += 8)
199                 dv_write_pack(dv_timecode, c, &buf[j+k]);
200
201             if (((long)(buf-frame)/(c->sys->frame_size/(c->sys->difseg_size*c->sys->n_difchan))%c->sys->difseg_size) > 5) { /* FIXME: is this really needed ? */
202                 dv_write_pack(dv_video_recdate, c, &buf[j+14]);
203                 dv_write_pack(dv_video_rectime, c, &buf[j+22]);
204                 dv_write_pack(dv_video_recdate, c, &buf[j+38]);
205                 dv_write_pack(dv_video_rectime, c, &buf[j+46]);
206             }
207         }
208
209         /* DV VAUX: 4th, 5th and 6th 3DIFs */
210         for (j = 80*3 + 3; j < 80*6; j += 80) {
211             dv_write_pack(dv_video_recdate, c, &buf[j+5*2]);
212             dv_write_pack(dv_video_rectime, c, &buf[j+5*3]);
213             dv_write_pack(dv_video_recdate, c, &buf[j+5*11]);
214             dv_write_pack(dv_video_rectime, c, &buf[j+5*12]);
215         }
216     }
217 }
218
219 /*
220  * The following 3 functions constitute our interface to the world
221  */
222
223 static int dv_assemble_frame(DVMuxContext *c, AVStream* st,
224                              uint8_t* data, int data_size, uint8_t** frame)
225 {
226     int i, reqasize;
227
228     *frame = &c->frame_buf[0];
229     reqasize = 4 * dv_audio_frame_size(c->sys, c->frames);
230
231     switch (st->codec->codec_type) {
232     case AVMEDIA_TYPE_VIDEO:
233         /* FIXME: we have to have more sensible approach than this one */
234         if (c->has_video)
235             av_log(st->codec, AV_LOG_ERROR, "Can't process DV frame #%d. Insufficient audio data or severe sync problem.\n", c->frames);
236
237         memcpy(*frame, data, c->sys->frame_size);
238         c->has_video = 1;
239         break;
240     case AVMEDIA_TYPE_AUDIO:
241         for (i = 0; i < c->n_ast && st != c->ast[i]; i++);
242
243           /* FIXME: we have to have more sensible approach than this one */
244         if (av_fifo_size(c->audio_data[i]) + data_size >= 100*AVCODEC_MAX_AUDIO_FRAME_SIZE)
245             av_log(st->codec, AV_LOG_ERROR, "Can't process DV frame #%d. Insufficient video data or severe sync problem.\n", c->frames);
246         av_fifo_generic_write(c->audio_data[i], data, data_size, NULL);
247
248         /* Let us see if we've got enough audio for one DV frame. */
249         c->has_audio |= ((reqasize <= av_fifo_size(c->audio_data[i])) << i);
250
251         break;
252     default:
253         break;
254     }
255
256     /* Let us see if we have enough data to construct one DV frame. */
257     if (c->has_video == 1 && c->has_audio + 1 == 1 << c->n_ast) {
258         dv_inject_metadata(c, *frame);
259         c->has_audio = 0;
260         for (i=0; i < c->n_ast; i++) {
261             dv_inject_audio(c, i, *frame);
262             av_fifo_drain(c->audio_data[i], reqasize);
263             c->has_audio |= ((reqasize <= av_fifo_size(c->audio_data[i])) << i);
264         }
265
266         c->has_video = 0;
267
268         c->frames++;
269
270         return c->sys->frame_size;
271     }
272
273     return 0;
274 }
275
276 static DVMuxContext* dv_init_mux(AVFormatContext* s)
277 {
278     DVMuxContext *c = s->priv_data;
279     AVStream *vst = NULL;
280     AVDictionaryEntry *t;
281     int i;
282
283     /* we support at most 1 video and 2 audio streams */
284     if (s->nb_streams > 3)
285         return NULL;
286
287     c->n_ast  = 0;
288     c->ast[0] = c->ast[1] = NULL;
289
290     /* We have to sort out where audio and where video stream is */
291     for (i=0; i<s->nb_streams; i++) {
292         switch (s->streams[i]->codec->codec_type) {
293         case AVMEDIA_TYPE_VIDEO:
294             if (vst) return NULL;
295             vst = s->streams[i];
296             break;
297         case AVMEDIA_TYPE_AUDIO:
298             if (c->n_ast > 1) return NULL;
299             c->ast[c->n_ast++] = s->streams[i];
300             break;
301         default:
302             goto bail_out;
303         }
304     }
305
306     /* Some checks -- DV format is very picky about its incoming streams */
307     if (!vst || vst->codec->codec_id != CODEC_ID_DVVIDEO)
308         goto bail_out;
309     for (i=0; i<c->n_ast; i++) {
310         if (c->ast[i] && (c->ast[i]->codec->codec_id    != CODEC_ID_PCM_S16LE ||
311                           c->ast[i]->codec->sample_rate != 48000 ||
312                           c->ast[i]->codec->channels    != 2))
313             goto bail_out;
314     }
315     c->sys = avpriv_dv_codec_profile(vst->codec);
316     if (!c->sys)
317         goto bail_out;
318
319     if ((c->n_ast > 1) && (c->sys->n_difchan < 2)) {
320         /* only 1 stereo pair is allowed in 25Mbps mode */
321         goto bail_out;
322     }
323
324     /* Ok, everything seems to be in working order */
325     c->frames     = 0;
326     c->has_audio  = 0;
327     c->has_video  = 0;
328     if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
329         c->start_time = ff_iso8601_to_unix_time(t->value);
330
331     for (i=0; i < c->n_ast; i++) {
332         if (c->ast[i] && !(c->audio_data[i]=av_fifo_alloc(100*AVCODEC_MAX_AUDIO_FRAME_SIZE))) {
333             while (i > 0) {
334                 i--;
335                 av_fifo_free(c->audio_data[i]);
336             }
337             goto bail_out;
338         }
339     }
340
341     return c;
342
343 bail_out:
344     return NULL;
345 }
346
347 static void dv_delete_mux(DVMuxContext *c)
348 {
349     int i;
350     for (i=0; i < c->n_ast; i++)
351         av_fifo_free(c->audio_data[i]);
352 }
353
354 static int dv_write_header(AVFormatContext *s)
355 {
356     AVRational rate;
357     DVMuxContext *dvc = s->priv_data;
358
359     if (!dv_init_mux(s)) {
360         av_log(s, AV_LOG_ERROR, "Can't initialize DV format!\n"
361                     "Make sure that you supply exactly two streams:\n"
362                     "     video: 25fps or 29.97fps, audio: 2ch/48kHz/PCM\n"
363                     "     (50Mbps allows an optional second audio stream)\n");
364         return -1;
365     }
366     rate.num = dvc->sys->ltc_divisor;
367     rate.den = 1;
368     if (dvc->tc_opt_str)
369         return av_timecode_init_from_string(&dvc->tc, rate,
370                                             dvc->tc_opt_str, s);
371     return av_timecode_init(&dvc->tc, rate, 0, 0, s);
372 }
373
374 static int dv_write_packet(struct AVFormatContext *s, AVPacket *pkt)
375 {
376     uint8_t* frame;
377     int fsize;
378
379     fsize = dv_assemble_frame(s->priv_data, s->streams[pkt->stream_index],
380                               pkt->data, pkt->size, &frame);
381     if (fsize > 0) {
382         avio_write(s->pb, frame, fsize);
383         avio_flush(s->pb);
384     }
385     return 0;
386 }
387
388 /*
389  * We might end up with some extra A/V data without matching counterpart.
390  * E.g. video data without enough audio to write the complete frame.
391  * Currently we simply drop the last frame. I don't know whether this
392  * is the best strategy of all
393  */
394 static int dv_write_trailer(struct AVFormatContext *s)
395 {
396     dv_delete_mux(s->priv_data);
397     return 0;
398 }
399
400 static const AVClass class = {
401     .class_name = "dv",
402     .item_name  = av_default_item_name,
403     .version    = LIBAVUTIL_VERSION_INT,
404     .option     = (const AVOption[]){
405         {AV_TIMECODE_OPTION(DVMuxContext, tc_opt_str, AV_OPT_FLAG_ENCODING_PARAM)},
406         {NULL},
407     },
408 };
409
410 AVOutputFormat ff_dv_muxer = {
411     .name              = "dv",
412     .long_name         = NULL_IF_CONFIG_SMALL("DV video format"),
413     .extensions        = "dv",
414     .priv_data_size    = sizeof(DVMuxContext),
415     .audio_codec       = CODEC_ID_PCM_S16LE,
416     .video_codec       = CODEC_ID_DVVIDEO,
417     .write_header      = dv_write_header,
418     .write_packet      = dv_write_packet,
419     .write_trailer     = dv_write_trailer,
420     .priv_class        = &class,
421 };