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 <stdint.h>
23 
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/mathematics.h"
26 #include "libavutil/tree.h"
27 #include "libavutil/dict.h"
28 #include "libavutil/avassert.h"
29 #include "libavutil/time.h"
30 #include "libavutil/opt.h"
31 #include "libavcodec/bytestream.h"
33 #include "nut.h"
34 #include "internal.h"
35 #include "avio_internal.h"
36 #include "riff.h"
37 
38 static int find_expected_header(AVCodecContext *c, int size, int key_frame,
39  uint8_t out[64])
40 {
41  int sample_rate = c->sample_rate;
42 
43  if (size > 4096)
44  return 0;
45 
46  AV_WB24(out, 1);
47 
48  if (c->codec_id == AV_CODEC_ID_MPEG4) {
49  if (key_frame) {
50  return 3;
51  } else {
52  out[3] = 0xB6;
53  return 4;
54  }
55  } else if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO ||
57  return 3;
58  } else if (c->codec_id == AV_CODEC_ID_H264) {
59  return 3;
60  } else if (c->codec_id == AV_CODEC_ID_MP3 ||
61  c->codec_id == AV_CODEC_ID_MP2) {
62  int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
63  int layer = c->codec_id == AV_CODEC_ID_MP3 ? 3 : 2;
64  unsigned int header = 0xFFF00000;
65 
66  lsf = sample_rate < (24000 + 32000) / 2;
67  mpeg25 = sample_rate < (12000 + 16000) / 2;
68  sample_rate <<= lsf + mpeg25;
69  if (sample_rate < (32000 + 44100) / 2) sample_rate_index = 2;
70  else if (sample_rate < (44100 + 48000) / 2) sample_rate_index = 0;
71  else sample_rate_index = 1;
72 
73  sample_rate = avpriv_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
74 
75  for (bitrate_index = 2; bitrate_index < 30; bitrate_index++) {
76  frame_size =
77  avpriv_mpa_bitrate_tab[lsf][layer - 1][bitrate_index >> 1];
78  frame_size = (frame_size * 144000) / (sample_rate << lsf) +
79  (bitrate_index & 1);
80 
81  if (frame_size == size)
82  break;
83  }
84 
85  header |= (!lsf) << 19;
86  header |= (4 - layer) << 17;
87  header |= 1 << 16; //no crc
88  AV_WB32(out, header);
89  if (size <= 0)
90  return 2; //we guess there is no crc, if there is one the user clearly does not care about overhead
91  if (bitrate_index == 30)
92  return -1; //something is wrong ...
93 
94  header |= (bitrate_index >> 1) << 12;
95  header |= sample_rate_index << 10;
96  header |= (bitrate_index & 1) << 9;
97 
98  return 2; //FIXME actually put the needed ones in build_elision_headers()
99  //return 3; //we guess that the private bit is not set
100 //FIXME the above assumptions should be checked, if these turn out false too often something should be done
101  }
102  return 0;
103 }
104 
105 static int find_header_idx(AVFormatContext *s, AVCodecContext *c, int size, int frame_type)
106 {
107  NUTContext *nut = s->priv_data;
108  uint8_t out[64];
109  int i;
110  int len = find_expected_header(c, size, frame_type, out);
111 
112  for (i = 1; i < nut->header_count; i++) {
113  if (len == nut->header_len[i] && !memcmp(out, nut->header[i], len)) {
114  return i;
115  }
116  }
117 
118  return 0;
119 }
120 
122 {
123  NUTContext *nut = s->priv_data;
124  int i;
125  //FIXME this is lame
126  //FIXME write a 2pass mode to find the maximal headers
127  static const uint8_t headers[][5] = {
128  { 3, 0x00, 0x00, 0x01 },
129  { 4, 0x00, 0x00, 0x01, 0xB6},
130  { 2, 0xFF, 0xFA }, //mp3+crc
131  { 2, 0xFF, 0xFB }, //mp3
132  { 2, 0xFF, 0xFC }, //mp2+crc
133  { 2, 0xFF, 0xFD }, //mp2
134  };
135 
136  nut->header_count = 7;
137  for (i = 1; i < nut->header_count; i++) {
138  nut->header_len[i] = headers[i - 1][0];
139  nut->header[i] = &headers[i - 1][1];
140  }
141 }
142 
144 {
145  NUTContext *nut = s->priv_data;
146  int key_frame, index, pred, stream_id;
147  int start = 1;
148  int end = 254;
149  int keyframe_0_esc = s->nb_streams > 2;
150  int pred_table[10];
151  FrameCode *ft;
152 
153  ft = &nut->frame_code[start];
154  ft->flags = FLAG_CODED;
155  ft->size_mul = 1;
156  ft->pts_delta = 1;
157  start++;
158 
159  if (keyframe_0_esc) {
160  /* keyframe = 0 escape */
161  FrameCode *ft = &nut->frame_code[start];
163  ft->size_mul = 1;
164  start++;
165  }
166 
167  for (stream_id = 0; stream_id < s->nb_streams; stream_id++) {
168  int start2 = start + (end - start) * stream_id / s->nb_streams;
169  int end2 = start + (end - start) * (stream_id + 1) / s->nb_streams;
170  AVCodecContext *codec = s->streams[stream_id]->codec;
171  int is_audio = codec->codec_type == AVMEDIA_TYPE_AUDIO;
172  int intra_only = /*codec->intra_only || */ is_audio;
173  int pred_count;
174  int frame_size = 0;
175 
176  if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
178  if (codec->codec_id == AV_CODEC_ID_VORBIS && !frame_size)
179  frame_size = 64;
180  } else {
181  AVRational f = av_div_q(codec->time_base, *nut->stream[stream_id].time_base);
182  if (f.den == 1 && f.num>0)
183  frame_size = f.num;
184  }
185  if (!frame_size)
186  frame_size = 1;
187 
188  for (key_frame = 0; key_frame < 2; key_frame++) {
189  if (!intra_only || !keyframe_0_esc || key_frame != 0) {
190  FrameCode *ft = &nut->frame_code[start2];
191  ft->flags = FLAG_KEY * key_frame;
193  ft->stream_id = stream_id;
194  ft->size_mul = 1;
195  if (is_audio)
196  ft->header_idx = find_header_idx(s, codec, -1, key_frame);
197  start2++;
198  }
199  }
200 
201  key_frame = intra_only;
202 #if 1
203  if (is_audio) {
204  int frame_bytes = codec->frame_size * (int64_t)codec->bit_rate /
205  (8 * codec->sample_rate);
206  int pts;
207  for (pts = 0; pts < 2; pts++) {
208  for (pred = 0; pred < 2; pred++) {
209  FrameCode *ft = &nut->frame_code[start2];
210  ft->flags = FLAG_KEY * key_frame;
211  ft->stream_id = stream_id;
212  ft->size_mul = frame_bytes + 2;
213  ft->size_lsb = frame_bytes + pred;
214  ft->pts_delta = pts * frame_size;
215  ft->header_idx = find_header_idx(s, codec, frame_bytes + pred, key_frame);
216  start2++;
217  }
218  }
219  } else {
220  FrameCode *ft = &nut->frame_code[start2];
221  ft->flags = FLAG_KEY | FLAG_SIZE_MSB;
222  ft->stream_id = stream_id;
223  ft->size_mul = 1;
224  ft->pts_delta = frame_size;
225  start2++;
226  }
227 #endif
228 
229  if (codec->has_b_frames) {
230  pred_count = 5;
231  pred_table[0] = -2;
232  pred_table[1] = -1;
233  pred_table[2] = 1;
234  pred_table[3] = 3;
235  pred_table[4] = 4;
236  } else if (codec->codec_id == AV_CODEC_ID_VORBIS) {
237  pred_count = 3;
238  pred_table[0] = 2;
239  pred_table[1] = 9;
240  pred_table[2] = 16;
241  } else {
242  pred_count = 1;
243  pred_table[0] = 1;
244  }
245 
246  for (pred = 0; pred < pred_count; pred++) {
247  int start3 = start2 + (end2 - start2) * pred / pred_count;
248  int end3 = start2 + (end2 - start2) * (pred + 1) / pred_count;
249 
250  pred_table[pred] *= frame_size;
251 
252  for (index = start3; index < end3; index++) {
253  FrameCode *ft = &nut->frame_code[index];
254  ft->flags = FLAG_KEY * key_frame;
255  ft->flags |= FLAG_SIZE_MSB;
256  ft->stream_id = stream_id;
257 //FIXME use single byte size and pred from last
258  ft->size_mul = end3 - start3;
259  ft->size_lsb = index - start3;
260  ft->pts_delta = pred_table[pred];
261  if (is_audio)
262  ft->header_idx = find_header_idx(s, codec, -1, key_frame);
263  }
264  }
265  }
266  memmove(&nut->frame_code['N' + 1], &nut->frame_code['N'], sizeof(FrameCode) * (255 - 'N'));
267  nut->frame_code[0].flags =
268  nut->frame_code[255].flags =
269  nut->frame_code['N'].flags = FLAG_INVALID;
270 }
271 
272 static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc, uint64_t val)
273 {
274  val *= nut->time_base_count;
275  val += time_base - nut->time_base;
276  ff_put_v(bc, val);
277 }
278 /**
279  * Store a string as vb.
280  */
281 static void put_str(AVIOContext *bc, const char *string)
282 {
283  int len = strlen(string);
284 
285  ff_put_v(bc, len);
286  avio_write(bc, string, len);
287 }
288 
289 static void put_s(AVIOContext *bc, int64_t val)
290 {
291  ff_put_v(bc, 2 * FFABS(val) - (val > 0));
292 }
293 
294 #ifdef TRACE
295 static inline void ff_put_v_trace(AVIOContext *bc, uint64_t v, const char *file,
296  const char *func, int line)
297 {
298  av_log(NULL, AV_LOG_DEBUG, "ff_put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
299 
300  ff_put_v(bc, v);
301 }
302 
303 static inline void put_s_trace(AVIOContext *bc, int64_t v, const char *file, const char *func, int line)
304 {
305  av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
306 
307  put_s(bc, v);
308 }
309 #define ff_put_v(bc, v) ff_put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
310 #define put_s(bc, v) put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
311 #endif
312 
313 //FIXME remove calculate_checksum
314 static void put_packet(NUTContext *nut, AVIOContext *bc, AVIOContext *dyn_bc,
315  int calculate_checksum, uint64_t startcode)
316 {
317  uint8_t *dyn_buf = NULL;
318  int dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
319  int forw_ptr = dyn_size + 4 * calculate_checksum;
320 
321  if (forw_ptr > 4096)
323  avio_wb64(bc, startcode);
324  ff_put_v(bc, forw_ptr);
325  if (forw_ptr > 4096)
326  avio_wl32(bc, ffio_get_checksum(bc));
327 
328  if (calculate_checksum)
330  avio_write(bc, dyn_buf, dyn_size);
331  if (calculate_checksum)
332  avio_wl32(bc, ffio_get_checksum(bc));
333 
334  av_free(dyn_buf);
335 }
336 
338 {
339  int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields,
340  tmp_head_idx;
341  int64_t tmp_match;
342 
343  ff_put_v(bc, nut->version);
344  if (nut->version > 3)
345  ff_put_v(bc, nut->minor_version = 1);
346  ff_put_v(bc, nut->avf->nb_streams);
347  ff_put_v(bc, nut->max_distance);
348  ff_put_v(bc, nut->time_base_count);
349 
350  for (i = 0; i < nut->time_base_count; i++) {
351  ff_put_v(bc, nut->time_base[i].num);
352  ff_put_v(bc, nut->time_base[i].den);
353  }
354 
355  tmp_pts = 0;
356  tmp_mul = 1;
357  tmp_stream = 0;
358  tmp_match = 1 - (1LL << 62);
359  tmp_head_idx = 0;
360  for (i = 0; i < 256; ) {
361  tmp_fields = 0;
362  tmp_size = 0;
363 // tmp_res=0;
364  if (tmp_pts != nut->frame_code[i].pts_delta ) tmp_fields = 1;
365  if (tmp_mul != nut->frame_code[i].size_mul ) tmp_fields = 2;
366  if (tmp_stream != nut->frame_code[i].stream_id ) tmp_fields = 3;
367  if (tmp_size != nut->frame_code[i].size_lsb ) tmp_fields = 4;
368 // if (tmp_res != nut->frame_code[i].res ) tmp_fields=5;
369  if (tmp_head_idx != nut->frame_code[i].header_idx) tmp_fields = 8;
370 
371  tmp_pts = nut->frame_code[i].pts_delta;
372  tmp_flags = nut->frame_code[i].flags;
373  tmp_stream = nut->frame_code[i].stream_id;
374  tmp_mul = nut->frame_code[i].size_mul;
375  tmp_size = nut->frame_code[i].size_lsb;
376 // tmp_res = nut->frame_code[i].res;
377  tmp_head_idx = nut->frame_code[i].header_idx;
378 
379  for (j = 0; i < 256; j++, i++) {
380  if (i == 'N') {
381  j--;
382  continue;
383  }
384  if (nut->frame_code[i].pts_delta != tmp_pts ||
385  nut->frame_code[i].flags != tmp_flags ||
386  nut->frame_code[i].stream_id != tmp_stream ||
387  nut->frame_code[i].size_mul != tmp_mul ||
388  nut->frame_code[i].size_lsb != tmp_size + j ||
389 // nut->frame_code[i].res != tmp_res ||
390  nut->frame_code[i].header_idx != tmp_head_idx)
391  break;
392  }
393  if (j != tmp_mul - tmp_size)
394  tmp_fields = 6;
395 
396  ff_put_v(bc, tmp_flags);
397  ff_put_v(bc, tmp_fields);
398  if (tmp_fields > 0) put_s(bc, tmp_pts);
399  if (tmp_fields > 1) ff_put_v(bc, tmp_mul);
400  if (tmp_fields > 2) ff_put_v(bc, tmp_stream);
401  if (tmp_fields > 3) ff_put_v(bc, tmp_size);
402  if (tmp_fields > 4) ff_put_v(bc, 0 /*tmp_res*/);
403  if (tmp_fields > 5) ff_put_v(bc, j);
404  if (tmp_fields > 6) ff_put_v(bc, tmp_match);
405  if (tmp_fields > 7) ff_put_v(bc, tmp_head_idx);
406  }
407  ff_put_v(bc, nut->header_count - 1);
408  for (i = 1; i < nut->header_count; i++) {
409  ff_put_v(bc, nut->header_len[i]);
410  avio_write(bc, nut->header[i], nut->header_len[i]);
411  }
412  // flags had been effectively introduced in version 4
413  if (nut->version > 3)
414  ff_put_v(bc, nut->flags);
415 }
416 
418  AVStream *st, int i)
419 {
420  NUTContext *nut = avctx->priv_data;
421  AVCodecContext *codec = st->codec;
422 
423  ff_put_v(bc, i);
424  switch (codec->codec_type) {
425  case AVMEDIA_TYPE_VIDEO: ff_put_v(bc, 0); break;
426  case AVMEDIA_TYPE_AUDIO: ff_put_v(bc, 1); break;
427  case AVMEDIA_TYPE_SUBTITLE: ff_put_v(bc, 2); break;
428  default: ff_put_v(bc, 3); break;
429  }
430  ff_put_v(bc, 4);
431  if (codec->codec_tag) {
432  avio_wl32(bc, codec->codec_tag);
433  } else {
434  av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
435  return AVERROR(EINVAL);
436  }
437 
438  ff_put_v(bc, nut->stream[i].time_base - nut->time_base);
439  ff_put_v(bc, nut->stream[i].msb_pts_shift);
440  ff_put_v(bc, nut->stream[i].max_pts_distance);
441  ff_put_v(bc, codec->has_b_frames);
442  avio_w8(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
443 
444  ff_put_v(bc, codec->extradata_size);
445  avio_write(bc, codec->extradata, codec->extradata_size);
446 
447  switch (codec->codec_type) {
448  case AVMEDIA_TYPE_AUDIO:
449  ff_put_v(bc, codec->sample_rate);
450  ff_put_v(bc, 1);
451  ff_put_v(bc, codec->channels);
452  break;
453  case AVMEDIA_TYPE_VIDEO:
454  ff_put_v(bc, codec->width);
455  ff_put_v(bc, codec->height);
456 
457  if (st->sample_aspect_ratio.num <= 0 ||
458  st->sample_aspect_ratio.den <= 0) {
459  ff_put_v(bc, 0);
460  ff_put_v(bc, 0);
461  } else {
464  }
465  ff_put_v(bc, 0); /* csp type -- unknown */
466  break;
467  default:
468  break;
469  }
470  return 0;
471 }
472 
473 static int add_info(AVIOContext *bc, const char *type, const char *value)
474 {
475  put_str(bc, type);
476  put_s(bc, -1);
477  put_str(bc, value);
478  return 1;
479 }
480 
482 {
483  AVFormatContext *s = nut->avf;
484  AVDictionaryEntry *t = NULL;
485  AVIOContext *dyn_bc;
486  uint8_t *dyn_buf = NULL;
487  int count = 0, dyn_size;
488  int ret = avio_open_dyn_buf(&dyn_bc);
489  if (ret < 0)
490  return ret;
491 
492  while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
493  count += add_info(dyn_bc, t->key, t->value);
494 
495  ff_put_v(bc, 0); //stream_if_plus1
496  ff_put_v(bc, 0); //chapter_id
497  ff_put_v(bc, 0); //timestamp_start
498  ff_put_v(bc, 0); //length
499 
500  ff_put_v(bc, count);
501 
502  dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
503  avio_write(bc, dyn_buf, dyn_size);
504  av_free(dyn_buf);
505  return 0;
506 }
507 
508 static int write_streaminfo(NUTContext *nut, AVIOContext *bc, int stream_id) {
509  AVFormatContext *s= nut->avf;
510  AVStream* st = s->streams[stream_id];
511  AVDictionaryEntry *t = NULL;
512  AVIOContext *dyn_bc;
513  uint8_t *dyn_buf=NULL;
514  int count=0, dyn_size, i;
515  int ret = avio_open_dyn_buf(&dyn_bc);
516  if (ret < 0)
517  return ret;
518 
519  while ((t = av_dict_get(st->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
520  count += add_info(dyn_bc, t->key, t->value);
521  for (i=0; ff_nut_dispositions[i].flag; ++i) {
522  if (st->disposition & ff_nut_dispositions[i].flag)
523  count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
524  }
525  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
526  uint8_t buf[256];
527  snprintf(buf, sizeof(buf), "%d/%d", st->codec->time_base.den, st->codec->time_base.num);
528  count += add_info(dyn_bc, "r_frame_rate", buf);
529  }
530  dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
531 
532  if (count) {
533  ff_put_v(bc, stream_id + 1); //stream_id_plus1
534  ff_put_v(bc, 0); //chapter_id
535  ff_put_v(bc, 0); //timestamp_start
536  ff_put_v(bc, 0); //length
537 
538  ff_put_v(bc, count);
539 
540  avio_write(bc, dyn_buf, dyn_size);
541  }
542 
543  av_free(dyn_buf);
544  return count;
545 }
546 
547 static int write_chapter(NUTContext *nut, AVIOContext *bc, int id)
548 {
549  AVIOContext *dyn_bc;
550  uint8_t *dyn_buf = NULL;
551  AVDictionaryEntry *t = NULL;
552  AVChapter *ch = nut->avf->chapters[id];
553  int ret, dyn_size, count = 0;
554 
555  ret = avio_open_dyn_buf(&dyn_bc);
556  if (ret < 0)
557  return ret;
558 
559  ff_put_v(bc, 0); // stream_id_plus1
560  put_s(bc, id + 1); // chapter_id
561  put_tt(nut, nut->chapter[id].time_base, bc, ch->start); // chapter_start
562  ff_put_v(bc, ch->end - ch->start); // chapter_len
563 
564  while ((t = av_dict_get(ch->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
565  count += add_info(dyn_bc, t->key, t->value);
566 
567  ff_put_v(bc, count);
568 
569  dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
570  avio_write(bc, dyn_buf, dyn_size);
571  av_freep(&dyn_buf);
572  return 0;
573 }
574 
575 static int write_index(NUTContext *nut, AVIOContext *bc) {
576  int i;
577  Syncpoint dummy= { .pos= 0 };
578  Syncpoint *next_node[2] = { NULL };
579  int64_t startpos = avio_tell(bc);
580  int64_t payload_size;
581 
582  put_tt(nut, nut->max_pts_tb, bc, nut->max_pts);
583 
584  ff_put_v(bc, nut->sp_count);
585 
586  for (i=0; i<nut->sp_count; i++) {
587  av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp, (void**)next_node);
588  ff_put_v(bc, (next_node[1]->pos >> 4) - (dummy.pos>>4));
589  dummy.pos = next_node[1]->pos;
590  }
591 
592  for (i=0; i<nut->avf->nb_streams; i++) {
593  StreamContext *nus= &nut->stream[i];
594  int64_t last_pts= -1;
595  int j, k;
596  for (j=0; j<nut->sp_count; j++) {
597  int flag;
598  int n = 0;
599 
600  if (j && nus->keyframe_pts[j] == nus->keyframe_pts[j-1]) {
601  av_log(nut->avf, AV_LOG_WARNING, "Multiple keyframes with same PTS\n");
602  nus->keyframe_pts[j] = AV_NOPTS_VALUE;
603  }
604 
605  flag = (nus->keyframe_pts[j] != AV_NOPTS_VALUE) ^ (j+1 == nut->sp_count);
606  for (; j<nut->sp_count && (nus->keyframe_pts[j] != AV_NOPTS_VALUE) == flag; j++)
607  n++;
608 
609  ff_put_v(bc, 1 + 2*flag + 4*n);
610  for (k= j - n; k<=j && k<nut->sp_count; k++) {
611  if (nus->keyframe_pts[k] == AV_NOPTS_VALUE)
612  continue;
613  av_assert0(nus->keyframe_pts[k] > last_pts);
614  ff_put_v(bc, nus->keyframe_pts[k] - last_pts);
615  last_pts = nus->keyframe_pts[k];
616  }
617  }
618  }
619 
620  payload_size = avio_tell(bc) - startpos + 8 + 4;
621 
622  avio_wb64(bc, 8 + payload_size + av_log2(payload_size) / 7 + 1 + 4*(payload_size > 4096));
623 
624  return 0;
625 }
626 
628 {
629  NUTContext *nut = avctx->priv_data;
630  AVIOContext *dyn_bc;
631  int i, ret;
632 
634 
635  ret = avio_open_dyn_buf(&dyn_bc);
636  if (ret < 0)
637  return ret;
638  write_mainheader(nut, dyn_bc);
639  put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
640 
641  for (i = 0; i < nut->avf->nb_streams; i++) {
642  ret = avio_open_dyn_buf(&dyn_bc);
643  if (ret < 0)
644  return ret;
645  ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i);
646  if (ret < 0)
647  return ret;
648  put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
649  }
650 
651  ret = avio_open_dyn_buf(&dyn_bc);
652  if (ret < 0)
653  return ret;
654  write_globalinfo(nut, dyn_bc);
655  put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
656 
657  for (i = 0; i < nut->avf->nb_streams; i++) {
658  ret = avio_open_dyn_buf(&dyn_bc);
659  if (ret < 0)
660  return ret;
661  ret = write_streaminfo(nut, dyn_bc, i);
662  if (ret < 0)
663  return ret;
664  if (ret > 0)
665  put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
666  else {
667  uint8_t *buf;
668  avio_close_dyn_buf(dyn_bc, &buf);
669  av_free(buf);
670  }
671  }
672 
673  for (i = 0; i < nut->avf->nb_chapters; i++) {
674  ret = avio_open_dyn_buf(&dyn_bc);
675  if (ret < 0)
676  return ret;
677  ret = write_chapter(nut, dyn_bc, i);
678  if (ret < 0) {
679  uint8_t *buf;
680  avio_close_dyn_buf(dyn_bc, &buf);
681  av_freep(&buf);
682  return ret;
683  }
684  put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
685  }
686 
687  nut->last_syncpoint_pos = INT_MIN;
688  nut->header_count++;
689  return 0;
690 }
691 
693 {
694  NUTContext *nut = s->priv_data;
695  AVIOContext *bc = s->pb;
696  int i, j, ret;
697 
698  nut->avf = s;
699 
700  nut->version = FFMAX(NUT_STABLE_VERSION, 3 + !!nut->flags);
702  av_log(s, AV_LOG_ERROR,
703  "The additional syncpoint modes require version %d, "
704  "that is currently not finalized, "
705  "please set -f_strict experimental in order to enable it.\n",
706  nut->version);
707  return AVERROR_EXPERIMENTAL;
708  }
709 
710  nut->stream = av_calloc(s->nb_streams, sizeof(*nut->stream ));
711  nut->chapter = av_calloc(s->nb_chapters, sizeof(*nut->chapter));
712  nut->time_base= av_calloc(s->nb_streams +
713  s->nb_chapters, sizeof(*nut->time_base));
714  if (!nut->stream || !nut->chapter || !nut->time_base) {
715  av_freep(&nut->stream);
716  av_freep(&nut->chapter);
717  av_freep(&nut->time_base);
718  return AVERROR(ENOMEM);
719  }
720 
721  for (i = 0; i < s->nb_streams; i++) {
722  AVStream *st = s->streams[i];
723  int ssize;
724  AVRational time_base;
725  ff_parse_specific_params(st, &time_base.den, &ssize, &time_base.num);
726 
727  if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->sample_rate) {
728  time_base = (AVRational) {1, st->codec->sample_rate};
729  } else {
730  time_base = ff_choose_timebase(s, st, 48000);
731  }
732 
733  avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
734 
735  for (j = 0; j < nut->time_base_count; j++)
736  if (!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))) {
737  break;
738  }
739  nut->time_base[j] = time_base;
740  nut->stream[i].time_base = &nut->time_base[j];
741  if (j == nut->time_base_count)
742  nut->time_base_count++;
743 
744  if (INT64_C(1000) * time_base.num >= time_base.den)
745  nut->stream[i].msb_pts_shift = 7;
746  else
747  nut->stream[i].msb_pts_shift = 14;
748  nut->stream[i].max_pts_distance =
749  FFMAX(time_base.den, time_base.num) / time_base.num;
750  }
751 
752  for (i = 0; i < s->nb_chapters; i++) {
753  AVChapter *ch = s->chapters[i];
754 
755  for (j = 0; j < nut->time_base_count; j++)
756  if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
757  break;
758 
759  nut->time_base[j] = ch->time_base;
760  nut->chapter[i].time_base = &nut->time_base[j];
761  if (j == nut->time_base_count)
762  nut->time_base_count++;
763  }
764 
765  nut->max_distance = MAX_DISTANCE;
767  build_frame_code(s);
768  av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
769 
770  avio_write(bc, ID_STRING, strlen(ID_STRING));
771  avio_w8(bc, 0);
772 
773  if ((ret = write_headers(s, bc)) < 0)
774  return ret;
775 
776  if (s->avoid_negative_ts < 0)
777  s->avoid_negative_ts = 1;
778 
779  avio_flush(bc);
780 
781  return 0;
782 }
783 
785  AVPacket *pkt)
786 {
787  int flags = 0;
788 
789  if (pkt->flags & AV_PKT_FLAG_KEY)
790  flags |= FLAG_KEY;
791  if (pkt->stream_index != fc->stream_id)
792  flags |= FLAG_STREAM_ID;
793  if (pkt->size / fc->size_mul)
794  flags |= FLAG_SIZE_MSB;
795  if (pkt->pts - nus->last_pts != fc->pts_delta)
796  flags |= FLAG_CODED_PTS;
797  if (pkt->side_data_elems && nut->version > 3)
798  flags |= FLAG_SM_DATA;
799  if (pkt->size > 2 * nut->max_distance)
800  flags |= FLAG_CHECKSUM;
801  if (FFABS(pkt->pts - nus->last_pts) > nus->max_pts_distance)
802  flags |= FLAG_CHECKSUM;
803  if (pkt->size < nut->header_len[fc->header_idx] ||
804  (pkt->size > 4096 && fc->header_idx) ||
805  memcmp(pkt->data, nut->header[fc->header_idx],
806  nut->header_len[fc->header_idx]))
807  flags |= FLAG_HEADER_IDX;
808 
809  return flags | (fc->flags & FLAG_CODED);
810 }
811 
813 {
814  int i;
815  int best_i = 0;
816  int best_len = 0;
817 
818  if (pkt->size > 4096)
819  return 0;
820 
821  for (i = 1; i < nut->header_count; i++)
822  if (pkt->size >= nut->header_len[i]
823  && nut->header_len[i] > best_len
824  && !memcmp(pkt->data, nut->header[i], nut->header_len[i])) {
825  best_i = i;
826  best_len = nut->header_len[i];
827  }
828  return best_i;
829 }
830 
831 static int write_sm_data(AVFormatContext *s, AVIOContext *bc, AVPacket *pkt, int is_meta)
832 {
833  int ret, i, dyn_size;
834  unsigned flags;
835  AVIOContext *dyn_bc;
836  int sm_data_count = 0;
837  uint8_t tmp[256];
838  uint8_t *dyn_buf;
839 
840  ret = avio_open_dyn_buf(&dyn_bc);
841  if (ret < 0)
842  return ret;
843 
844  for (i = 0; i<pkt->side_data_elems; i++) {
845  const uint8_t *data = pkt->side_data[i].data;
846  int size = pkt->side_data[i].size;
847  const uint8_t *data_end = data + size;
848 
849  if (is_meta) {
852  if (!size || data[size-1]) {
853  ret = AVERROR(EINVAL);
854  goto fail;
855  }
856  while (data < data_end) {
857  const uint8_t *key = data;
858  const uint8_t *val = data + strlen(key) + 1;
859 
860  if(val >= data_end) {
861  ret = AVERROR(EINVAL);
862  goto fail;
863  }
864  put_str(dyn_bc, key);
865  put_s(dyn_bc, -1);
866  put_str(dyn_bc, val);
867  data = val + strlen(val) + 1;
868  sm_data_count++;
869  }
870  }
871  } else {
872  switch (pkt->side_data[i].type) {
873  case AV_PKT_DATA_PALETTE:
876  default:
877  if (pkt->side_data[i].type == AV_PKT_DATA_PALETTE) {
878  put_str(dyn_bc, "Palette");
879  } else if(pkt->side_data[i].type == AV_PKT_DATA_NEW_EXTRADATA) {
880  put_str(dyn_bc, "Extradata");
881  } else if(pkt->side_data[i].type == AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL) {
882  snprintf(tmp, sizeof(tmp), "CodecSpecificSide%"PRId64"", AV_RB64(data));
883  put_str(dyn_bc, tmp);
884  } else {
885  snprintf(tmp, sizeof(tmp), "UserData%s-SD-%d",
886  (s->flags & AVFMT_FLAG_BITEXACT) ? "Lavf" : LIBAVFORMAT_IDENT,
887  pkt->side_data[i].type);
888  put_str(dyn_bc, tmp);
889  }
890  put_s(dyn_bc, -2);
891  put_str(dyn_bc, "bin");
892  ff_put_v(dyn_bc, pkt->side_data[i].size);
893  avio_write(dyn_bc, data, pkt->side_data[i].size);
894  sm_data_count++;
895  break;
897  flags = bytestream_get_le32(&data);
899  put_str(dyn_bc, "Channels");
900  put_s(dyn_bc, bytestream_get_le32(&data));
901  sm_data_count++;
902  }
904  put_str(dyn_bc, "ChannelLayout");
905  put_s(dyn_bc, -2);
906  put_str(dyn_bc, "u64");
907  ff_put_v(bc, 8);
908  avio_write(dyn_bc, data, 8); data+=8;
909  sm_data_count++;
910  }
912  put_str(dyn_bc, "SampleRate");
913  put_s(dyn_bc, bytestream_get_le32(&data));
914  sm_data_count++;
915  }
917  put_str(dyn_bc, "Width");
918  put_s(dyn_bc, bytestream_get_le32(&data));
919  put_str(dyn_bc, "Height");
920  put_s(dyn_bc, bytestream_get_le32(&data));
921  sm_data_count+=2;
922  }
923  break;
925  if (AV_RL32(data)) {
926  put_str(dyn_bc, "SkipStart");
927  put_s(dyn_bc, (unsigned)AV_RL32(data));
928  sm_data_count++;
929  }
930  if (AV_RL32(data+4)) {
931  put_str(dyn_bc, "SkipEnd");
932  put_s(dyn_bc, (unsigned)AV_RL32(data+4));
933  sm_data_count++;
934  }
935  break;
938  // belongs into meta, not side data
939  break;
940  }
941  }
942  }
943 
944 fail:
945  ff_put_v(bc, sm_data_count);
946  dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
947  avio_write(bc, dyn_buf, dyn_size);
948  av_freep(&dyn_buf);
949 
950  return ret;
951 }
952 
954 {
955  NUTContext *nut = s->priv_data;
956  StreamContext *nus = &nut->stream[pkt->stream_index];
957  AVIOContext *bc = s->pb, *dyn_bc, *sm_bc = NULL;
958  FrameCode *fc;
959  int64_t coded_pts;
960  int best_length, frame_code, flags, needed_flags, i, header_idx;
961  int best_header_idx;
962  int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
963  int store_sp = 0;
964  int ret = 0;
965  int sm_size = 0;
966  int data_size = pkt->size;
967  uint8_t *sm_buf = NULL;
968 
969  if (pkt->pts < 0) {
970  av_log(s, AV_LOG_ERROR,
971  "Negative pts not supported stream %d, pts %"PRId64"\n",
972  pkt->stream_index, pkt->pts);
973  if (pkt->pts == AV_NOPTS_VALUE)
974  av_log(s, AV_LOG_ERROR, "Try to enable the genpts flag\n");
975  return AVERROR(EINVAL);
976  }
977 
978  if (pkt->side_data_elems && nut->version > 3) {
979  ret = avio_open_dyn_buf(&sm_bc);
980  if (ret < 0)
981  return ret;
982  ret = write_sm_data(s, sm_bc, pkt, 0);
983  if (ret >= 0)
984  ret = write_sm_data(s, sm_bc, pkt, 1);
985  sm_size = avio_close_dyn_buf(sm_bc, &sm_buf);
986  if (ret < 0)
987  goto fail;
988  data_size += sm_size;
989  }
990 
991  if (1LL << (20 + 3 * nut->header_count) <= avio_tell(bc))
992  write_headers(s, bc);
993 
994  if (key_frame && !(nus->last_flags & FLAG_KEY))
995  store_sp = 1;
996 
997  if (data_size + 30 /*FIXME check*/ + avio_tell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
998  store_sp = 1;
999 
1000 //FIXME: Ensure store_sp is 1 in the first place.
1001 
1002  if (store_sp &&
1003  (!(nut->flags & NUT_PIPE) || nut->last_syncpoint_pos == INT_MIN)) {
1004  int64_t sp_pos = INT64_MAX;
1005 
1006  ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
1007  for (i = 0; i < s->nb_streams; i++) {
1008  AVStream *st = s->streams[i];
1009  int64_t dts_tb = av_rescale_rnd(pkt->dts,
1010  nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
1011  nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
1012  AV_ROUND_DOWN);
1013  int index = av_index_search_timestamp(st, dts_tb,
1015  if (index >= 0) {
1016  sp_pos = FFMIN(sp_pos, st->index_entries[index].pos);
1017  if (!nut->write_index && 2*index > st->nb_index_entries) {
1018  memmove(st->index_entries,
1019  st->index_entries + index,
1020  sizeof(*st->index_entries) * (st->nb_index_entries - index));
1021  st->nb_index_entries -= index;
1022  }
1023  }
1024  }
1025 
1026  nut->last_syncpoint_pos = avio_tell(bc);
1027  ret = avio_open_dyn_buf(&dyn_bc);
1028  if (ret < 0)
1029  goto fail;
1030  put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
1031  ff_put_v(dyn_bc, sp_pos != INT64_MAX ? (nut->last_syncpoint_pos - sp_pos) >> 4 : 0);
1032 
1033  if (nut->flags & NUT_BROADCAST) {
1034  put_tt(nut, nus->time_base, dyn_bc,
1036  }
1037  put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
1038 
1039  if (nut->write_index) {
1040  if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0 /*unused*/, pkt->dts)) < 0)
1041  goto fail;
1042 
1043  if ((1ll<<60) % nut->sp_count == 0)
1044  for (i=0; i<s->nb_streams; i++) {
1045  int j;
1046  StreamContext *nus = &nut->stream[i];
1047  av_reallocp_array(&nus->keyframe_pts, 2*nut->sp_count, sizeof(*nus->keyframe_pts));
1048  if (!nus->keyframe_pts) {
1049  ret = AVERROR(ENOMEM);
1050  goto fail;
1051  }
1052  for (j=nut->sp_count == 1 ? 0 : nut->sp_count; j<2*nut->sp_count; j++)
1053  nus->keyframe_pts[j] = AV_NOPTS_VALUE;
1054  }
1055  }
1056  }
1058 
1059  coded_pts = pkt->pts & ((1 << nus->msb_pts_shift) - 1);
1060  if (ff_lsb2full(nus, coded_pts) != pkt->pts)
1061  coded_pts = pkt->pts + (1 << nus->msb_pts_shift);
1062 
1063  best_header_idx = find_best_header_idx(nut, pkt);
1064 
1065  best_length = INT_MAX;
1066  frame_code = -1;
1067  for (i = 0; i < 256; i++) {
1068  int length = 0;
1069  FrameCode *fc = &nut->frame_code[i];
1070  int flags = fc->flags;
1071 
1072  if (flags & FLAG_INVALID)
1073  continue;
1074  needed_flags = get_needed_flags(nut, nus, fc, pkt);
1075 
1076  if (flags & FLAG_CODED) {
1077  length++;
1078  flags = needed_flags;
1079  }
1080 
1081  if ((flags & needed_flags) != needed_flags)
1082  continue;
1083 
1084  if ((flags ^ needed_flags) & FLAG_KEY)
1085  continue;
1086 
1087  if (flags & FLAG_STREAM_ID)
1088  length += ff_get_v_length(pkt->stream_index);
1089 
1090  if (data_size % fc->size_mul != fc->size_lsb)
1091  continue;
1092  if (flags & FLAG_SIZE_MSB)
1093  length += ff_get_v_length(data_size / fc->size_mul);
1094 
1095  if (flags & FLAG_CHECKSUM)
1096  length += 4;
1097 
1098  if (flags & FLAG_CODED_PTS)
1099  length += ff_get_v_length(coded_pts);
1100 
1101  if ( (flags & FLAG_CODED)
1102  && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx] + 1) {
1103  flags |= FLAG_HEADER_IDX;
1104  }
1105 
1106  if (flags & FLAG_HEADER_IDX) {
1107  length += 1 - nut->header_len[best_header_idx];
1108  } else {
1109  length -= nut->header_len[fc->header_idx];
1110  }
1111 
1112  length *= 4;
1113  length += !(flags & FLAG_CODED_PTS);
1114  length += !(flags & FLAG_CHECKSUM);
1115 
1116  if (length < best_length) {
1117  best_length = length;
1118  frame_code = i;
1119  }
1120  }
1121  av_assert0(frame_code != -1);
1122 
1123  fc = &nut->frame_code[frame_code];
1124  flags = fc->flags;
1125  needed_flags = get_needed_flags(nut, nus, fc, pkt);
1126  header_idx = fc->header_idx;
1127 
1129  avio_w8(bc, frame_code);
1130  if (flags & FLAG_CODED) {
1131  ff_put_v(bc, (flags ^ needed_flags) & ~(FLAG_CODED));
1132  flags = needed_flags;
1133  }
1134  if (flags & FLAG_STREAM_ID) ff_put_v(bc, pkt->stream_index);
1135  if (flags & FLAG_CODED_PTS) ff_put_v(bc, coded_pts);
1136  if (flags & FLAG_SIZE_MSB ) ff_put_v(bc, data_size / fc->size_mul);
1137  if (flags & FLAG_HEADER_IDX) ff_put_v(bc, header_idx = best_header_idx);
1138 
1139  if (flags & FLAG_CHECKSUM) avio_wl32(bc, ffio_get_checksum(bc));
1140  else ffio_get_checksum(bc);
1141 
1142  if (flags & FLAG_SM_DATA) {
1143  avio_write(bc, sm_buf, sm_size);
1144  }
1145  avio_write(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
1146 
1147  nus->last_flags = flags;
1148  nus->last_pts = pkt->pts;
1149 
1150  //FIXME just store one per syncpoint
1151  if (flags & FLAG_KEY && !(nut->flags & NUT_PIPE)) {
1153  s->streams[pkt->stream_index],
1154  nut->last_syncpoint_pos,
1155  pkt->pts,
1156  0,
1157  0,
1159  if (nus->keyframe_pts && nus->keyframe_pts[nut->sp_count] == AV_NOPTS_VALUE)
1160  nus->keyframe_pts[nut->sp_count] = pkt->pts;
1161  }
1162 
1163  if (!nut->max_pts_tb || av_compare_ts(nut->max_pts, *nut->max_pts_tb, pkt->pts, *nus->time_base) < 0) {
1164  nut->max_pts = pkt->pts;
1165  nut->max_pts_tb = nus->time_base;
1166  }
1167 
1168 fail:
1169  av_freep(&sm_buf);
1170 
1171  return ret;
1172 }
1173 
1175 {
1176  NUTContext *nut = s->priv_data;
1177  AVIOContext *bc = s->pb, *dyn_bc;
1178  int i, ret;
1179 
1180  while (nut->header_count < 3)
1181  write_headers(s, bc);
1182 
1183  ret = avio_open_dyn_buf(&dyn_bc);
1184  if (ret >= 0 && nut->sp_count) {
1185  av_assert1(nut->write_index);
1186  write_index(nut, dyn_bc);
1187  put_packet(nut, bc, dyn_bc, 1, INDEX_STARTCODE);
1188  }
1189 
1190  ff_nut_free_sp(nut);
1191  for (i=0; i<s->nb_streams; i++)
1192  av_freep(&nut->stream[i].keyframe_pts);
1193 
1194  av_freep(&nut->stream);
1195  av_freep(&nut->chapter);
1196  av_freep(&nut->time_base);
1197 
1198  return 0;
1199 }
1200 
1201 #define OFFSET(x) offsetof(NUTContext, x)
1202 #define E AV_OPT_FLAG_ENCODING_PARAM
1203 static const AVOption options[] = {
1204  { "syncpoints", "NUT syncpoint behaviour", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, E, "syncpoints" },
1205  { "default", "", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, INT_MIN, INT_MAX, E, "syncpoints" },
1206  { "none", "Disable syncpoints, low overhead and unseekable", 0, AV_OPT_TYPE_CONST, {.i64 = NUT_PIPE}, INT_MIN, INT_MAX, E, "syncpoints" },
1207  { "timestamped", "Extend syncpoints with a wallclock timestamp", 0, AV_OPT_TYPE_CONST, {.i64 = NUT_BROADCAST}, INT_MIN, INT_MAX, E, "syncpoints" },
1208  { "write_index", "Write index", OFFSET(write_index), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E, },
1209  { NULL },
1210 };
1211 
1212 static const AVClass class = {
1213  .class_name = "nutenc",
1214  .item_name = av_default_item_name,
1215  .option = options,
1217 };
1218 
1220  .name = "nut",
1221  .long_name = NULL_IF_CONFIG_SMALL("NUT"),
1222  .mime_type = "video/x-nut",
1223  .extensions = "nut",
1224  .priv_data_size = sizeof(NUTContext),
1225  .audio_codec = CONFIG_LIBVORBIS ? AV_CODEC_ID_VORBIS :
1226  CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_MP2,
1227  .video_codec = AV_CODEC_ID_MPEG4,
1232  .codec_tag = ff_nut_codec_tags,
1233  .priv_class = &class,
1234 };