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