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