FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
nutdec.c
Go to the documentation of this file.
1 /*
2  * "NUT" Container Format demuxer
3  * Copyright (c) 2004-2006 Michael Niedermayer
4  * Copyright (c) 2003 Alex Beregszaszi
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22 
23 #include "libavutil/avstring.h"
24 #include "libavutil/avassert.h"
25 #include "libavutil/bswap.h"
26 #include "libavutil/dict.h"
27 #include "libavutil/intreadwrite.h"
28 #include "libavutil/mathematics.h"
29 #include "libavutil/tree.h"
30 #include "libavcodec/bytestream.h"
31 #include "avio_internal.h"
32 #include "isom.h"
33 #include "nut.h"
34 #include "riff.h"
35 
36 #define NUT_MAX_STREAMS 256 /* arbitrary sanity check value */
37 
38 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
39  int64_t *pos_arg, int64_t pos_limit);
40 
41 static int get_str(AVIOContext *bc, char *string, unsigned int maxlen)
42 {
43  unsigned int len = ffio_read_varlen(bc);
44 
45  if (len && maxlen)
46  avio_read(bc, string, FFMIN(len, maxlen));
47  while (len > maxlen) {
48  avio_r8(bc);
49  len--;
50  }
51 
52  if (maxlen)
53  string[FFMIN(len, maxlen - 1)] = 0;
54 
55  if (maxlen == len)
56  return -1;
57  else
58  return 0;
59 }
60 
61 static int64_t get_s(AVIOContext *bc)
62 {
63  int64_t v = ffio_read_varlen(bc) + 1;
64 
65  if (v & 1)
66  return -(v >> 1);
67  else
68  return (v >> 1);
69 }
70 
71 static uint64_t get_fourcc(AVIOContext *bc)
72 {
73  unsigned int len = ffio_read_varlen(bc);
74 
75  if (len == 2)
76  return avio_rl16(bc);
77  else if (len == 4)
78  return avio_rl32(bc);
79  else {
80  av_log(NULL, AV_LOG_ERROR, "Unsupported fourcc length %d\n", len);
81  return -1;
82  }
83 }
84 
85 #ifdef TRACE
86 static inline uint64_t get_v_trace(AVIOContext *bc, const char *file,
87  const char *func, int line)
88 {
89  uint64_t v = ffio_read_varlen(bc);
90 
91  av_log(NULL, AV_LOG_DEBUG, "get_v %5"PRId64" / %"PRIX64" in %s %s:%d\n",
92  v, v, file, func, line);
93  return v;
94 }
95 
96 static inline int64_t get_s_trace(AVIOContext *bc, const char *file,
97  const char *func, int line)
98 {
99  int64_t v = get_s(bc);
100 
101  av_log(NULL, AV_LOG_DEBUG, "get_s %5"PRId64" / %"PRIX64" in %s %s:%d\n",
102  v, v, file, func, line);
103  return v;
104 }
105 
106 static inline uint64_t get_4cc_trace(AVIOContext *bc, char *file,
107  char *func, int line)
108 {
109  uint64_t v = get_fourcc(bc);
110 
111  av_log(NULL, AV_LOG_DEBUG, "get_fourcc %5"PRId64" / %"PRIX64" in %s %s:%d\n",
112  v, v, file, func, line);
113  return v;
114 }
115 #define ffio_read_varlen(bc) get_v_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
116 #define get_s(bc) get_s_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
117 #define get_fourcc(bc) get_4cc_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
118 #endif
119 
121  int calculate_checksum, uint64_t startcode)
122 {
123  int64_t size;
124 // start = avio_tell(bc) - 8;
125 
126  startcode = av_be2ne64(startcode);
127  startcode = ff_crc04C11DB7_update(0, (uint8_t*) &startcode, 8);
128 
130  size = ffio_read_varlen(bc);
131  if (size > 4096)
132  avio_rb32(bc);
133  if (ffio_get_checksum(bc) && size > 4096)
134  return -1;
135 
136  ffio_init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
137 
138  return size;
139 }
140 
141 static uint64_t find_any_startcode(AVIOContext *bc, int64_t pos)
142 {
143  uint64_t state = 0;
144 
145  if (pos >= 0)
146  /* Note, this may fail if the stream is not seekable, but that should
147  * not matter, as in this case we simply start where we currently are */
148  avio_seek(bc, pos, SEEK_SET);
149  while (!url_feof(bc)) {
150  state = (state << 8) | avio_r8(bc);
151  if ((state >> 56) != 'N')
152  continue;
153  switch (state) {
154  case MAIN_STARTCODE:
155  case STREAM_STARTCODE:
156  case SYNCPOINT_STARTCODE:
157  case INFO_STARTCODE:
158  case INDEX_STARTCODE:
159  return state;
160  }
161  }
162 
163  return 0;
164 }
165 
166 /**
167  * Find the given startcode.
168  * @param code the startcode
169  * @param pos the start position of the search, or -1 if the current position
170  * @return the position of the startcode or -1 if not found
171  */
172 static int64_t find_startcode(AVIOContext *bc, uint64_t code, int64_t pos)
173 {
174  for (;;) {
175  uint64_t startcode = find_any_startcode(bc, pos);
176  if (startcode == code)
177  return avio_tell(bc) - 8;
178  else if (startcode == 0)
179  return -1;
180  pos = -1;
181  }
182 }
183 
184 static int nut_probe(AVProbeData *p)
185 {
186  int i;
187 
188  for (i = 0; i < p->buf_size-8; i++) {
189  if (AV_RB32(p->buf+i) != MAIN_STARTCODE>>32)
190  continue;
191  if (AV_RB32(p->buf+i+4) == (MAIN_STARTCODE & 0xFFFFFFFF))
192  return AVPROBE_SCORE_MAX;
193  }
194  return 0;
195 }
196 
197 #define GET_V(dst, check) \
198  do { \
199  tmp = ffio_read_varlen(bc); \
200  if (!(check)) { \
201  av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp); \
202  return AVERROR_INVALIDDATA; \
203  } \
204  dst = tmp; \
205  } while (0)
206 
207 static int skip_reserved(AVIOContext *bc, int64_t pos)
208 {
209  pos -= avio_tell(bc);
210  if (pos < 0) {
211  avio_seek(bc, pos, SEEK_CUR);
212  return AVERROR_INVALIDDATA;
213  } else {
214  while (pos--)
215  avio_r8(bc);
216  return 0;
217  }
218 }
219 
221 {
222  AVFormatContext *s = nut->avf;
223  AVIOContext *bc = s->pb;
224  uint64_t tmp, end;
225  unsigned int stream_count;
226  int i, j, count;
227  int tmp_stream, tmp_mul, tmp_pts, tmp_size, tmp_res, tmp_head_idx;
228 
229  end = get_packetheader(nut, bc, 1, MAIN_STARTCODE);
230  end += avio_tell(bc);
231 
232  nut->version = ffio_read_varlen(bc);
233  if (nut->version < NUT_MIN_VERSION &&
234  nut->version > NUT_MAX_VERSION) {
235  av_log(s, AV_LOG_ERROR, "Version %d not supported.\n",
236  nut->version);
237  return AVERROR(ENOSYS);
238  }
239  if (nut->version > 3)
240  nut->minor_version = ffio_read_varlen(bc);
241 
242  GET_V(stream_count, tmp > 0 && tmp <= NUT_MAX_STREAMS);
243 
244  nut->max_distance = ffio_read_varlen(bc);
245  if (nut->max_distance > 65536) {
246  av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);
247  nut->max_distance = 65536;
248  }
249 
250  GET_V(nut->time_base_count, tmp > 0 && tmp < INT_MAX / sizeof(AVRational));
251  nut->time_base = av_malloc(nut->time_base_count * sizeof(AVRational));
252  if (!nut->time_base)
253  return AVERROR(ENOMEM);
254 
255  for (i = 0; i < nut->time_base_count; i++) {
256  GET_V(nut->time_base[i].num, tmp > 0 && tmp < (1ULL << 31));
257  GET_V(nut->time_base[i].den, tmp > 0 && tmp < (1ULL << 31));
258  if (av_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1) {
259  av_log(s, AV_LOG_ERROR, "time base invalid\n");
260  return AVERROR_INVALIDDATA;
261  }
262  }
263  tmp_pts = 0;
264  tmp_mul = 1;
265  tmp_stream = 0;
266  tmp_head_idx = 0;
267  for (i = 0; i < 256;) {
268  int tmp_flags = ffio_read_varlen(bc);
269  int tmp_fields = ffio_read_varlen(bc);
270 
271  if (tmp_fields > 0)
272  tmp_pts = get_s(bc);
273  if (tmp_fields > 1)
274  tmp_mul = ffio_read_varlen(bc);
275  if (tmp_fields > 2)
276  tmp_stream = ffio_read_varlen(bc);
277  if (tmp_fields > 3)
278  tmp_size = ffio_read_varlen(bc);
279  else
280  tmp_size = 0;
281  if (tmp_fields > 4)
282  tmp_res = ffio_read_varlen(bc);
283  else
284  tmp_res = 0;
285  if (tmp_fields > 5)
286  count = ffio_read_varlen(bc);
287  else
288  count = tmp_mul - tmp_size;
289  if (tmp_fields > 6)
290  get_s(bc);
291  if (tmp_fields > 7)
292  tmp_head_idx = ffio_read_varlen(bc);
293 
294  while (tmp_fields-- > 8)
295  ffio_read_varlen(bc);
296 
297  if (count == 0 || i + count > 256) {
298  av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
299  return AVERROR_INVALIDDATA;
300  }
301  if (tmp_stream >= stream_count) {
302  av_log(s, AV_LOG_ERROR, "illegal stream number\n");
303  return AVERROR_INVALIDDATA;
304  }
305 
306  for (j = 0; j < count; j++, i++) {
307  if (i == 'N') {
308  nut->frame_code[i].flags = FLAG_INVALID;
309  j--;
310  continue;
311  }
312  nut->frame_code[i].flags = tmp_flags;
313  nut->frame_code[i].pts_delta = tmp_pts;
314  nut->frame_code[i].stream_id = tmp_stream;
315  nut->frame_code[i].size_mul = tmp_mul;
316  nut->frame_code[i].size_lsb = tmp_size + j;
317  nut->frame_code[i].reserved_count = tmp_res;
318  nut->frame_code[i].header_idx = tmp_head_idx;
319  }
320  }
321  av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
322 
323  if (end > avio_tell(bc) + 4) {
324  int rem = 1024;
325  GET_V(nut->header_count, tmp < 128U);
326  nut->header_count++;
327  for (i = 1; i < nut->header_count; i++) {
328  uint8_t *hdr;
329  GET_V(nut->header_len[i], tmp > 0 && tmp < 256);
330  rem -= nut->header_len[i];
331  if (rem < 0) {
332  av_log(s, AV_LOG_ERROR, "invalid elision header\n");
333  return AVERROR_INVALIDDATA;
334  }
335  hdr = av_malloc(nut->header_len[i]);
336  if (!hdr)
337  return AVERROR(ENOMEM);
338  avio_read(bc, hdr, nut->header_len[i]);
339  nut->header[i] = hdr;
340  }
341  av_assert0(nut->header_len[0] == 0);
342  }
343 
344  // flags had been effectively introduced in version 4
345  if (nut->version > 3 && end > avio_tell(bc) + 4) {
346  nut->flags = ffio_read_varlen(bc);
347  }
348 
349  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
350  av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
351  return AVERROR_INVALIDDATA;
352  }
353 
354  nut->stream = av_calloc(stream_count, sizeof(StreamContext));
355  if (!nut->stream)
356  return AVERROR(ENOMEM);
357  for (i = 0; i < stream_count; i++)
358  avformat_new_stream(s, NULL);
359 
360  return 0;
361 }
362 
364 {
365  AVFormatContext *s = nut->avf;
366  AVIOContext *bc = s->pb;
367  StreamContext *stc;
368  int class, stream_id;
369  uint64_t tmp, end;
370  AVStream *st;
371 
372  end = get_packetheader(nut, bc, 1, STREAM_STARTCODE);
373  end += avio_tell(bc);
374 
375  GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);
376  stc = &nut->stream[stream_id];
377  st = s->streams[stream_id];
378  if (!st)
379  return AVERROR(ENOMEM);
380 
381  class = ffio_read_varlen(bc);
382  tmp = get_fourcc(bc);
383  st->codec->codec_tag = tmp;
384  switch (class) {
385  case 0:
387  st->codec->codec_id = av_codec_get_id((const AVCodecTag * const []) {
391  0
392  },
393  tmp);
394  break;
395  case 1:
397  st->codec->codec_id = av_codec_get_id((const AVCodecTag * const []) {
401  0
402  },
403  tmp);
404  break;
405  case 2:
408  break;
409  case 3:
412  break;
413  default:
414  av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
415  return AVERROR(ENOSYS);
416  }
417  if (class < 3 && st->codec->codec_id == AV_CODEC_ID_NONE)
418  av_log(s, AV_LOG_ERROR,
419  "Unknown codec tag '0x%04x' for stream number %d\n",
420  (unsigned int) tmp, stream_id);
421 
422  GET_V(stc->time_base_id, tmp < nut->time_base_count);
423  GET_V(stc->msb_pts_shift, tmp < 16);
425  GET_V(stc->decode_delay, tmp < 1000); // sanity limit, raise this if Moore's law is true
426  st->codec->has_b_frames = stc->decode_delay;
427  ffio_read_varlen(bc); // stream flags
428 
429  GET_V(st->codec->extradata_size, tmp < (1 << 30));
430  if (st->codec->extradata_size) {
431  if (ff_get_extradata(st->codec, bc, st->codec->extradata_size) < 0)
432  return AVERROR(ENOMEM);
433  }
434 
435  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
436  GET_V(st->codec->width, tmp > 0);
437  GET_V(st->codec->height, tmp > 0);
440  if ((!st->sample_aspect_ratio.num) != (!st->sample_aspect_ratio.den)) {
441  av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n",
443  return AVERROR_INVALIDDATA;
444  }
445  ffio_read_varlen(bc); /* csp type */
446  } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
447  GET_V(st->codec->sample_rate, tmp > 0);
448  ffio_read_varlen(bc); // samplerate_den
449  GET_V(st->codec->channels, tmp > 0);
450  }
451  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
452  av_log(s, AV_LOG_ERROR,
453  "stream header %d checksum mismatch\n", stream_id);
454  return AVERROR_INVALIDDATA;
455  }
456  stc->time_base = &nut->time_base[stc->time_base_id];
457  avpriv_set_pts_info(s->streams[stream_id], 63, stc->time_base->num,
458  stc->time_base->den);
459  return 0;
460 }
461 
463  int stream_id)
464 {
465  int flag = 0, i;
466 
467  for (i = 0; ff_nut_dispositions[i].flag; ++i)
468  if (!strcmp(ff_nut_dispositions[i].str, value))
469  flag = ff_nut_dispositions[i].flag;
470  if (!flag)
471  av_log(avf, AV_LOG_INFO, "unknown disposition type '%s'\n", value);
472  for (i = 0; i < avf->nb_streams; ++i)
473  if (stream_id == i || stream_id == -1)
474  avf->streams[i]->disposition |= flag;
475 }
476 
478 {
479  AVFormatContext *s = nut->avf;
480  AVIOContext *bc = s->pb;
481  uint64_t tmp, chapter_start, chapter_len;
482  unsigned int stream_id_plus1, count;
483  int chapter_id, i;
484  int64_t value, end;
485  char name[256], str_value[1024], type_str[256];
486  const char *type;
487  AVChapter *chapter = NULL;
488  AVStream *st = NULL;
489  AVDictionary **metadata = NULL;
490 
491  end = get_packetheader(nut, bc, 1, INFO_STARTCODE);
492  end += avio_tell(bc);
493 
494  GET_V(stream_id_plus1, tmp <= s->nb_streams);
495  chapter_id = get_s(bc);
496  chapter_start = ffio_read_varlen(bc);
497  chapter_len = ffio_read_varlen(bc);
498  count = ffio_read_varlen(bc);
499 
500  if (chapter_id && !stream_id_plus1) {
501  int64_t start = chapter_start / nut->time_base_count;
502  chapter = avpriv_new_chapter(s, chapter_id,
503  nut->time_base[chapter_start %
504  nut->time_base_count],
505  start, start + chapter_len, NULL);
506  metadata = &chapter->metadata;
507  } else if (stream_id_plus1) {
508  st = s->streams[stream_id_plus1 - 1];
509  metadata = &st->metadata;
510  } else
511  metadata = &s->metadata;
512 
513  for (i = 0; i < count; i++) {
514  get_str(bc, name, sizeof(name));
515  value = get_s(bc);
516  if (value == -1) {
517  type = "UTF-8";
518  get_str(bc, str_value, sizeof(str_value));
519  } else if (value == -2) {
520  get_str(bc, type_str, sizeof(type_str));
521  type = type_str;
522  get_str(bc, str_value, sizeof(str_value));
523  } else if (value == -3) {
524  type = "s";
525  value = get_s(bc);
526  } else if (value == -4) {
527  type = "t";
528  value = ffio_read_varlen(bc);
529  } else if (value < -4) {
530  type = "r";
531  get_s(bc);
532  } else {
533  type = "v";
534  }
535 
536  if (stream_id_plus1 > s->nb_streams) {
537  av_log(s, AV_LOG_ERROR, "invalid stream id for info packet\n");
538  continue;
539  }
540 
541  if (!strcmp(type, "UTF-8")) {
542  if (chapter_id == 0 && !strcmp(name, "Disposition")) {
543  set_disposition_bits(s, str_value, stream_id_plus1 - 1);
544  continue;
545  }
546 
547  if (stream_id_plus1 && !strcmp(name, "r_frame_rate")) {
548  sscanf(str_value, "%d/%d", &st->r_frame_rate.num, &st->r_frame_rate.den);
549  if (st->r_frame_rate.num >= 1000LL*st->r_frame_rate.den)
550  st->r_frame_rate.num = st->r_frame_rate.den = 0;
551  continue;
552  }
553 
554  if (metadata && av_strcasecmp(name, "Uses") &&
555  av_strcasecmp(name, "Depends") && av_strcasecmp(name, "Replaces"))
556  av_dict_set(metadata, name, str_value, 0);
557  }
558  }
559 
560  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
561  av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
562  return AVERROR_INVALIDDATA;
563  }
564  return 0;
565 }
566 
567 static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr)
568 {
569  AVFormatContext *s = nut->avf;
570  AVIOContext *bc = s->pb;
571  int64_t end;
572  uint64_t tmp;
573  int ret;
574 
575  nut->last_syncpoint_pos = avio_tell(bc) - 8;
576 
577  end = get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
578  end += avio_tell(bc);
579 
580  tmp = ffio_read_varlen(bc);
581  *back_ptr = nut->last_syncpoint_pos - 16 * ffio_read_varlen(bc);
582  if (*back_ptr < 0)
583  return AVERROR_INVALIDDATA;
584 
585  ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count],
586  tmp / nut->time_base_count);
587 
588  if (nut->flags & NUT_BROADCAST) {
589  tmp = ffio_read_varlen(bc);
590  av_log(s, AV_LOG_VERBOSE, "Syncpoint wallclock %"PRId64"\n",
591  av_rescale_q(tmp / nut->time_base_count,
592  nut->time_base[tmp % nut->time_base_count],
593  AV_TIME_BASE_Q));
594  }
595 
596  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
597  av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
598  return AVERROR_INVALIDDATA;
599  }
600 
601  *ts = tmp / nut->time_base_count *
602  av_q2d(nut->time_base[tmp % nut->time_base_count]) * AV_TIME_BASE;
603 
604  if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts)) < 0)
605  return ret;
606 
607  return 0;
608 }
609 
610 //FIXME calculate exactly, this is just a good approximation.
611 static int64_t find_duration(NUTContext *nut, int64_t filesize)
612 {
613  AVFormatContext *s = nut->avf;
614  int64_t duration = 0;
615 
616  ff_find_last_ts(s, -1, &duration, NULL, nut_read_timestamp);
617 
618  if(duration > 0)
620  return duration;
621 }
622 
624 {
625  AVFormatContext *s = nut->avf;
626  AVIOContext *bc = s->pb;
627  uint64_t tmp, end;
628  int i, j, syncpoint_count;
629  int64_t filesize = avio_size(bc);
630  int64_t *syncpoints;
631  uint64_t max_pts;
632  int8_t *has_keyframe;
633  int ret = AVERROR_INVALIDDATA;
634 
635  if(filesize <= 0)
636  return -1;
637 
638  avio_seek(bc, filesize - 12, SEEK_SET);
639  avio_seek(bc, filesize - avio_rb64(bc), SEEK_SET);
640  if (avio_rb64(bc) != INDEX_STARTCODE) {
641  av_log(s, AV_LOG_ERROR, "no index at the end\n");
642 
643  if(s->duration<=0)
644  s->duration = find_duration(nut, filesize);
645  return ret;
646  }
647 
648  end = get_packetheader(nut, bc, 1, INDEX_STARTCODE);
649  end += avio_tell(bc);
650 
651  max_pts = ffio_read_varlen(bc);
652  s->duration = av_rescale_q(max_pts / nut->time_base_count,
653  nut->time_base[max_pts % nut->time_base_count],
656 
657  GET_V(syncpoint_count, tmp < INT_MAX / 8 && tmp > 0);
658  syncpoints = av_malloc_array(syncpoint_count, sizeof(int64_t));
659  has_keyframe = av_malloc_array(syncpoint_count + 1, sizeof(int8_t));
660  if (!syncpoints || !has_keyframe) {
661  ret = AVERROR(ENOMEM);
662  goto fail;
663  }
664  for (i = 0; i < syncpoint_count; i++) {
665  syncpoints[i] = ffio_read_varlen(bc);
666  if (syncpoints[i] <= 0)
667  goto fail;
668  if (i)
669  syncpoints[i] += syncpoints[i - 1];
670  }
671 
672  for (i = 0; i < s->nb_streams; i++) {
673  int64_t last_pts = -1;
674  for (j = 0; j < syncpoint_count;) {
675  uint64_t x = ffio_read_varlen(bc);
676  int type = x & 1;
677  int n = j;
678  x >>= 1;
679  if (type) {
680  int flag = x & 1;
681  x >>= 1;
682  if (n + x >= syncpoint_count + 1) {
683  av_log(s, AV_LOG_ERROR, "index overflow A %d + %"PRIu64" >= %d\n", n, x, syncpoint_count + 1);
684  goto fail;
685  }
686  while (x--)
687  has_keyframe[n++] = flag;
688  has_keyframe[n++] = !flag;
689  } else {
690  while (x != 1) {
691  if (n >= syncpoint_count + 1) {
692  av_log(s, AV_LOG_ERROR, "index overflow B\n");
693  goto fail;
694  }
695  has_keyframe[n++] = x & 1;
696  x >>= 1;
697  }
698  }
699  if (has_keyframe[0]) {
700  av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");
701  goto fail;
702  }
703  av_assert0(n <= syncpoint_count + 1);
704  for (; j < n && j < syncpoint_count; j++) {
705  if (has_keyframe[j]) {
706  uint64_t B, A = ffio_read_varlen(bc);
707  if (!A) {
708  A = ffio_read_varlen(bc);
709  B = ffio_read_varlen(bc);
710  // eor_pts[j][i] = last_pts + A + B
711  } else
712  B = 0;
713  av_add_index_entry(s->streams[i], 16 * syncpoints[j - 1],
714  last_pts + A, 0, 0, AVINDEX_KEYFRAME);
715  last_pts += A + B;
716  }
717  }
718  }
719  }
720 
721  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
722  av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
723  goto fail;
724  }
725  ret = 0;
726 
727 fail:
728  av_free(syncpoints);
729  av_free(has_keyframe);
730  return ret;
731 }
732 
734 {
735  NUTContext *nut = s->priv_data;
736  AVIOContext *bc = s->pb;
737  int64_t pos;
738  int initialized_stream_count;
739 
740  nut->avf = s;
741 
742  /* main header */
743  pos = 0;
744  do {
745  pos = find_startcode(bc, MAIN_STARTCODE, pos) + 1;
746  if (pos < 0 + 1) {
747  av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
748  return AVERROR_INVALIDDATA;
749  }
750  } while (decode_main_header(nut) < 0);
751 
752  /* stream headers */
753  pos = 0;
754  for (initialized_stream_count = 0; initialized_stream_count < s->nb_streams;) {
755  pos = find_startcode(bc, STREAM_STARTCODE, pos) + 1;
756  if (pos < 0 + 1) {
757  av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
758  return AVERROR_INVALIDDATA;
759  }
760  if (decode_stream_header(nut) >= 0)
761  initialized_stream_count++;
762  }
763 
764  /* info headers */
765  pos = 0;
766  for (;;) {
767  uint64_t startcode = find_any_startcode(bc, pos);
768  pos = avio_tell(bc);
769 
770  if (startcode == 0) {
771  av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
772  return AVERROR_INVALIDDATA;
773  } else if (startcode == SYNCPOINT_STARTCODE) {
774  nut->next_startcode = startcode;
775  break;
776  } else if (startcode != INFO_STARTCODE) {
777  continue;
778  }
779 
780  decode_info_header(nut);
781  }
782 
783  s->data_offset = pos - 8;
784 
785  if (bc->seekable) {
786  int64_t orig_pos = avio_tell(bc);
788  avio_seek(bc, orig_pos, SEEK_SET);
789  }
791 
793 
794  return 0;
795 }
796 
797 static int read_sm_data(AVFormatContext *s, AVIOContext *bc, AVPacket *pkt, int is_meta, int64_t maxpos)
798 {
799  int count = ffio_read_varlen(bc);
800  int skip_start = 0;
801  int skip_end = 0;
802  int channels = 0;
803  int64_t channel_layout = 0;
804  int sample_rate = 0;
805  int width = 0;
806  int height = 0;
807  int i;
808 
809  for (i=0; i<count; i++) {
810  uint8_t name[256], str_value[256], type_str[256];
811  int value;
812  if (avio_tell(bc) >= maxpos)
813  return AVERROR_INVALIDDATA;
814  get_str(bc, name, sizeof(name));
815  value = get_s(bc);
816 
817  if (value == -1) {
818  get_str(bc, str_value, sizeof(str_value));
819  av_log(s, AV_LOG_WARNING, "Unknown string %s / %s\n", name, str_value);
820  } else if (value == -2) {
821  uint8_t *dst = NULL;
822  int64_t v64, value_len;
823 
824  get_str(bc, type_str, sizeof(type_str));
825  value_len = ffio_read_varlen(bc);
826  if (avio_tell(bc) + value_len >= maxpos)
827  return AVERROR_INVALIDDATA;
828  if (!strcmp(name, "Palette")) {
829  dst = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, value_len);
830  } else if (!strcmp(name, "Extradata")) {
831  dst = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, value_len);
832  } else if (sscanf(name, "CodecSpecificSide%"SCNd64"", &v64) == 1) {
834  if(!dst)
835  return AVERROR(ENOMEM);
836  AV_WB64(dst, v64);
837  dst += 8;
838  } else if (!strcmp(name, "ChannelLayout") && value_len == 8) {
839  channel_layout = avio_rl64(bc);
840  continue;
841  } else {
842  av_log(s, AV_LOG_WARNING, "Unknown data %s / %s\n", name, type_str);
843  avio_skip(bc, value_len);
844  continue;
845  }
846  if(!dst)
847  return AVERROR(ENOMEM);
848  avio_read(bc, dst, value_len);
849  } else if (value == -3) {
850  value = get_s(bc);
851  } else if (value == -4) {
852  value = ffio_read_varlen(bc);
853  } else if (value < -4) {
854  get_s(bc);
855  } else {
856  if (!strcmp(name, "SkipStart")) {
857  skip_start = value;
858  } else if (!strcmp(name, "SkipEnd")) {
859  skip_end = value;
860  } else if (!strcmp(name, "Channels")) {
861  channels = value;
862  } else if (!strcmp(name, "SampleRate")) {
863  sample_rate = value;
864  } else if (!strcmp(name, "Width")) {
865  width = value;
866  } else if (!strcmp(name, "Height")) {
867  height = value;
868  } else {
869  av_log(s, AV_LOG_WARNING, "Unknown integer %s\n", name);
870  }
871  }
872  }
873 
874  if (channels || channel_layout || sample_rate || width || height) {
876  if (!dst)
877  return AVERROR(ENOMEM);
878  bytestream_put_le32(&dst,
880  AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT*(!!channel_layout) +
881  AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE*(!!sample_rate) +
882  AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS*(!!(width|height))
883  );
884  if (channels)
885  bytestream_put_le32(&dst, channels);
886  if (channel_layout)
887  bytestream_put_le64(&dst, channel_layout);
888  if (sample_rate)
889  bytestream_put_le32(&dst, sample_rate);
890  if (width || height){
891  bytestream_put_le32(&dst, width);
892  bytestream_put_le32(&dst, height);
893  }
894  }
895 
896  if (skip_start || skip_end) {
898  if (!dst)
899  return AVERROR(ENOMEM);
900  AV_WL32(dst, skip_start);
901  AV_WL32(dst+4, skip_end);
902  }
903 
904  return 0;
905 }
906 
907 static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id,
908  uint8_t *header_idx, int frame_code)
909 {
910  AVFormatContext *s = nut->avf;
911  AVIOContext *bc = s->pb;
912  StreamContext *stc;
913  int size, flags, size_mul, pts_delta, i, reserved_count;
914  uint64_t tmp;
915 
916  if (!(nut->flags & NUT_PIPE) &&
917  avio_tell(bc) > nut->last_syncpoint_pos + nut->max_distance) {
918  av_log(s, AV_LOG_ERROR,
919  "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n",
920  avio_tell(bc), nut->last_syncpoint_pos, nut->max_distance);
921  return AVERROR_INVALIDDATA;
922  }
923 
924  flags = nut->frame_code[frame_code].flags;
925  size_mul = nut->frame_code[frame_code].size_mul;
926  size = nut->frame_code[frame_code].size_lsb;
927  *stream_id = nut->frame_code[frame_code].stream_id;
928  pts_delta = nut->frame_code[frame_code].pts_delta;
929  reserved_count = nut->frame_code[frame_code].reserved_count;
930  *header_idx = nut->frame_code[frame_code].header_idx;
931 
932  if (flags & FLAG_INVALID)
933  return AVERROR_INVALIDDATA;
934  if (flags & FLAG_CODED)
935  flags ^= ffio_read_varlen(bc);
936  if (flags & FLAG_STREAM_ID) {
937  GET_V(*stream_id, tmp < s->nb_streams);
938  }
939  stc = &nut->stream[*stream_id];
940  if (flags & FLAG_CODED_PTS) {
941  int coded_pts = ffio_read_varlen(bc);
942  // FIXME check last_pts validity?
943  if (coded_pts < (1 << stc->msb_pts_shift)) {
944  *pts = ff_lsb2full(stc, coded_pts);
945  } else
946  *pts = coded_pts - (1LL << stc->msb_pts_shift);
947  } else
948  *pts = stc->last_pts + pts_delta;
949  if (flags & FLAG_SIZE_MSB)
950  size += size_mul * ffio_read_varlen(bc);
951  if (flags & FLAG_MATCH_TIME)
952  get_s(bc);
953  if (flags & FLAG_HEADER_IDX)
954  *header_idx = ffio_read_varlen(bc);
955  if (flags & FLAG_RESERVED)
956  reserved_count = ffio_read_varlen(bc);
957  for (i = 0; i < reserved_count; i++)
958  ffio_read_varlen(bc);
959 
960  if (*header_idx >= (unsigned)nut->header_count) {
961  av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
962  return AVERROR_INVALIDDATA;
963  }
964  if (size > 4096)
965  *header_idx = 0;
966  size -= nut->header_len[*header_idx];
967 
968  if (flags & FLAG_CHECKSUM) {
969  avio_rb32(bc); // FIXME check this
970  } else if (!(nut->flags & NUT_PIPE) &&
971  size > 2 * nut->max_distance ||
972  FFABS(stc->last_pts - *pts) > stc->max_pts_distance) {
973  av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
974  return AVERROR_INVALIDDATA;
975  }
976 
977  stc->last_pts = *pts;
978  stc->last_flags = flags;
979 
980  return size;
981 }
982 
983 static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code)
984 {
985  AVFormatContext *s = nut->avf;
986  AVIOContext *bc = s->pb;
987  int size, stream_id, discard;
988  int64_t pts, last_IP_pts;
989  StreamContext *stc;
990  uint8_t header_idx;
991  int ret;
992 
993  size = decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
994  if (size < 0)
995  return size;
996 
997  stc = &nut->stream[stream_id];
998 
999  if (stc->last_flags & FLAG_KEY)
1000  stc->skip_until_key_frame = 0;
1001 
1002  discard = s->streams[stream_id]->discard;
1003  last_IP_pts = s->streams[stream_id]->last_IP_pts;
1004  if ((discard >= AVDISCARD_NONKEY && !(stc->last_flags & FLAG_KEY)) ||
1005  (discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE &&
1006  last_IP_pts > pts) ||
1007  discard >= AVDISCARD_ALL ||
1008  stc->skip_until_key_frame) {
1009  avio_skip(bc, size);
1010  return 1;
1011  }
1012 
1013  if (av_new_packet(pkt, size + nut->header_len[header_idx]) < 0)
1014  return AVERROR(ENOMEM);
1015  memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
1016  pkt->pos = avio_tell(bc); // FIXME
1017  if (stc->last_flags & FLAG_SM_DATA) {
1018  int sm_size;
1019  if (read_sm_data(s, bc, pkt, 0, pkt->pos + size) < 0)
1020  return AVERROR_INVALIDDATA;
1021  if (read_sm_data(s, bc, pkt, 1, pkt->pos + size) < 0)
1022  return AVERROR_INVALIDDATA;
1023  sm_size = avio_tell(bc) - pkt->pos;
1024  size -= sm_size;
1025  pkt->size -= sm_size;
1026  }
1027 
1028  ret = avio_read(bc, pkt->data + nut->header_len[header_idx], size);
1029  if (ret != size) {
1030  if (ret < 0)
1031  return ret;
1032  }
1033  av_shrink_packet(pkt, nut->header_len[header_idx] + ret);
1034 
1035  pkt->stream_index = stream_id;
1036  if (stc->last_flags & FLAG_KEY)
1037  pkt->flags |= AV_PKT_FLAG_KEY;
1038  pkt->pts = pts;
1039 
1040  return 0;
1041 }
1042 
1044 {
1045  NUTContext *nut = s->priv_data;
1046  AVIOContext *bc = s->pb;
1047  int i, frame_code = 0, ret, skip;
1048  int64_t ts, back_ptr;
1049 
1050  for (;;) {
1051  int64_t pos = avio_tell(bc);
1052  uint64_t tmp = nut->next_startcode;
1053  nut->next_startcode = 0;
1054 
1055  if (tmp) {
1056  pos -= 8;
1057  } else {
1058  frame_code = avio_r8(bc);
1059  if (url_feof(bc))
1060  return AVERROR_EOF;
1061  if (frame_code == 'N') {
1062  tmp = frame_code;
1063  for (i = 1; i < 8; i++)
1064  tmp = (tmp << 8) + avio_r8(bc);
1065  }
1066  }
1067  switch (tmp) {
1068  case MAIN_STARTCODE:
1069  case STREAM_STARTCODE:
1070  case INDEX_STARTCODE:
1071  skip = get_packetheader(nut, bc, 0, tmp);
1072  avio_skip(bc, skip);
1073  break;
1074  case INFO_STARTCODE:
1075  if (decode_info_header(nut) < 0)
1076  goto resync;
1077  break;
1078  case SYNCPOINT_STARTCODE:
1079  if (decode_syncpoint(nut, &ts, &back_ptr) < 0)
1080  goto resync;
1081  frame_code = avio_r8(bc);
1082  case 0:
1083  ret = decode_frame(nut, pkt, frame_code);
1084  if (ret == 0)
1085  return 0;
1086  else if (ret == 1) // OK but discard packet
1087  break;
1088  default:
1089 resync:
1090  av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
1091  tmp = find_any_startcode(bc, nut->last_syncpoint_pos + 1);
1092  if (tmp == 0)
1093  return AVERROR_INVALIDDATA;
1094  av_log(s, AV_LOG_DEBUG, "sync\n");
1095  nut->next_startcode = tmp;
1096  }
1097  }
1098 }
1099 
1100 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
1101  int64_t *pos_arg, int64_t pos_limit)
1102 {
1103  NUTContext *nut = s->priv_data;
1104  AVIOContext *bc = s->pb;
1105  int64_t pos, pts, back_ptr;
1106  av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n",
1107  stream_index, *pos_arg, pos_limit);
1108 
1109  pos = *pos_arg;
1110  do {
1111  pos = find_startcode(bc, SYNCPOINT_STARTCODE, pos) + 1;
1112  if (pos < 1) {
1113  av_log(s, AV_LOG_ERROR, "read_timestamp failed.\n");
1114  return AV_NOPTS_VALUE;
1115  }
1116  } while (decode_syncpoint(nut, &pts, &back_ptr) < 0);
1117  *pos_arg = pos - 1;
1118  av_assert0(nut->last_syncpoint_pos == *pos_arg);
1119 
1120  av_log(s, AV_LOG_DEBUG, "return %"PRId64" %"PRId64"\n", pts, back_ptr);
1121  if (stream_index == -2)
1122  return back_ptr;
1123  av_assert0(stream_index == -1);
1124  return pts;
1125 }
1126 
1127 static int read_seek(AVFormatContext *s, int stream_index,
1128  int64_t pts, int flags)
1129 {
1130  NUTContext *nut = s->priv_data;
1131  AVStream *st = s->streams[stream_index];
1132  Syncpoint dummy = { .ts = pts * av_q2d(st->time_base) * AV_TIME_BASE };
1133  Syncpoint nopts_sp = { .ts = AV_NOPTS_VALUE, .back_ptr = AV_NOPTS_VALUE };
1134  Syncpoint *sp, *next_node[2] = { &nopts_sp, &nopts_sp };
1135  int64_t pos, pos2, ts;
1136  int i;
1137 
1138  if (nut->flags & NUT_PIPE) {
1139  return AVERROR(ENOSYS);
1140  }
1141 
1142  if (st->index_entries) {
1143  int index = av_index_search_timestamp(st, pts, flags);
1144  if (index < 0)
1145  index = av_index_search_timestamp(st, pts, flags ^ AVSEEK_FLAG_BACKWARD);
1146  if (index < 0)
1147  return -1;
1148 
1149  pos2 = st->index_entries[index].pos;
1150  ts = st->index_entries[index].timestamp;
1151  } else {
1152  av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pts_cmp,
1153  (void **) next_node);
1154  av_log(s, AV_LOG_DEBUG, "%"PRIu64"-%"PRIu64" %"PRId64"-%"PRId64"\n",
1155  next_node[0]->pos, next_node[1]->pos, next_node[0]->ts,
1156  next_node[1]->ts);
1157  pos = ff_gen_search(s, -1, dummy.ts, next_node[0]->pos,
1158  next_node[1]->pos, next_node[1]->pos,
1159  next_node[0]->ts, next_node[1]->ts,
1161 
1162  if (!(flags & AVSEEK_FLAG_BACKWARD)) {
1163  dummy.pos = pos + 16;
1164  next_node[1] = &nopts_sp;
1165  av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
1166  (void **) next_node);
1167  pos2 = ff_gen_search(s, -2, dummy.pos, next_node[0]->pos,
1168  next_node[1]->pos, next_node[1]->pos,
1169  next_node[0]->back_ptr, next_node[1]->back_ptr,
1170  flags, &ts, nut_read_timestamp);
1171  if (pos2 >= 0)
1172  pos = pos2;
1173  // FIXME dir but I think it does not matter
1174  }
1175  dummy.pos = pos;
1176  sp = av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
1177  NULL);
1178 
1179  av_assert0(sp);
1180  pos2 = sp->back_ptr - 15;
1181  }
1182  av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
1183  pos = find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
1184  avio_seek(s->pb, pos, SEEK_SET);
1185  av_log(NULL, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
1186  if (pos2 > pos || pos2 + 15 < pos)
1187  av_log(NULL, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
1188  for (i = 0; i < s->nb_streams; i++)
1189  nut->stream[i].skip_until_key_frame = 1;
1190 
1191  return 0;
1192 }
1193 
1195 {
1196  NUTContext *nut = s->priv_data;
1197  int i;
1198 
1199  av_freep(&nut->time_base);
1200  av_freep(&nut->stream);
1201  ff_nut_free_sp(nut);
1202  for (i = 1; i < nut->header_count; i++)
1203  av_freep(&nut->header[i]);
1204 
1205  return 0;
1206 }
1207 
1209  .name = "nut",
1210  .long_name = NULL_IF_CONFIG_SMALL("NUT"),
1211  .flags = AVFMT_SEEK_TO_PTS,
1212  .priv_data_size = sizeof(NUTContext),
1213  .read_probe = nut_probe,
1217  .read_seek = read_seek,
1218  .extensions = "nut",
1219  .codec_tag = ff_nut_codec_tags,
1220 };