nutenc: do not use AVCodecContext.frame_size
[libav.git] / libavformat / nutenc.c
CommitLineData
70ea1e69
MN
1/*
2 * nut muxer
3 * Copyright (c) 2004-2007 Michael Niedermayer
4 *
2912e87a 5 * This file is part of Libav.
70ea1e69 6 *
2912e87a 7 * Libav is free software; you can redistribute it and/or
70ea1e69
MN
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 *
2912e87a 12 * Libav is distributed in the hope that it will be useful,
70ea1e69
MN
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
2912e87a 18 * License along with Libav; if not, write to the Free Software
70ea1e69
MN
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
8f8bc923
DB
22#include <stdint.h>
23
6a5d31ac 24#include "libavutil/intreadwrite.h"
0ebcdf5c 25#include "libavutil/mathematics.h"
245976da 26#include "libavutil/tree.h"
d2d67e42 27#include "libavutil/dict.h"
c94e2e85
LB
28#include "libavutil/time.h"
29#include "libavutil/opt.h"
245976da 30#include "libavcodec/mpegaudiodata.h"
70ea1e69 31#include "nut.h"
80b39e1c 32#include "internal.h"
4c4427a7 33#include "avio_internal.h"
bfe5454c 34#include "riff.h"
a712d725 35
fce4450d
LB
36static int find_expected_header(AVCodecContext *c, int size, int key_frame,
37 uint8_t out[64])
38{
39 int sample_rate = c->sample_rate;
a712d725 40
fce4450d 41 if (size > 4096)
a712d725
MN
42 return 0;
43
44 AV_WB24(out, 1);
45
fce4450d
LB
46 if (c->codec_id == AV_CODEC_ID_MPEG4) {
47 if (key_frame) {
a712d725 48 return 3;
fce4450d
LB
49 } else {
50 out[3] = 0xB6;
a712d725
MN
51 return 4;
52 }
fce4450d
LB
53 } else if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO ||
54 c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
a712d725 55 return 3;
fce4450d 56 } else if (c->codec_id == AV_CODEC_ID_H264) {
a712d725 57 return 3;
fce4450d
LB
58 } else if (c->codec_id == AV_CODEC_ID_MP3 ||
59 c->codec_id == AV_CODEC_ID_MP2) {
a712d725 60 int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
fce4450d
LB
61 int layer = c->codec_id == AV_CODEC_ID_MP3 ? 3 : 2;
62 unsigned int header = 0xFFF00000;
a712d725 63
fce4450d
LB
64 lsf = sample_rate < (24000 + 32000) / 2;
65 mpeg25 = sample_rate < (12000 + 16000) / 2;
a712d725 66 sample_rate <<= lsf + mpeg25;
fce4450d
LB
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;
a712d725 73
fce4450d 74 sample_rate = avpriv_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
a712d725 75
fce4450d
LB
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);
a712d725 81
fce4450d 82 if (frame_size == size)
a712d725
MN
83 break;
84 }
85
fce4450d
LB
86 header |= (!lsf) << 19;
87 header |= (4 - layer) << 17;
88 header |= 1 << 16; //no crc
a712d725 89 AV_WB32(out, header);
fce4450d
LB
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 ...
a712d725 94
fce4450d
LB
95 header |= (bitrate_index >> 1) << 12;
96 header |= sample_rate_index << 10;
97 header |= (bitrate_index & 1) << 9;
a712d725
MN
98
99 return 2; //FIXME actually put the needed ones in build_elision_headers()
6ff15cd5 100 //return 3; //we guess that the private bit is not set
7ce68923 101//FIXME the above assumptions should be checked, if these turn out false too often something should be done
a712d725
MN
102 }
103 return 0;
104}
105
fce4450d
LB
106static int find_header_idx(AVFormatContext *s, AVCodecContext *c, int size,
107 int frame_type)
108{
a712d725
MN
109 NUTContext *nut = s->priv_data;
110 uint8_t out[64];
111 int i;
fce4450d 112 int len = find_expected_header(c, size, frame_type, out);
a712d725 113
fce4450d
LB
114 for (i = 1; i < nut->header_count; i++) {
115 if (len == nut->header_len[i] && !memcmp(out, nut->header[i], len)) {
a712d725
MN
116 return i;
117 }
118 }
fce4450d 119
a712d725
MN
120 return 0;
121}
122
fce4450d
LB
123static void build_elision_headers(AVFormatContext *s)
124{
a712d725
MN
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
fce4450d
LB
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
a712d725
MN
136 };
137
fce4450d
LB
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];
a712d725
MN
142 }
143}
70ea1e69 144
fce4450d
LB
145static void build_frame_code(AVFormatContext *s)
146{
70ea1e69
MN
147 NUTContext *nut = s->priv_data;
148 int key_frame, index, pred, stream_id;
fce4450d
LB
149 int start = 1;
150 int end = 254;
151 int keyframe_0_esc = s->nb_streams > 2;
70ea1e69 152 int pred_table[10];
0fcfa8eb
MN
153 FrameCode *ft;
154
fce4450d
LB
155 ft = &nut->frame_code[start];
156 ft->flags = FLAG_CODED;
157 ft->size_mul = 1;
158 ft->pts_delta = 1;
0fcfa8eb 159 start++;
70ea1e69 160
fce4450d 161 if (keyframe_0_esc) {
70ea1e69 162 /* keyframe = 0 escape */
fce4450d
LB
163 FrameCode *ft = &nut->frame_code[start];
164 ft->flags = FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
165 ft->size_mul = 1;
70ea1e69
MN
166 start++;
167 }
168
fce4450d
LB
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;
70ea1e69 172 AVCodecContext *codec = s->streams[stream_id]->codec;
80a11de7 173 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec->codec_id);
fce4450d
LB
174 int is_audio = codec->codec_type == AVMEDIA_TYPE_AUDIO;
175 int intra_only = /*codec->intra_only || */ is_audio;
70ea1e69
MN
176 int pred_count;
177
fce4450d
LB
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);
70ea1e69
MN
187 start2++;
188 }
189 }
190
fce4450d
LB
191 key_frame = intra_only;
192 if (is_audio) {
dc6527ed 193 int frame_bytes;
70ea1e69 194 int pts;
dc6527ed
AK
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
fce4450d
LB
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);
70ea1e69
MN
212 start2++;
213 }
fce4450d
LB
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;
70ea1e69
MN
220 start2++;
221 }
70ea1e69 222
80a11de7 223 if (desc && desc->props & AV_CODEC_PROP_REORDER) {
fce4450d
LB
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;
70ea1e69
MN
238 }
239
fce4450d
LB
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;
70ea1e69 243
fce4450d
LB
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;
70ea1e69 249//FIXME use single byte size and pred from last
fce4450d
LB
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);
70ea1e69
MN
255 }
256 }
257 }
fce4450d
LB
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;
70ea1e69
MN
263}
264
fce4450d
LB
265static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc,
266 uint64_t val)
267{
491216c6 268 val *= nut->time_base_count;
073f8b10 269 val += time_base - nut->time_base;
f8280ff4 270 ff_put_v(bc, val);
491216c6 271}
70ea1e69 272/**
49bd8e4b 273 * Store a string as vb.
70ea1e69 274 */
fce4450d
LB
275static void put_str(AVIOContext *bc, const char *string)
276{
277 int len = strlen(string);
70ea1e69 278
f8280ff4 279 ff_put_v(bc, len);
77eb5504 280 avio_write(bc, string, len);
70ea1e69
MN
281}
282
fce4450d
LB
283static void put_s(AVIOContext *bc, int64_t val)
284{
285 ff_put_v(bc, 2 * FFABS(val) - (val > 0));
70ea1e69
MN
286}
287
288#ifdef TRACE
bc66827f
DB
289static inline void ff_put_v_trace(AVIOContext *bc, uint64_t v, const char *file,
290 const char *func, int line)
291{
f8280ff4 292 av_log(NULL, AV_LOG_DEBUG, "ff_put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
70ea1e69 293
f8280ff4 294 ff_put_v(bc, v);
70ea1e69
MN
295}
296
bc66827f
DB
297static inline void put_s_trace(AVIOContext *bc, int64_t v, const char *file,
298 const char *func, int line)
299{
7a26da44 300 av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
70ea1e69
MN
301
302 put_s(bc, v);
303}
f8280ff4 304#define ff_put_v(bc, v) ff_put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
70ea1e69
MN
305#define put_s(bc, v) put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
306#endif
307
34f8cc38 308//FIXME remove calculate_checksum
fce4450d
LB
309static 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;
6c666941 315
fce4450d 316 if (forw_ptr > 4096)
4c4427a7 317 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
77eb5504 318 avio_wb64(bc, startcode);
f8280ff4 319 ff_put_v(bc, forw_ptr);
fce4450d 320 if (forw_ptr > 4096)
b64030f2 321 avio_wl32(bc, ffio_get_checksum(bc));
70ea1e69 322
fce4450d 323 if (calculate_checksum)
4c4427a7 324 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
77eb5504 325 avio_write(bc, dyn_buf, dyn_size);
fce4450d 326 if (calculate_checksum)
b64030f2 327 avio_wl32(bc, ffio_get_checksum(bc));
70ea1e69 328
8d9a3f7e 329 av_free(dyn_buf);
70ea1e69
MN
330}
331
fce4450d
LB
332static 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;
a712d725 336 int64_t tmp_match;
70ea1e69 337
c94e2e85 338 ff_put_v(bc, nut->version);
f8280ff4
MC
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);
70ea1e69 342
fce4450d 343 for (i = 0; i < nut->time_base_count; i++) {
f8280ff4
MC
344 ff_put_v(bc, nut->time_base[i].num);
345 ff_put_v(bc, nut->time_base[i].den);
70ea1e69
MN
346 }
347
fce4450d
LB
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;
70ea1e69 356// tmp_res=0;
fce4450d
LB
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;
70ea1e69 365// if(tmp_res != nut->frame_code[i].res ) tmp_fields=5;
fce4450d
LB
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;
70ea1e69 374// tmp_res = nut->frame_code[i].res;
fce4450d 375 tmp_head_idx = nut->frame_code[i].header_idx;
70ea1e69 376
fce4450d
LB
377 for (j = 0; i < 256; j++, i++) {
378 if (i == 'N') {
70ea1e69
MN
379 j--;
380 continue;
381 }
fce4450d
LB
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;
70ea1e69 390 }
fce4450d
LB
391 if (j != tmp_mul - tmp_size)
392 tmp_fields = 6;
70ea1e69 393
f8280ff4
MC
394 ff_put_v(bc, tmp_flags);
395 ff_put_v(bc, tmp_fields);
fce4450d
LB
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);
a712d725 412 }
fce4450d
LB
413 ff_put_v(bc, nut->header_count - 1);
414 for (i = 1; i < nut->header_count; i++) {
f8280ff4 415 ff_put_v(bc, nut->header_len[i]);
77eb5504 416 avio_write(bc, nut->header[i], nut->header_len[i]);
70ea1e69 417 }
c94e2e85
LB
418 // flags had been effectively introduced in version 4
419 if (nut->version > NUT_STABLE_VERSION)
420 ff_put_v(bc, nut->flags);
97d5eb11 421}
70ea1e69 422
fce4450d
LB
423static int write_streamheader(AVFormatContext *avctx, AVIOContext *bc,
424 AVStream *st, int i)
425{
426 NUTContext *nut = avctx->priv_data;
59729451 427 AVCodecContext *codec = st->codec;
80a11de7 428 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec->codec_id);
fce4450d 429 unsigned codec_tag = av_codec_get_tag(ff_nut_codec_tags, codec->codec_id);
1bd442c2 430
f8280ff4 431 ff_put_v(bc, i);
fce4450d
LB
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;
0809b51e 445 }
f8280ff4 446 ff_put_v(bc, 4);
1bd442c2 447
1e7ff5ac
LB
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)
1bd442c2
LB
450 codec_tag = codec->codec_tag;
451
452 if (codec_tag) {
453 avio_wl32(bc, codec_tag);
fa586439
SS
454 } else {
455 av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
ffd5f098 456 return AVERROR(EINVAL);
fa586439 457 }
0809b51e 458
f8280ff4
MC
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);
80a11de7 462 ff_put_v(bc, (desc && desc->props & AV_CODEC_PROP_REORDER) ? 16 : 0);
77eb5504 463 avio_w8(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
0809b51e 464
f8280ff4 465 ff_put_v(bc, codec->extradata_size);
77eb5504 466 avio_write(bc, codec->extradata, codec->extradata_size);
0809b51e 467
fce4450d 468 switch (codec->codec_type) {
72415b2a 469 case AVMEDIA_TYPE_AUDIO:
f8280ff4
MC
470 ff_put_v(bc, codec->sample_rate);
471 ff_put_v(bc, 1);
472 ff_put_v(bc, codec->channels);
0809b51e 473 break;
72415b2a 474 case AVMEDIA_TYPE_VIDEO:
f8280ff4
MC
475 ff_put_v(bc, codec->width);
476 ff_put_v(bc, codec->height);
0a5790d1 477
fce4450d
LB
478 if (st->sample_aspect_ratio.num <= 0 ||
479 st->sample_aspect_ratio.den <= 0) {
f8280ff4
MC
480 ff_put_v(bc, 0);
481 ff_put_v(bc, 0);
fce4450d 482 } else {
f8280ff4
MC
483 ff_put_v(bc, st->sample_aspect_ratio.num);
484 ff_put_v(bc, st->sample_aspect_ratio.den);
0a5790d1 485 }
f8280ff4 486 ff_put_v(bc, 0); /* csp type -- unknown */
0809b51e
MN
487 break;
488 default:
489 break;
490 }
491 return 0;
492}
493
fce4450d
LB
494static int add_info(AVIOContext *bc, const char *type, const char *value)
495{
ead1939f
MN
496 put_str(bc, type);
497 put_s(bc, -1);
498 put_str(bc, value);
499 return 1;
500}
501
fce4450d
LB
502static int write_globalinfo(NUTContext *nut, AVIOContext *bc)
503{
504 AVFormatContext *s = nut->avf;
d2d67e42 505 AVDictionaryEntry *t = NULL;
ae628ec1 506 AVIOContext *dyn_bc;
fce4450d
LB
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)
899681cd 511 return ret;
ead1939f 512
d2d67e42 513 while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
43382b5f 514 count += add_info(dyn_bc, t->key, t->value);
ead1939f 515
f8280ff4
MC
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
ead1939f 520
f8280ff4 521 ff_put_v(bc, count);
ead1939f 522
fce4450d 523 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
77eb5504 524 avio_write(bc, dyn_buf, dyn_size);
ead1939f 525 av_free(dyn_buf);
899681cd 526 return 0;
ead1939f
MN
527}
528
ae628ec1 529static int write_streaminfo(NUTContext *nut, AVIOContext *bc, int stream_id){
90c2295b
ES
530 AVFormatContext *s= nut->avf;
531 AVStream* st = s->streams[stream_id];
ae628ec1 532 AVIOContext *dyn_bc;
90c2295b
ES
533 uint8_t *dyn_buf=NULL;
534 int count=0, dyn_size, i;
b92c5452 535 int ret = avio_open_dyn_buf(&dyn_bc);
90c2295b
ES
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 }
6dc7d80d 543 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
90c2295b
ES
544
545 if (count) {
f8280ff4
MC
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
90c2295b 550
f8280ff4 551 ff_put_v(bc, count);
90c2295b 552
77eb5504 553 avio_write(bc, dyn_buf, dyn_size);
90c2295b
ES
554 }
555
556 av_free(dyn_buf);
557 return count;
558}
559
073f8b10
AK
560static int write_chapter(NUTContext *nut, AVIOContext *bc, int id)
561{
562 AVIOContext *dyn_bc;
fce4450d 563 uint8_t *dyn_buf = NULL;
d2d67e42 564 AVDictionaryEntry *t = NULL;
fce4450d 565 AVChapter *ch = nut->avf->chapters[id];
073f8b10
AK
566 int ret, dyn_size, count = 0;
567
b92c5452 568 ret = avio_open_dyn_buf(&dyn_bc);
073f8b10
AK
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
d2d67e42 577 while ((t = av_dict_get(ch->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
073f8b10
AK
578 count += add_info(dyn_bc, t->key, t->value);
579
580 ff_put_v(bc, count);
581
6dc7d80d 582 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
073f8b10
AK
583 avio_write(bc, dyn_buf, dyn_size);
584 av_freep(&dyn_buf);
585 return 0;
586}
587
fce4450d
LB
588static int write_headers(AVFormatContext *avctx, AVIOContext *bc)
589{
da9e6c42 590 NUTContext *nut = avctx->priv_data;
ae628ec1 591 AVIOContext *dyn_bc;
899681cd 592 int i, ret;
7e506494 593
03700d39
AK
594 ff_metadata_conv_ctx(avctx, ff_nut_metadata_conv, NULL);
595
b92c5452 596 ret = avio_open_dyn_buf(&dyn_bc);
fce4450d 597 if (ret < 0)
899681cd
BA
598 return ret;
599 write_mainheader(nut, dyn_bc);
600 put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
7e506494 601
fce4450d 602 for (i = 0; i < nut->avf->nb_streams; i++) {
b92c5452 603 ret = avio_open_dyn_buf(&dyn_bc);
fce4450d 604 if (ret < 0)
899681cd 605 return ret;
fce4450d
LB
606 ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i);
607 if (ret < 0)
fc0c4124 608 return ret;
899681cd 609 put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
7e506494 610 }
ead1939f 611
b92c5452 612 ret = avio_open_dyn_buf(&dyn_bc);
fce4450d 613 if (ret < 0)
899681cd
BA
614 return ret;
615 write_globalinfo(nut, dyn_bc);
616 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
14b3f996 617
90c2295b 618 for (i = 0; i < nut->avf->nb_streams; i++) {
b92c5452 619 ret = avio_open_dyn_buf(&dyn_bc);
fce4450d 620 if (ret < 0)
90c2295b
ES
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);
8e32b1f0
MS
627 else
628 ffio_free_dyn_buf(&dyn_bc);
90c2295b
ES
629 }
630
073f8b10 631 for (i = 0; i < nut->avf->nb_chapters; i++) {
b92c5452 632 ret = avio_open_dyn_buf(&dyn_bc);
073f8b10
AK
633 if (ret < 0)
634 return ret;
635 ret = write_chapter(nut, dyn_bc, i);
636 if (ret < 0) {
8e32b1f0 637 ffio_free_dyn_buf(&dyn_bc);
073f8b10
AK
638 return ret;
639 }
640 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
641 }
642
fce4450d 643 nut->last_syncpoint_pos = INT_MIN;
14b3f996 644 nut->header_count++;
899681cd 645 return 0;
7e506494
MN
646}
647
fce4450d
LB
648static int nut_write_header(AVFormatContext *s)
649{
97d5eb11 650 NUTContext *nut = s->priv_data;
ae628ec1 651 AVIOContext *bc = s->pb;
fc0c4124 652 int i, j, ret;
97d5eb11 653
fce4450d 654 nut->avf = s;
97d5eb11 655
c94e2e85
LB
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
fce4450d 666 nut->stream = av_mallocz(sizeof(StreamContext) * s->nb_streams);
25588d3b 667 if (s->nb_chapters)
fce4450d
LB
668 nut->chapter = av_mallocz(sizeof(ChapterContext) * s->nb_chapters);
669 nut->time_base = av_mallocz(sizeof(AVRational) * (s->nb_streams +
073f8b10 670 s->nb_chapters));
76432655
RB
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 }
97d5eb11 677
fce4450d
LB
678 for (i = 0; i < s->nb_streams; i++) {
679 AVStream *st = s->streams[i];
97d5eb11
MN
680 int ssize;
681 AVRational time_base;
d754ed41 682 ff_parse_specific_params(st, &time_base.den, &ssize,
fce4450d 683 &time_base.num);
97d5eb11 684
c3f9ebf7 685 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
97d5eb11 686
fce4450d
LB
687 for (j = 0; j < nut->time_base_count; j++)
688 if (!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))) {
97d5eb11
MN
689 break;
690 }
fce4450d
LB
691 nut->time_base[j] = time_base;
692 nut->stream[i].time_base = &nut->time_base[j];
693 if (j == nut->time_base_count)
97d5eb11
MN
694 nut->time_base_count++;
695
fce4450d 696 if (INT64_C(1000) * time_base.num >= time_base.den)
97d5eb11
MN
697 nut->stream[i].msb_pts_shift = 7;
698 else
699 nut->stream[i].msb_pts_shift = 14;
fce4450d
LB
700 nut->stream[i].max_pts_distance =
701 FFMAX(time_base.den, time_base.num) / time_base.num;
97d5eb11
MN
702 }
703
073f8b10
AK
704 for (i = 0; i < s->nb_chapters; i++) {
705 AVChapter *ch = s->chapters[i];
706
fce4450d 707 for (j = 0; j < nut->time_base_count; j++)
073f8b10
AK
708 if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
709 break;
073f8b10 710
fce4450d 711 nut->time_base[j] = ch->time_base;
073f8b10 712 nut->chapter[i].time_base = &nut->time_base[j];
fce4450d 713 if (j == nut->time_base_count)
073f8b10
AK
714 nut->time_base_count++;
715 }
716
82badd27 717 nut->max_distance = MAX_DISTANCE;
a712d725 718 build_elision_headers(s);
97d5eb11
MN
719 build_frame_code(s);
720 assert(nut->frame_code['N'].flags == FLAG_INVALID);
721
77eb5504
AK
722 avio_write(bc, ID_STRING, strlen(ID_STRING));
723 avio_w8(bc, 0);
97d5eb11 724
fc0c4124
SS
725 if ((ret = write_headers(s, bc)) < 0)
726 return ret;
dcc9bde0 727
b7f2fdde 728 avio_flush(bc);
70ea1e69 729
14b3f996 730 //FIXME index
70ea1e69
MN
731
732 return 0;
733}
734
fce4450d
LB
735static 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;
e1249ba9 757
d2062ff6 758 return flags | (fc->flags & FLAG_CODED);
e1249ba9
MN
759}
760
fce4450d
LB
761static int find_best_header_idx(NUTContext *nut, AVPacket *pkt)
762{
a712d725 763 int i;
fce4450d
LB
764 int best_i = 0;
765 int best_len = 0;
a712d725 766
fce4450d 767 if (pkt->size > 4096)
a712d725
MN
768 return 0;
769
fce4450d
LB
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];
a712d725 776 }
a712d725
MN
777 return best_i;
778}
779
fce4450d
LB
780static 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;
e1249ba9
MN
785 FrameCode *fc;
786 int64_t coded_pts;
fce4450d
LB
787 int best_length, frame_code, flags, needed_flags, i, header_idx,
788 best_header_idx;
cc947f04 789 int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
fce4450d 790 int store_sp = 0;
899681cd 791 int ret;
e1249ba9 792
07585ffa
LB
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 }
f53dd468 799
fce4450d 800 if (1LL << (20 + 3 * nut->header_count) <= avio_tell(bc))
da9e6c42 801 write_headers(s, bc);
14b3f996 802
fce4450d
LB
803 if (key_frame && !(nus->last_flags & FLAG_KEY))
804 store_sp = 1;
e1249ba9 805
fce4450d
LB
806 if (pkt->size + 30 /*FIXME check*/ + avio_tell(bc) >=
807 nut->last_syncpoint_pos + nut->max_distance)
808 store_sp = 1;
e1249ba9 809
93951943 810//FIXME: Ensure store_sp is 1 in the first place.
e1249ba9 811
c94e2e85
LB
812 if (store_sp &&
813 (!(nut->flags & NUT_PIPE) || nut->last_syncpoint_pos == INT_MIN)) {
fce4450d 814 Syncpoint *sp, dummy = { .pos = INT64_MAX };
7c04134f 815
e1249ba9 816 ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
fce4450d
LB
817 for (i = 0; i < s->nb_streams; i++) {
818 AVStream *st = s->streams[i];
4ddcc983
OS
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);
fce4450d
LB
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);
7c04134f 827 }
fce4450d
LB
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);
e1249ba9 832
fce4450d
LB
833 nut->last_syncpoint_pos = avio_tell(bc);
834 ret = avio_open_dyn_buf(&dyn_bc);
835 if (ret < 0)
899681cd 836 return ret;
073f8b10 837 put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
fce4450d 838 ff_put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos) >> 4 : 0);
c94e2e85
LB
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 }
899681cd 844 put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
7c04134f 845
b1fcdc08
DB
846 if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0 /*unused*/, pkt->dts)) < 0)
847 return ret;
e1249ba9
MN
848 }
849 assert(nus->last_pts != AV_NOPTS_VALUE);
850
fce4450d
LB
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);
e1249ba9 854
fce4450d 855 best_header_idx = find_best_header_idx(nut, pkt);
a712d725 856
fce4450d
LB
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;
e1249ba9 863
fce4450d 864 if (flags & FLAG_INVALID)
e1249ba9 865 continue;
fce4450d 866 needed_flags = get_needed_flags(nut, nus, fc, pkt);
e1249ba9 867
fce4450d 868 if (flags & FLAG_CODED) {
e1249ba9 869 length++;
63dd9d0e 870 flags = needed_flags;
e1249ba9
MN
871 }
872
fce4450d 873 if ((flags & needed_flags) != needed_flags)
e1249ba9
MN
874 continue;
875
fce4450d 876 if ((flags ^ needed_flags) & FLAG_KEY)
e1249ba9
MN
877 continue;
878
fce4450d
LB
879 if (flags & FLAG_STREAM_ID)
880 length += ff_get_v_length(pkt->stream_index);
e1249ba9 881
fce4450d 882 if (pkt->size % fc->size_mul != fc->size_lsb)
e1249ba9 883 continue;
fce4450d 884 if (flags & FLAG_SIZE_MSB)
f8280ff4 885 length += ff_get_v_length(pkt->size / fc->size_mul);
e1249ba9 886
fce4450d
LB
887 if (flags & FLAG_CHECKSUM)
888 length += 4;
e1249ba9 889
fce4450d 890 if (flags & FLAG_CODED_PTS)
f8280ff4 891 length += ff_get_v_length(coded_pts);
e1249ba9 892
fce4450d
LB
893 if ((flags & FLAG_CODED)
894 && nut->header_len[best_header_idx] >
895 nut->header_len[fc->header_idx] + 1) {
a712d725
MN
896 flags |= FLAG_HEADER_IDX;
897 }
898
fce4450d 899 if (flags & FLAG_HEADER_IDX) {
a712d725 900 length += 1 - nut->header_len[best_header_idx];
fce4450d 901 } else {
a712d725
MN
902 length -= nut->header_len[fc->header_idx];
903 }
904
fce4450d
LB
905 length *= 4;
906 length += !(flags & FLAG_CODED_PTS);
907 length += !(flags & FLAG_CHECKSUM);
e1249ba9 908
fce4450d
LB
909 if (length < best_length) {
910 best_length = length;
911 frame_code = i;
e1249ba9
MN
912 }
913 }
b69183f6
VG
914
915 if (frame_code < 0)
916 return AVERROR_BUG;
917
fce4450d
LB
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;
e1249ba9 922
4c4427a7 923 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
77eb5504 924 avio_w8(bc, frame_code);
fce4450d
LB
925 if (flags & FLAG_CODED) {
926 ff_put_v(bc, (flags ^ needed_flags) & ~(FLAG_CODED));
e1249ba9
MN
927 flags = needed_flags;
928 }
fce4450d
LB
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);
e1249ba9 942
fce4450d
LB
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;
7c04134f
MN
947
948 //FIXME just store one per syncpoint
c94e2e85 949 if (flags & FLAG_KEY && !(nut->flags & NUT_PIPE))
7c04134f
MN
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
70ea1e69
MN
958 return 0;
959}
960
fce4450d
LB
961static int nut_write_trailer(AVFormatContext *s)
962{
963 NUTContext *nut = s->priv_data;
964 AVIOContext *bc = s->pb;
bd533e6c 965
fce4450d 966 while (nut->header_count < 3)
da9e6c42 967 write_headers(s, bc);
3b4bb19e 968
4b83fc0f 969 ff_nut_free_sp(nut);
27dbc47c 970 av_freep(&nut->stream);
2cface71 971 av_freep(&nut->chapter);
27dbc47c 972 av_freep(&nut->time_base);
bd533e6c
MN
973
974 return 0;
975}
976
c94e2e85
LB
977#define OFFSET(x) offsetof(NUTContext, x)
978#define E AV_OPT_FLAG_ENCODING_PARAM
979static 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
987static const AVClass class = {
988 .class_name = "nutenc",
989 .item_name = av_default_item_name,
990 .option = options,
991 .version = LIBAVUTIL_VERSION_INT,
992};
993
c6610a21 994AVOutputFormat ff_nut_muxer = {
dfc2c4d9 995 .name = "nut",
6774247a 996 .long_name = NULL_IF_CONFIG_SMALL("NUT"),
dfc2c4d9
AK
997 .mime_type = "video/x-nut",
998 .extensions = "nut",
999 .priv_data_size = sizeof(NUTContext),
36ef5369
AK
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,
5ee5dc4e
LB
1003 .write_header = nut_write_header,
1004 .write_packet = nut_write_packet,
1005 .write_trailer = nut_write_trailer,
20234a4b 1006 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
1bd442c2 1007 .codec_tag = ff_nut_codec_tags,
c94e2e85 1008 .priv_class = &class,
70ea1e69 1009};