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