FFmpeg
 All Data Structures Namespaces 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, NUT_VERSION);
339  ff_put_v(bc, nut->avf->nb_streams);
340  ff_put_v(bc, nut->max_distance);
341  ff_put_v(bc, nut->time_base_count);
342 
343  for (i = 0; i < nut->time_base_count; i++) {
344  ff_put_v(bc, nut->time_base[i].num);
345  ff_put_v(bc, nut->time_base[i].den);
346  }
347 
348  tmp_pts = 0;
349  tmp_mul = 1;
350  tmp_stream = 0;
351  tmp_match = 1 - (1LL << 62);
352  tmp_head_idx = 0;
353  for (i = 0; i < 256; ) {
354  tmp_fields = 0;
355  tmp_size = 0;
356 // tmp_res=0;
357  if (tmp_pts != nut->frame_code[i].pts_delta ) 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;
474  AVDictionaryEntry *t = NULL;
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];
501  AVDictionaryEntry *t = NULL;
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;
541  AVDictionaryEntry *t = 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;
588  int n = 0;
589 
590  if (j && nus->keyframe_pts[j] == nus->keyframe_pts[j-1]) {
591  av_log(nut->avf, AV_LOG_WARNING, "Multiple keyframes with same PTS\n");
592  nus->keyframe_pts[j] = AV_NOPTS_VALUE;
593  }
594 
595  flag = (nus->keyframe_pts[j] != AV_NOPTS_VALUE) ^ (j+1 == nut->sp_count);
596  for (; j<nut->sp_count && (nus->keyframe_pts[j] != AV_NOPTS_VALUE) == flag; j++)
597  n++;
598 
599  ff_put_v(bc, 1 + 2*flag + 4*n);
600  for (k= j - n; k<=j && k<nut->sp_count; k++) {
601  if (nus->keyframe_pts[k] == AV_NOPTS_VALUE)
602  continue;
603  av_assert0(nus->keyframe_pts[k] > last_pts);
604  ff_put_v(bc, nus->keyframe_pts[k] - last_pts);
605  last_pts = nus->keyframe_pts[k];
606  }
607  }
608  }
609 
610  payload_size = avio_tell(bc) - startpos + 8 + 4;
611 
612  avio_wb64(bc, 8 + payload_size + av_log2(payload_size) / 7 + 1 + 4*(payload_size > 4096));
613 
614  return 0;
615 }
616 
618 {
619  NUTContext *nut = avctx->priv_data;
620  AVIOContext *dyn_bc;
621  int i, ret;
622 
624 
625  ret = avio_open_dyn_buf(&dyn_bc);
626  if (ret < 0)
627  return ret;
628  write_mainheader(nut, dyn_bc);
629  put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
630 
631  for (i = 0; i < nut->avf->nb_streams; i++) {
632  ret = avio_open_dyn_buf(&dyn_bc);
633  if (ret < 0)
634  return ret;
635  ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i);
636  if (ret < 0)
637  return ret;
638  put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
639  }
640 
641  ret = avio_open_dyn_buf(&dyn_bc);
642  if (ret < 0)
643  return ret;
644  write_globalinfo(nut, dyn_bc);
645  put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
646 
647  for (i = 0; i < nut->avf->nb_streams; i++) {
648  ret = avio_open_dyn_buf(&dyn_bc);
649  if (ret < 0)
650  return ret;
651  ret = write_streaminfo(nut, dyn_bc, i);
652  if (ret < 0)
653  return ret;
654  if (ret > 0)
655  put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
656  else {
657  uint8_t *buf;
658  avio_close_dyn_buf(dyn_bc, &buf);
659  av_free(buf);
660  }
661  }
662 
663  for (i = 0; i < nut->avf->nb_chapters; i++) {
664  ret = avio_open_dyn_buf(&dyn_bc);
665  if (ret < 0)
666  return ret;
667  ret = write_chapter(nut, dyn_bc, i);
668  if (ret < 0) {
669  uint8_t *buf;
670  avio_close_dyn_buf(dyn_bc, &buf);
671  av_freep(&buf);
672  return ret;
673  }
674  put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
675  }
676 
677  nut->last_syncpoint_pos = INT_MIN;
678  nut->header_count++;
679  return 0;
680 }
681 
683 {
684  NUTContext *nut = s->priv_data;
685  AVIOContext *bc = s->pb;
686  int i, j, ret;
687 
688  nut->avf = s;
689 
690  nut->stream = av_calloc(s->nb_streams, sizeof(*nut->stream ));
691  nut->chapter = av_calloc(s->nb_chapters, sizeof(*nut->chapter));
692  nut->time_base= av_calloc(s->nb_streams +
693  s->nb_chapters, sizeof(*nut->time_base));
694  if (!nut->stream || !nut->chapter || !nut->time_base) {
695  av_freep(&nut->stream);
696  av_freep(&nut->chapter);
697  av_freep(&nut->time_base);
698  return AVERROR(ENOMEM);
699  }
700 
701  for (i = 0; i < s->nb_streams; i++) {
702  AVStream *st = s->streams[i];
703  int ssize;
704  AVRational time_base;
705  ff_parse_specific_params(st->codec, &time_base.den, &ssize, &time_base.num);
706 
707  if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->sample_rate) {
708  time_base = (AVRational) {1, st->codec->sample_rate};
709  } else {
710  time_base = ff_choose_timebase(s, st, 48000);
711  }
712 
713  avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
714 
715  for (j = 0; j < nut->time_base_count; j++)
716  if (!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))) {
717  break;
718  }
719  nut->time_base[j] = time_base;
720  nut->stream[i].time_base = &nut->time_base[j];
721  if (j == nut->time_base_count)
722  nut->time_base_count++;
723 
724  if (INT64_C(1000) * time_base.num >= time_base.den)
725  nut->stream[i].msb_pts_shift = 7;
726  else
727  nut->stream[i].msb_pts_shift = 14;
728  nut->stream[i].max_pts_distance =
729  FFMAX(time_base.den, time_base.num) / time_base.num;
730  }
731 
732  for (i = 0; i < s->nb_chapters; i++) {
733  AVChapter *ch = s->chapters[i];
734 
735  for (j = 0; j < nut->time_base_count; j++)
736  if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
737  break;
738 
739  nut->time_base[j] = ch->time_base;
740  nut->chapter[i].time_base = &nut->time_base[j];
741  if (j == nut->time_base_count)
742  nut->time_base_count++;
743  }
744 
745  nut->max_distance = MAX_DISTANCE;
747  build_frame_code(s);
748  av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
749 
750  avio_write(bc, ID_STRING, strlen(ID_STRING));
751  avio_w8(bc, 0);
752 
753  if ((ret = write_headers(s, bc)) < 0)
754  return ret;
755 
756  if (s->avoid_negative_ts < 0)
757  s->avoid_negative_ts = 1;
758 
759  avio_flush(bc);
760 
761  return 0;
762 }
763 
765  AVPacket *pkt)
766 {
767  int flags = 0;
768 
769  if (pkt->flags & AV_PKT_FLAG_KEY)
770  flags |= FLAG_KEY;
771  if (pkt->stream_index != fc->stream_id)
772  flags |= FLAG_STREAM_ID;
773  if (pkt->size / fc->size_mul)
774  flags |= FLAG_SIZE_MSB;
775  if (pkt->pts - nus->last_pts != fc->pts_delta)
776  flags |= FLAG_CODED_PTS;
777  if (pkt->size > 2 * nut->max_distance)
778  flags |= FLAG_CHECKSUM;
779  if (FFABS(pkt->pts - nus->last_pts) > nus->max_pts_distance)
780  flags |= FLAG_CHECKSUM;
781  if (pkt->size < nut->header_len[fc->header_idx] ||
782  (pkt->size > 4096 && fc->header_idx) ||
783  memcmp(pkt->data, nut->header[fc->header_idx],
784  nut->header_len[fc->header_idx]))
785  flags |= FLAG_HEADER_IDX;
786 
787  return flags | (fc->flags & FLAG_CODED);
788 }
789 
791 {
792  int i;
793  int best_i = 0;
794  int best_len = 0;
795 
796  if (pkt->size > 4096)
797  return 0;
798 
799  for (i = 1; i < nut->header_count; i++)
800  if (pkt->size >= nut->header_len[i]
801  && nut->header_len[i] > best_len
802  && !memcmp(pkt->data, nut->header[i], nut->header_len[i])) {
803  best_i = i;
804  best_len = nut->header_len[i];
805  }
806  return best_i;
807 }
808 
810 {
811  NUTContext *nut = s->priv_data;
812  StreamContext *nus = &nut->stream[pkt->stream_index];
813  AVIOContext *bc = s->pb, *dyn_bc;
814  FrameCode *fc;
815  int64_t coded_pts;
816  int best_length, frame_code, flags, needed_flags, i, header_idx;
817  int best_header_idx;
818  int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
819  int store_sp = 0;
820  int ret;
821 
822  if (pkt->pts < 0) {
823  av_log(s, AV_LOG_ERROR,
824  "Negative pts not supported stream %d, pts %"PRId64"\n",
825  pkt->stream_index, pkt->pts);
826  return AVERROR(EINVAL);
827  }
828 
829  if (1LL << (20 + 3 * nut->header_count) <= avio_tell(bc))
830  write_headers(s, bc);
831 
832  if (key_frame && !(nus->last_flags & FLAG_KEY))
833  store_sp = 1;
834 
835  if (pkt->size + 30 /*FIXME check*/ + avio_tell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
836  store_sp = 1;
837 
838 //FIXME: Ensure store_sp is 1 in the first place.
839 
840  if (store_sp) {
841  Syncpoint *sp, dummy = { .pos = INT64_MAX };
842 
843  ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
844  for (i = 0; i < s->nb_streams; i++) {
845  AVStream *st = s->streams[i];
846  int64_t dts_tb = av_rescale_rnd(pkt->dts,
847  nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
848  nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
849  AV_ROUND_DOWN);
850  int index = av_index_search_timestamp(st, dts_tb,
852  if (index >= 0)
853  dummy.pos = FFMIN(dummy.pos, st->index_entries[index].pos);
854  }
855  if (dummy.pos == INT64_MAX)
856  dummy.pos = 0;
857  sp = av_tree_find(nut->syncpoints, &dummy, (void *)ff_nut_sp_pos_cmp,
858  NULL);
859 
860  nut->last_syncpoint_pos = avio_tell(bc);
861  ret = avio_open_dyn_buf(&dyn_bc);
862  if (ret < 0)
863  return ret;
864  put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
865  ff_put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos) >> 4 : 0);
866  put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
867 
868  if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0 /*unused*/, pkt->dts)) < 0)
869  return ret;
870 
871  if ((1ll<<60) % nut->sp_count == 0)
872  for (i=0; i<s->nb_streams; i++) {
873  int j;
874  StreamContext *nus = &nut->stream[i];
875  av_reallocp_array(&nus->keyframe_pts, 2*nut->sp_count, sizeof(*nus->keyframe_pts));
876  if (!nus->keyframe_pts)
877  return AVERROR(ENOMEM);
878  for (j=nut->sp_count == 1 ? 0 : nut->sp_count; j<2*nut->sp_count; j++)
879  nus->keyframe_pts[j] = AV_NOPTS_VALUE;
880  }
881  }
883 
884  coded_pts = pkt->pts & ((1 << nus->msb_pts_shift) - 1);
885  if (ff_lsb2full(nus, coded_pts) != pkt->pts)
886  coded_pts = pkt->pts + (1 << nus->msb_pts_shift);
887 
888  best_header_idx = find_best_header_idx(nut, pkt);
889 
890  best_length = INT_MAX;
891  frame_code = -1;
892  for (i = 0; i < 256; i++) {
893  int length = 0;
894  FrameCode *fc = &nut->frame_code[i];
895  int flags = fc->flags;
896 
897  if (flags & FLAG_INVALID)
898  continue;
899  needed_flags = get_needed_flags(nut, nus, fc, pkt);
900 
901  if (flags & FLAG_CODED) {
902  length++;
903  flags = needed_flags;
904  }
905 
906  if ((flags & needed_flags) != needed_flags)
907  continue;
908 
909  if ((flags ^ needed_flags) & FLAG_KEY)
910  continue;
911 
912  if (flags & FLAG_STREAM_ID)
913  length += ff_get_v_length(pkt->stream_index);
914 
915  if (pkt->size % fc->size_mul != fc->size_lsb)
916  continue;
917  if (flags & FLAG_SIZE_MSB)
918  length += ff_get_v_length(pkt->size / fc->size_mul);
919 
920  if (flags & FLAG_CHECKSUM)
921  length += 4;
922 
923  if (flags & FLAG_CODED_PTS)
924  length += ff_get_v_length(coded_pts);
925 
926  if ( (flags & FLAG_CODED)
927  && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx] + 1) {
928  flags |= FLAG_HEADER_IDX;
929  }
930 
931  if (flags & FLAG_HEADER_IDX) {
932  length += 1 - nut->header_len[best_header_idx];
933  } else {
934  length -= nut->header_len[fc->header_idx];
935  }
936 
937  length *= 4;
938  length += !(flags & FLAG_CODED_PTS);
939  length += !(flags & FLAG_CHECKSUM);
940 
941  if (length < best_length) {
942  best_length = length;
943  frame_code = i;
944  }
945  }
946  av_assert0(frame_code != -1);
947  fc = &nut->frame_code[frame_code];
948  flags = fc->flags;
949  needed_flags = get_needed_flags(nut, nus, fc, pkt);
950  header_idx = fc->header_idx;
951 
953  avio_w8(bc, frame_code);
954  if (flags & FLAG_CODED) {
955  ff_put_v(bc, (flags ^ needed_flags) & ~(FLAG_CODED));
956  flags = needed_flags;
957  }
958  if (flags & FLAG_STREAM_ID) ff_put_v(bc, pkt->stream_index);
959  if (flags & FLAG_CODED_PTS) ff_put_v(bc, coded_pts);
960  if (flags & FLAG_SIZE_MSB ) ff_put_v(bc, pkt->size / fc->size_mul);
961  if (flags & FLAG_HEADER_IDX) ff_put_v(bc, header_idx = best_header_idx);
962 
963  if (flags & FLAG_CHECKSUM) avio_wl32(bc, ffio_get_checksum(bc));
964  else ffio_get_checksum(bc);
965 
966  avio_write(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
967  nus->last_flags = flags;
968  nus->last_pts = pkt->pts;
969 
970  //FIXME just store one per syncpoint
971  if (flags & FLAG_KEY) {
973  s->streams[pkt->stream_index],
974  nut->last_syncpoint_pos,
975  pkt->pts,
976  0,
977  0,
979  if (nus->keyframe_pts && nus->keyframe_pts[nut->sp_count] == AV_NOPTS_VALUE)
980  nus->keyframe_pts[nut->sp_count] = pkt->pts;
981  }
982 
983  if (!nut->max_pts_tb || av_compare_ts(nut->max_pts, *nut->max_pts_tb, pkt->pts, *nus->time_base) < 0) {
984  nut->max_pts = pkt->pts;
985  nut->max_pts_tb = nus->time_base;
986  }
987 
988  return 0;
989 }
990 
992 {
993  NUTContext *nut = s->priv_data;
994  AVIOContext *bc = s->pb, *dyn_bc;
995  int i, ret;
996 
997  while (nut->header_count < 3)
998  write_headers(s, bc);
999 
1000  ret = avio_open_dyn_buf(&dyn_bc);
1001  if (ret >= 0 && nut->sp_count) {
1002  write_index(nut, dyn_bc);
1003  put_packet(nut, bc, dyn_bc, 1, INDEX_STARTCODE);
1004  }
1005 
1006  ff_nut_free_sp(nut);
1007  for (i=0; i<s->nb_streams; i++)
1008  av_freep(&nut->stream[i].keyframe_pts);
1009 
1010  av_freep(&nut->stream);
1011  av_freep(&nut->chapter);
1012  av_freep(&nut->time_base);
1013 
1014  return 0;
1015 }
1016 
1018  .name = "nut",
1019  .long_name = NULL_IF_CONFIG_SMALL("NUT"),
1020  .mime_type = "video/x-nut",
1021  .extensions = "nut",
1022  .priv_data_size = sizeof(NUTContext),
1023  .audio_codec = CONFIG_LIBVORBIS ? AV_CODEC_ID_VORBIS :
1024  CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_MP2,
1025  .video_codec = AV_CODEC_ID_MPEG4,
1030  .codec_tag = ff_nut_codec_tags,
1031 };