b7b0c9c7903f0aec424bb454f32e5146316ea5aa
[libav.git] / libavformat / nutenc.c
1 /*
2 * nut muxer
3 * Copyright (c) 2004-2007 Michael Niedermayer
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 <stdint.h>
23
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/mathematics.h"
26 #include "libavutil/tree.h"
27 #include "libavutil/dict.h"
28 #include "libavutil/time.h"
29 #include "libavutil/opt.h"
30 #include "libavcodec/mpegaudiodata.h"
31 #include "nut.h"
32 #include "internal.h"
33 #include "avio_internal.h"
34 #include "riff.h"
35
36 static int find_expected_header(AVCodecContext *c, int size, int key_frame,
37 uint8_t out[64])
38 {
39 int sample_rate = c->sample_rate;
40
41 if (size > 4096)
42 return 0;
43
44 AV_WB24(out, 1);
45
46 if (c->codec_id == AV_CODEC_ID_MPEG4) {
47 if (key_frame) {
48 return 3;
49 } else {
50 out[3] = 0xB6;
51 return 4;
52 }
53 } else if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO ||
54 c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
55 return 3;
56 } else if (c->codec_id == AV_CODEC_ID_H264) {
57 return 3;
58 } else if (c->codec_id == AV_CODEC_ID_MP3 ||
59 c->codec_id == AV_CODEC_ID_MP2) {
60 int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
61 int layer = c->codec_id == AV_CODEC_ID_MP3 ? 3 : 2;
62 unsigned int header = 0xFFF00000;
63
64 lsf = sample_rate < (24000 + 32000) / 2;
65 mpeg25 = sample_rate < (12000 + 16000) / 2;
66 sample_rate <<= lsf + mpeg25;
67 if (sample_rate < (32000 + 44100) / 2)
68 sample_rate_index = 2;
69 else if (sample_rate < (44100 + 48000) / 2)
70 sample_rate_index = 0;
71 else
72 sample_rate_index = 1;
73
74 sample_rate = avpriv_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
75
76 for (bitrate_index = 2; bitrate_index < 30; bitrate_index++) {
77 frame_size =
78 avpriv_mpa_bitrate_tab[lsf][layer - 1][bitrate_index >> 1];
79 frame_size = (frame_size * 144000) / (sample_rate << lsf) +
80 (bitrate_index & 1);
81
82 if (frame_size == size)
83 break;
84 }
85
86 header |= (!lsf) << 19;
87 header |= (4 - layer) << 17;
88 header |= 1 << 16; //no crc
89 AV_WB32(out, header);
90 if (size <= 0)
91 return 2; //we guess there is no crc, if there is one the user clearly does not care about overhead
92 if (bitrate_index == 30)
93 return -1; //something is wrong ...
94
95 header |= (bitrate_index >> 1) << 12;
96 header |= sample_rate_index << 10;
97 header |= (bitrate_index & 1) << 9;
98
99 return 2; //FIXME actually put the needed ones in build_elision_headers()
100 //return 3; //we guess that the private bit is not set
101 //FIXME the above assumptions should be checked, if these turn out false too often something should be done
102 }
103 return 0;
104 }
105
106 static int find_header_idx(AVFormatContext *s, AVCodecContext *c, int size,
107 int frame_type)
108 {
109 NUTContext *nut = s->priv_data;
110 uint8_t out[64];
111 int i;
112 int len = find_expected_header(c, size, frame_type, out);
113
114 for (i = 1; i < nut->header_count; i++) {
115 if (len == nut->header_len[i] && !memcmp(out, nut->header[i], len)) {
116 return i;
117 }
118 }
119
120 return 0;
121 }
122
123 static void build_elision_headers(AVFormatContext *s)
124 {
125 NUTContext *nut = s->priv_data;
126 int i;
127 //FIXME this is lame
128 //FIXME write a 2pass mode to find the maximal headers
129 static const uint8_t headers[][5] = {
130 { 3, 0x00, 0x00, 0x01 },
131 { 4, 0x00, 0x00, 0x01, 0xB6},
132 { 2, 0xFF, 0xFA }, //mp3+crc
133 { 2, 0xFF, 0xFB }, //mp3
134 { 2, 0xFF, 0xFC }, //mp2+crc
135 { 2, 0xFF, 0xFD }, //mp2
136 };
137
138 nut->header_count = 7;
139 for (i = 1; i < nut->header_count; i++) {
140 nut->header_len[i] = headers[i - 1][0];
141 nut->header[i] = &headers[i - 1][1];
142 }
143 }
144
145 static void build_frame_code(AVFormatContext *s)
146 {
147 NUTContext *nut = s->priv_data;
148 int key_frame, index, pred, stream_id;
149 int start = 1;
150 int end = 254;
151 int keyframe_0_esc = s->nb_streams > 2;
152 int pred_table[10];
153 FrameCode *ft;
154
155 ft = &nut->frame_code[start];
156 ft->flags = FLAG_CODED;
157 ft->size_mul = 1;
158 ft->pts_delta = 1;
159 start++;
160
161 if (keyframe_0_esc) {
162 /* keyframe = 0 escape */
163 FrameCode *ft = &nut->frame_code[start];
164 ft->flags = FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
165 ft->size_mul = 1;
166 start++;
167 }
168
169 for (stream_id = 0; stream_id < s->nb_streams; stream_id++) {
170 int start2 = start + (end - start) * stream_id / s->nb_streams;
171 int end2 = start + (end - start) * (stream_id + 1) / s->nb_streams;
172 AVCodecContext *codec = s->streams[stream_id]->codec;
173 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec->codec_id);
174 int is_audio = codec->codec_type == AVMEDIA_TYPE_AUDIO;
175 int intra_only = /*codec->intra_only || */ is_audio;
176 int pred_count;
177
178 for (key_frame = 0; key_frame < 2; key_frame++) {
179 if (!intra_only || !keyframe_0_esc || key_frame != 0) {
180 FrameCode *ft = &nut->frame_code[start2];
181 ft->flags = FLAG_KEY * key_frame;
182 ft->flags |= FLAG_SIZE_MSB | FLAG_CODED_PTS;
183 ft->stream_id = stream_id;
184 ft->size_mul = 1;
185 if (is_audio)
186 ft->header_idx = find_header_idx(s, codec, -1, key_frame);
187 start2++;
188 }
189 }
190
191 key_frame = intra_only;
192 if (is_audio) {
193 int frame_bytes = codec->frame_size * (int64_t)codec->bit_rate /
194 (8 * codec->sample_rate);
195 int pts;
196 for (pts = 0; pts < 2; pts++)
197 for (pred = 0; pred < 2; pred++) {
198 FrameCode *ft = &nut->frame_code[start2];
199 ft->flags = FLAG_KEY * key_frame;
200 ft->stream_id = stream_id;
201 ft->size_mul = frame_bytes + 2;
202 ft->size_lsb = frame_bytes + pred;
203 ft->pts_delta = pts;
204 ft->header_idx = find_header_idx(s, codec, frame_bytes + pred, key_frame);
205 start2++;
206 }
207 } else {
208 FrameCode *ft = &nut->frame_code[start2];
209 ft->flags = FLAG_KEY | FLAG_SIZE_MSB;
210 ft->stream_id = stream_id;
211 ft->size_mul = 1;
212 ft->pts_delta = 1;
213 start2++;
214 }
215
216 if (desc && desc->props & AV_CODEC_PROP_REORDER) {
217 pred_count = 5;
218 pred_table[0] = -2;
219 pred_table[1] = -1;
220 pred_table[2] = 1;
221 pred_table[3] = 3;
222 pred_table[4] = 4;
223 } else if (codec->codec_id == AV_CODEC_ID_VORBIS) {
224 pred_count = 3;
225 pred_table[0] = 2;
226 pred_table[1] = 9;
227 pred_table[2] = 16;
228 } else {
229 pred_count = 1;
230 pred_table[0] = 1;
231 }
232
233 for (pred = 0; pred < pred_count; pred++) {
234 int start3 = start2 + (end2 - start2) * pred / pred_count;
235 int end3 = start2 + (end2 - start2) * (pred + 1) / pred_count;
236
237 for (index = start3; index < end3; index++) {
238 FrameCode *ft = &nut->frame_code[index];
239 ft->flags = FLAG_KEY * key_frame;
240 ft->flags |= FLAG_SIZE_MSB;
241 ft->stream_id = stream_id;
242 //FIXME use single byte size and pred from last
243 ft->size_mul = end3 - start3;
244 ft->size_lsb = index - start3;
245 ft->pts_delta = pred_table[pred];
246 if (is_audio)
247 ft->header_idx = find_header_idx(s, codec, -1, key_frame);
248 }
249 }
250 }
251 memmove(&nut->frame_code['N' + 1], &nut->frame_code['N'],
252 sizeof(FrameCode) * (255 - 'N'));
253 nut->frame_code[0].flags =
254 nut->frame_code[255].flags =
255 nut->frame_code['N'].flags = FLAG_INVALID;
256 }
257
258 static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc,
259 uint64_t val)
260 {
261 val *= nut->time_base_count;
262 val += time_base - nut->time_base;
263 ff_put_v(bc, val);
264 }
265 /**
266 * Store a string as vb.
267 */
268 static void put_str(AVIOContext *bc, const char *string)
269 {
270 int len = strlen(string);
271
272 ff_put_v(bc, len);
273 avio_write(bc, string, len);
274 }
275
276 static void put_s(AVIOContext *bc, int64_t val)
277 {
278 ff_put_v(bc, 2 * FFABS(val) - (val > 0));
279 }
280
281 #ifdef TRACE
282 static inline void ff_put_v_trace(AVIOContext *bc, uint64_t v, const char *file,
283 const char *func, int line)
284 {
285 av_log(NULL, AV_LOG_DEBUG, "ff_put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
286
287 ff_put_v(bc, v);
288 }
289
290 static inline void put_s_trace(AVIOContext *bc, int64_t v, const char *file,
291 const char *func, int line)
292 {
293 av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
294
295 put_s(bc, v);
296 }
297 #define ff_put_v(bc, v) ff_put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
298 #define put_s(bc, v) put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
299 #endif
300
301 //FIXME remove calculate_checksum
302 static void put_packet(NUTContext *nut, AVIOContext *bc, AVIOContext *dyn_bc,
303 int calculate_checksum, uint64_t startcode)
304 {
305 uint8_t *dyn_buf = NULL;
306 int dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
307 int forw_ptr = dyn_size + 4 * calculate_checksum;
308
309 if (forw_ptr > 4096)
310 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
311 avio_wb64(bc, startcode);
312 ff_put_v(bc, forw_ptr);
313 if (forw_ptr > 4096)
314 avio_wl32(bc, ffio_get_checksum(bc));
315
316 if (calculate_checksum)
317 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
318 avio_write(bc, dyn_buf, dyn_size);
319 if (calculate_checksum)
320 avio_wl32(bc, ffio_get_checksum(bc));
321
322 av_free(dyn_buf);
323 }
324
325 static void write_mainheader(NUTContext *nut, AVIOContext *bc)
326 {
327 int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields,
328 tmp_head_idx;
329 int64_t tmp_match;
330
331 ff_put_v(bc, nut->version);
332 ff_put_v(bc, nut->avf->nb_streams);
333 ff_put_v(bc, nut->max_distance);
334 ff_put_v(bc, nut->time_base_count);
335
336 for (i = 0; i < nut->time_base_count; i++) {
337 ff_put_v(bc, nut->time_base[i].num);
338 ff_put_v(bc, nut->time_base[i].den);
339 }
340
341 tmp_pts = 0;
342 tmp_mul = 1;
343 tmp_stream = 0;
344 tmp_match = 1 - (1LL << 62);
345 tmp_head_idx = 0;
346 for (i = 0; i < 256; ) {
347 tmp_fields = 0;
348 tmp_size = 0;
349 // tmp_res=0;
350 if (tmp_pts != nut->frame_code[i].pts_delta)
351 tmp_fields = 1;
352 if (tmp_mul != nut->frame_code[i].size_mul)
353 tmp_fields = 2;
354 if (tmp_stream != nut->frame_code[i].stream_id)
355 tmp_fields = 3;
356 if (tmp_size != nut->frame_code[i].size_lsb)
357 tmp_fields = 4;
358 // if(tmp_res != nut->frame_code[i].res ) tmp_fields=5;
359 if (tmp_head_idx != nut->frame_code[i].header_idx)
360 tmp_fields = 8;
361
362 tmp_pts = nut->frame_code[i].pts_delta;
363 tmp_flags = nut->frame_code[i].flags;
364 tmp_stream = nut->frame_code[i].stream_id;
365 tmp_mul = nut->frame_code[i].size_mul;
366 tmp_size = nut->frame_code[i].size_lsb;
367 // tmp_res = nut->frame_code[i].res;
368 tmp_head_idx = nut->frame_code[i].header_idx;
369
370 for (j = 0; i < 256; j++, i++) {
371 if (i == 'N') {
372 j--;
373 continue;
374 }
375 if (nut->frame_code[i].pts_delta != tmp_pts ||
376 nut->frame_code[i].flags != tmp_flags ||
377 nut->frame_code[i].stream_id != tmp_stream ||
378 nut->frame_code[i].size_mul != tmp_mul ||
379 nut->frame_code[i].size_lsb != tmp_size + j ||
380 // nut->frame_code[i].res != tmp_res ||
381 nut->frame_code[i].header_idx != tmp_head_idx)
382 break;
383 }
384 if (j != tmp_mul - tmp_size)
385 tmp_fields = 6;
386
387 ff_put_v(bc, tmp_flags);
388 ff_put_v(bc, tmp_fields);
389 if (tmp_fields > 0)
390 put_s(bc, tmp_pts);
391 if (tmp_fields > 1)
392 ff_put_v(bc, tmp_mul);
393 if (tmp_fields > 2)
394 ff_put_v(bc, tmp_stream);
395 if (tmp_fields > 3)
396 ff_put_v(bc, tmp_size);
397 if (tmp_fields > 4)
398 ff_put_v(bc, 0 /*tmp_res*/);
399 if (tmp_fields > 5)
400 ff_put_v(bc, j);
401 if (tmp_fields > 6)
402 ff_put_v(bc, tmp_match);
403 if (tmp_fields > 7)
404 ff_put_v(bc, tmp_head_idx);
405 }
406 ff_put_v(bc, nut->header_count - 1);
407 for (i = 1; i < nut->header_count; i++) {
408 ff_put_v(bc, nut->header_len[i]);
409 avio_write(bc, nut->header[i], nut->header_len[i]);
410 }
411 // flags had been effectively introduced in version 4
412 if (nut->version > NUT_STABLE_VERSION)
413 ff_put_v(bc, nut->flags);
414 }
415
416 static int write_streamheader(AVFormatContext *avctx, AVIOContext *bc,
417 AVStream *st, int i)
418 {
419 NUTContext *nut = avctx->priv_data;
420 AVCodecContext *codec = st->codec;
421 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec->codec_id);
422 unsigned codec_tag = av_codec_get_tag(ff_nut_codec_tags, codec->codec_id);
423
424 ff_put_v(bc, i);
425 switch (codec->codec_type) {
426 case AVMEDIA_TYPE_VIDEO:
427 ff_put_v(bc, 0);
428 break;
429 case AVMEDIA_TYPE_AUDIO:
430 ff_put_v(bc, 1);
431 break;
432 case AVMEDIA_TYPE_SUBTITLE:
433 ff_put_v(bc, 2);
434 break;
435 default:
436 ff_put_v(bc, 3);
437 break;
438 }
439 ff_put_v(bc, 4);
440
441 if (!codec_tag || codec->codec_id == AV_CODEC_ID_RAWVIDEO)
442 codec_tag = codec->codec_tag;
443
444 if (codec_tag) {
445 avio_wl32(bc, codec_tag);
446 } else {
447 av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
448 return AVERROR(EINVAL);
449 }
450
451 ff_put_v(bc, nut->stream[i].time_base - nut->time_base);
452 ff_put_v(bc, nut->stream[i].msb_pts_shift);
453 ff_put_v(bc, nut->stream[i].max_pts_distance);
454 ff_put_v(bc, (desc && desc->props & AV_CODEC_PROP_REORDER) ? 16 : 0);
455 avio_w8(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
456
457 ff_put_v(bc, codec->extradata_size);
458 avio_write(bc, codec->extradata, codec->extradata_size);
459
460 switch (codec->codec_type) {
461 case AVMEDIA_TYPE_AUDIO:
462 ff_put_v(bc, codec->sample_rate);
463 ff_put_v(bc, 1);
464 ff_put_v(bc, codec->channels);
465 break;
466 case AVMEDIA_TYPE_VIDEO:
467 ff_put_v(bc, codec->width);
468 ff_put_v(bc, codec->height);
469
470 if (st->sample_aspect_ratio.num <= 0 ||
471 st->sample_aspect_ratio.den <= 0) {
472 ff_put_v(bc, 0);
473 ff_put_v(bc, 0);
474 } else {
475 ff_put_v(bc, st->sample_aspect_ratio.num);
476 ff_put_v(bc, st->sample_aspect_ratio.den);
477 }
478 ff_put_v(bc, 0); /* csp type -- unknown */
479 break;
480 default:
481 break;
482 }
483 return 0;
484 }
485
486 static int add_info(AVIOContext *bc, const char *type, const char *value)
487 {
488 put_str(bc, type);
489 put_s(bc, -1);
490 put_str(bc, value);
491 return 1;
492 }
493
494 static int write_globalinfo(NUTContext *nut, AVIOContext *bc)
495 {
496 AVFormatContext *s = nut->avf;
497 AVDictionaryEntry *t = NULL;
498 AVIOContext *dyn_bc;
499 uint8_t *dyn_buf = NULL;
500 int count = 0, dyn_size;
501 int ret = avio_open_dyn_buf(&dyn_bc);
502 if (ret < 0)
503 return ret;
504
505 while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
506 count += add_info(dyn_bc, t->key, t->value);
507
508 ff_put_v(bc, 0); //stream_if_plus1
509 ff_put_v(bc, 0); //chapter_id
510 ff_put_v(bc, 0); //timestamp_start
511 ff_put_v(bc, 0); //length
512
513 ff_put_v(bc, count);
514
515 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
516 avio_write(bc, dyn_buf, dyn_size);
517 av_free(dyn_buf);
518 return 0;
519 }
520
521 static int write_streaminfo(NUTContext *nut, AVIOContext *bc, int stream_id){
522 AVFormatContext *s= nut->avf;
523 AVStream* st = s->streams[stream_id];
524 AVIOContext *dyn_bc;
525 uint8_t *dyn_buf=NULL;
526 int count=0, dyn_size, i;
527 int ret = avio_open_dyn_buf(&dyn_bc);
528 if(ret < 0)
529 return ret;
530
531 for (i=0; ff_nut_dispositions[i].flag; ++i) {
532 if (st->disposition & ff_nut_dispositions[i].flag)
533 count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
534 }
535 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
536
537 if (count) {
538 ff_put_v(bc, stream_id + 1); //stream_id_plus1
539 ff_put_v(bc, 0); //chapter_id
540 ff_put_v(bc, 0); //timestamp_start
541 ff_put_v(bc, 0); //length
542
543 ff_put_v(bc, count);
544
545 avio_write(bc, dyn_buf, dyn_size);
546 }
547
548 av_free(dyn_buf);
549 return count;
550 }
551
552 static int write_chapter(NUTContext *nut, AVIOContext *bc, int id)
553 {
554 AVIOContext *dyn_bc;
555 uint8_t *dyn_buf = NULL;
556 AVDictionaryEntry *t = NULL;
557 AVChapter *ch = nut->avf->chapters[id];
558 int ret, dyn_size, count = 0;
559
560 ret = avio_open_dyn_buf(&dyn_bc);
561 if (ret < 0)
562 return ret;
563
564 ff_put_v(bc, 0); // stream_id_plus1
565 put_s(bc, id + 1); // chapter_id
566 put_tt(nut, nut->chapter[id].time_base, bc, ch->start); // chapter_start
567 ff_put_v(bc, ch->end - ch->start); // chapter_len
568
569 while ((t = av_dict_get(ch->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
570 count += add_info(dyn_bc, t->key, t->value);
571
572 ff_put_v(bc, count);
573
574 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
575 avio_write(bc, dyn_buf, dyn_size);
576 av_freep(&dyn_buf);
577 return 0;
578 }
579
580 static int write_headers(AVFormatContext *avctx, AVIOContext *bc)
581 {
582 NUTContext *nut = avctx->priv_data;
583 AVIOContext *dyn_bc;
584 int i, ret;
585
586 ff_metadata_conv_ctx(avctx, ff_nut_metadata_conv, NULL);
587
588 ret = avio_open_dyn_buf(&dyn_bc);
589 if (ret < 0)
590 return ret;
591 write_mainheader(nut, dyn_bc);
592 put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
593
594 for (i = 0; i < nut->avf->nb_streams; i++) {
595 ret = avio_open_dyn_buf(&dyn_bc);
596 if (ret < 0)
597 return ret;
598 ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i);
599 if (ret < 0)
600 return ret;
601 put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
602 }
603
604 ret = avio_open_dyn_buf(&dyn_bc);
605 if (ret < 0)
606 return ret;
607 write_globalinfo(nut, dyn_bc);
608 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
609
610 for (i = 0; i < nut->avf->nb_streams; i++) {
611 ret = avio_open_dyn_buf(&dyn_bc);
612 if (ret < 0)
613 return ret;
614 ret = write_streaminfo(nut, dyn_bc, i);
615 if (ret < 0)
616 return ret;
617 if (ret > 0)
618 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
619 else
620 ffio_free_dyn_buf(&dyn_bc);
621 }
622
623 for (i = 0; i < nut->avf->nb_chapters; i++) {
624 ret = avio_open_dyn_buf(&dyn_bc);
625 if (ret < 0)
626 return ret;
627 ret = write_chapter(nut, dyn_bc, i);
628 if (ret < 0) {
629 ffio_free_dyn_buf(&dyn_bc);
630 return ret;
631 }
632 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
633 }
634
635 nut->last_syncpoint_pos = INT_MIN;
636 nut->header_count++;
637 return 0;
638 }
639
640 static int nut_write_header(AVFormatContext *s)
641 {
642 NUTContext *nut = s->priv_data;
643 AVIOContext *bc = s->pb;
644 int i, j, ret;
645
646 nut->avf = s;
647
648 nut->version = NUT_STABLE_VERSION + !!nut->flags;
649 if (nut->flags && s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
650 av_log(s, AV_LOG_ERROR,
651 "The additional syncpoint modes require version %d, "
652 "that is currently not finalized, "
653 "please set -f_strict experimental in order to enable it.\n",
654 nut->version);
655 return AVERROR_EXPERIMENTAL;
656 }
657
658 nut->stream = av_mallocz(sizeof(StreamContext) * s->nb_streams);
659 if (s->nb_chapters)
660 nut->chapter = av_mallocz(sizeof(ChapterContext) * s->nb_chapters);
661 nut->time_base = av_mallocz(sizeof(AVRational) * (s->nb_streams +
662 s->nb_chapters));
663 if (!nut->stream || (s->nb_chapters && !nut->chapter) || !nut->time_base) {
664 av_freep(&nut->stream);
665 av_freep(&nut->chapter);
666 av_freep(&nut->time_base);
667 return AVERROR(ENOMEM);
668 }
669
670 for (i = 0; i < s->nb_streams; i++) {
671 AVStream *st = s->streams[i];
672 int ssize;
673 AVRational time_base;
674 ff_parse_specific_params(st, &time_base.den, &ssize,
675 &time_base.num);
676
677 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
678
679 for (j = 0; j < nut->time_base_count; j++)
680 if (!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))) {
681 break;
682 }
683 nut->time_base[j] = time_base;
684 nut->stream[i].time_base = &nut->time_base[j];
685 if (j == nut->time_base_count)
686 nut->time_base_count++;
687
688 if (INT64_C(1000) * time_base.num >= time_base.den)
689 nut->stream[i].msb_pts_shift = 7;
690 else
691 nut->stream[i].msb_pts_shift = 14;
692 nut->stream[i].max_pts_distance =
693 FFMAX(time_base.den, time_base.num) / time_base.num;
694 }
695
696 for (i = 0; i < s->nb_chapters; i++) {
697 AVChapter *ch = s->chapters[i];
698
699 for (j = 0; j < nut->time_base_count; j++)
700 if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
701 break;
702
703 nut->time_base[j] = ch->time_base;
704 nut->chapter[i].time_base = &nut->time_base[j];
705 if (j == nut->time_base_count)
706 nut->time_base_count++;
707 }
708
709 nut->max_distance = MAX_DISTANCE;
710 build_elision_headers(s);
711 build_frame_code(s);
712 assert(nut->frame_code['N'].flags == FLAG_INVALID);
713
714 avio_write(bc, ID_STRING, strlen(ID_STRING));
715 avio_w8(bc, 0);
716
717 if ((ret = write_headers(s, bc)) < 0)
718 return ret;
719
720 avio_flush(bc);
721
722 //FIXME index
723
724 return 0;
725 }
726
727 static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc,
728 AVPacket *pkt)
729 {
730 int flags = 0;
731
732 if (pkt->flags & AV_PKT_FLAG_KEY)
733 flags |= FLAG_KEY;
734 if (pkt->stream_index != fc->stream_id)
735 flags |= FLAG_STREAM_ID;
736 if (pkt->size / fc->size_mul)
737 flags |= FLAG_SIZE_MSB;
738 if (pkt->pts - nus->last_pts != fc->pts_delta)
739 flags |= FLAG_CODED_PTS;
740 if (pkt->size > 2 * nut->max_distance)
741 flags |= FLAG_CHECKSUM;
742 if (FFABS(pkt->pts - nus->last_pts) > nus->max_pts_distance)
743 flags |= FLAG_CHECKSUM;
744 if (pkt->size < nut->header_len[fc->header_idx] ||
745 (pkt->size > 4096 && fc->header_idx) ||
746 memcmp(pkt->data, nut->header[fc->header_idx],
747 nut->header_len[fc->header_idx]))
748 flags |= FLAG_HEADER_IDX;
749
750 return flags | (fc->flags & FLAG_CODED);
751 }
752
753 static int find_best_header_idx(NUTContext *nut, AVPacket *pkt)
754 {
755 int i;
756 int best_i = 0;
757 int best_len = 0;
758
759 if (pkt->size > 4096)
760 return 0;
761
762 for (i = 1; i < nut->header_count; i++)
763 if (pkt->size >= nut->header_len[i]
764 && nut->header_len[i] > best_len
765 && !memcmp(pkt->data, nut->header[i], nut->header_len[i])) {
766 best_i = i;
767 best_len = nut->header_len[i];
768 }
769 return best_i;
770 }
771
772 static int nut_write_packet(AVFormatContext *s, AVPacket *pkt)
773 {
774 NUTContext *nut = s->priv_data;
775 StreamContext *nus = &nut->stream[pkt->stream_index];
776 AVIOContext *bc = s->pb, *dyn_bc;
777 FrameCode *fc;
778 int64_t coded_pts;
779 int best_length, frame_code, flags, needed_flags, i, header_idx,
780 best_header_idx;
781 int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
782 int store_sp = 0;
783 int ret;
784
785 if (pkt->pts < 0) {
786 av_log(s, AV_LOG_ERROR,
787 "Negative pts not supported stream %d, pts %"PRId64"\n",
788 pkt->stream_index, pkt->pts);
789 return AVERROR_INVALIDDATA;
790 }
791
792 if (1LL << (20 + 3 * nut->header_count) <= avio_tell(bc))
793 write_headers(s, bc);
794
795 if (key_frame && !(nus->last_flags & FLAG_KEY))
796 store_sp = 1;
797
798 if (pkt->size + 30 /*FIXME check*/ + avio_tell(bc) >=
799 nut->last_syncpoint_pos + nut->max_distance)
800 store_sp = 1;
801
802 //FIXME: Ensure store_sp is 1 in the first place.
803
804 if (store_sp &&
805 (!(nut->flags & NUT_PIPE) || nut->last_syncpoint_pos == INT_MIN)) {
806 Syncpoint *sp, dummy = { .pos = INT64_MAX };
807
808 ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
809 for (i = 0; i < s->nb_streams; i++) {
810 AVStream *st = s->streams[i];
811 int64_t dts_tb = av_rescale_rnd(pkt->dts,
812 nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
813 nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
814 AV_ROUND_DOWN);
815 int index = av_index_search_timestamp(st, dts_tb,
816 AVSEEK_FLAG_BACKWARD);
817 if (index >= 0)
818 dummy.pos = FFMIN(dummy.pos, st->index_entries[index].pos);
819 }
820 if (dummy.pos == INT64_MAX)
821 dummy.pos = 0;
822 sp = av_tree_find(nut->syncpoints, &dummy, (void *)ff_nut_sp_pos_cmp,
823 NULL);
824
825 nut->last_syncpoint_pos = avio_tell(bc);
826 ret = avio_open_dyn_buf(&dyn_bc);
827 if (ret < 0)
828 return ret;
829 put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
830 ff_put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos) >> 4 : 0);
831
832 if (nut->flags & NUT_BROADCAST) {
833 put_tt(nut, nus->time_base, dyn_bc,
834 av_rescale_q(av_gettime(), AV_TIME_BASE_Q, *nus->time_base));
835 }
836 put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
837
838 if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0 /*unused*/, pkt->dts)) < 0)
839 return ret;
840 }
841 assert(nus->last_pts != AV_NOPTS_VALUE);
842
843 coded_pts = pkt->pts & ((1 << nus->msb_pts_shift) - 1);
844 if (ff_lsb2full(nus, coded_pts) != pkt->pts)
845 coded_pts = pkt->pts + (1 << nus->msb_pts_shift);
846
847 best_header_idx = find_best_header_idx(nut, pkt);
848
849 best_length = INT_MAX;
850 frame_code = -1;
851 for (i = 0; i < 256; i++) {
852 int length = 0;
853 FrameCode *fc = &nut->frame_code[i];
854 int flags = fc->flags;
855
856 if (flags & FLAG_INVALID)
857 continue;
858 needed_flags = get_needed_flags(nut, nus, fc, pkt);
859
860 if (flags & FLAG_CODED) {
861 length++;
862 flags = needed_flags;
863 }
864
865 if ((flags & needed_flags) != needed_flags)
866 continue;
867
868 if ((flags ^ needed_flags) & FLAG_KEY)
869 continue;
870
871 if (flags & FLAG_STREAM_ID)
872 length += ff_get_v_length(pkt->stream_index);
873
874 if (pkt->size % fc->size_mul != fc->size_lsb)
875 continue;
876 if (flags & FLAG_SIZE_MSB)
877 length += ff_get_v_length(pkt->size / fc->size_mul);
878
879 if (flags & FLAG_CHECKSUM)
880 length += 4;
881
882 if (flags & FLAG_CODED_PTS)
883 length += ff_get_v_length(coded_pts);
884
885 if ((flags & FLAG_CODED)
886 && nut->header_len[best_header_idx] >
887 nut->header_len[fc->header_idx] + 1) {
888 flags |= FLAG_HEADER_IDX;
889 }
890
891 if (flags & FLAG_HEADER_IDX) {
892 length += 1 - nut->header_len[best_header_idx];
893 } else {
894 length -= nut->header_len[fc->header_idx];
895 }
896
897 length *= 4;
898 length += !(flags & FLAG_CODED_PTS);
899 length += !(flags & FLAG_CHECKSUM);
900
901 if (length < best_length) {
902 best_length = length;
903 frame_code = i;
904 }
905 }
906
907 if (frame_code < 0)
908 return AVERROR_BUG;
909
910 fc = &nut->frame_code[frame_code];
911 flags = fc->flags;
912 needed_flags = get_needed_flags(nut, nus, fc, pkt);
913 header_idx = fc->header_idx;
914
915 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
916 avio_w8(bc, frame_code);
917 if (flags & FLAG_CODED) {
918 ff_put_v(bc, (flags ^ needed_flags) & ~(FLAG_CODED));
919 flags = needed_flags;
920 }
921 if (flags & FLAG_STREAM_ID)
922 ff_put_v(bc, pkt->stream_index);
923 if (flags & FLAG_CODED_PTS)
924 ff_put_v(bc, coded_pts);
925 if (flags & FLAG_SIZE_MSB)
926 ff_put_v(bc, pkt->size / fc->size_mul);
927 if (flags & FLAG_HEADER_IDX)
928 ff_put_v(bc, header_idx = best_header_idx);
929
930 if (flags & FLAG_CHECKSUM)
931 avio_wl32(bc, ffio_get_checksum(bc));
932 else
933 ffio_get_checksum(bc);
934
935 avio_write(bc, pkt->data + nut->header_len[header_idx],
936 pkt->size - nut->header_len[header_idx]);
937 nus->last_flags = flags;
938 nus->last_pts = pkt->pts;
939
940 //FIXME just store one per syncpoint
941 if (flags & FLAG_KEY && !(nut->flags & NUT_PIPE))
942 av_add_index_entry(
943 s->streams[pkt->stream_index],
944 nut->last_syncpoint_pos,
945 pkt->pts,
946 0,
947 0,
948 AVINDEX_KEYFRAME);
949
950 return 0;
951 }
952
953 static int nut_write_trailer(AVFormatContext *s)
954 {
955 NUTContext *nut = s->priv_data;
956 AVIOContext *bc = s->pb;
957
958 while (nut->header_count < 3)
959 write_headers(s, bc);
960
961 ff_nut_free_sp(nut);
962 av_freep(&nut->stream);
963 av_freep(&nut->chapter);
964 av_freep(&nut->time_base);
965
966 return 0;
967 }
968
969 #define OFFSET(x) offsetof(NUTContext, x)
970 #define E AV_OPT_FLAG_ENCODING_PARAM
971 static const AVOption options[] = {
972 { "syncpoints", "NUT syncpoint behaviour", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, E, "syncpoints" },
973 { "default", "", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, INT_MIN, INT_MAX, E, "syncpoints" },
974 { "none", "Disable syncpoints, low overhead and unseekable", 0, AV_OPT_TYPE_CONST, {.i64 = NUT_PIPE}, INT_MIN, INT_MAX, E, "syncpoints" },
975 { "timestamped", "Extend syncpoints with a wallclock timestamp", 0, AV_OPT_TYPE_CONST, {.i64 = NUT_BROADCAST}, INT_MIN, INT_MAX, E, "syncpoints" },
976 { NULL },
977 };
978
979 static const AVClass class = {
980 .class_name = "nutenc",
981 .item_name = av_default_item_name,
982 .option = options,
983 .version = LIBAVUTIL_VERSION_INT,
984 };
985
986 AVOutputFormat ff_nut_muxer = {
987 .name = "nut",
988 .long_name = NULL_IF_CONFIG_SMALL("NUT"),
989 .mime_type = "video/x-nut",
990 .extensions = "nut",
991 .priv_data_size = sizeof(NUTContext),
992 .audio_codec = CONFIG_LIBVORBIS ? AV_CODEC_ID_VORBIS :
993 CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_MP2,
994 .video_codec = AV_CODEC_ID_MPEG4,
995 .write_header = nut_write_header,
996 .write_packet = nut_write_packet,
997 .write_trailer = nut_write_trailer,
998 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
999 .codec_tag = ff_nut_codec_tags,
1000 .priv_class = &class,
1001 };