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/mathematics.h"
28 #include "libavutil/tree.h"
29 #include "avio_internal.h"
30 #include "nut.h"
31 #include "riff.h"
32 
33 #define NUT_MAX_STREAMS 256 /* arbitrary sanity check value */
34 
35 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
36  int64_t *pos_arg, int64_t pos_limit);
37 
38 static int get_str(AVIOContext *bc, char *string, unsigned int maxlen)
39 {
40  unsigned int len = ffio_read_varlen(bc);
41 
42  if (len && maxlen)
43  avio_read(bc, string, FFMIN(len, maxlen));
44  while (len > maxlen) {
45  avio_r8(bc);
46  len--;
47  }
48 
49  if (maxlen)
50  string[FFMIN(len, maxlen - 1)] = 0;
51 
52  if (maxlen == len)
53  return -1;
54  else
55  return 0;
56 }
57 
58 static int64_t get_s(AVIOContext *bc)
59 {
60  int64_t v = ffio_read_varlen(bc) + 1;
61 
62  if (v & 1)
63  return -(v >> 1);
64  else
65  return (v >> 1);
66 }
67 
68 static uint64_t get_fourcc(AVIOContext *bc)
69 {
70  unsigned int len = ffio_read_varlen(bc);
71 
72  if (len == 2)
73  return avio_rl16(bc);
74  else if (len == 4)
75  return avio_rl32(bc);
76  else {
77  av_log(NULL, AV_LOG_ERROR, "Unsupported fourcc length %d\n", len);
78  return -1;
79  }
80 }
81 
82 #ifdef TRACE
83 static inline uint64_t get_v_trace(AVIOContext *bc, const char *file,
84  const char *func, int line)
85 {
86  uint64_t v = ffio_read_varlen(bc);
87 
88  av_log(NULL, AV_LOG_DEBUG, "get_v %5"PRId64" / %"PRIX64" in %s %s:%d\n",
89  v, v, file, func, line);
90  return v;
91 }
92 
93 static inline int64_t get_s_trace(AVIOContext *bc, const char *file,
94  const char *func, int line)
95 {
96  int64_t v = get_s(bc);
97 
98  av_log(NULL, AV_LOG_DEBUG, "get_s %5"PRId64" / %"PRIX64" in %s %s:%d\n",
99  v, v, file, func, line);
100  return v;
101 }
102 
103 static inline uint64_t get_4cc_trace(AVIOContext *bc, char *file,
104  char *func, int line)
105 {
106  uint64_t v = get_fourcc(bc);
107 
108  av_log(NULL, AV_LOG_DEBUG, "get_fourcc %5"PRId64" / %"PRIX64" in %s %s:%d\n",
109  v, v, file, func, line);
110  return v;
111 }
112 #define ffio_read_varlen(bc) get_v_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
113 #define get_s(bc) get_s_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
114 #define get_fourcc(bc) get_4cc_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
115 #endif
116 
118  int calculate_checksum, uint64_t startcode)
119 {
120  int64_t size;
121 // start = avio_tell(bc) - 8;
122 
123  startcode = av_be2ne64(startcode);
124  startcode = ff_crc04C11DB7_update(0, (uint8_t*) &startcode, 8);
125 
127  size = ffio_read_varlen(bc);
128  if (size > 4096)
129  avio_rb32(bc);
130  if (ffio_get_checksum(bc) && size > 4096)
131  return -1;
132 
133  ffio_init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
134 
135  return size;
136 }
137 
138 static uint64_t find_any_startcode(AVIOContext *bc, int64_t pos)
139 {
140  uint64_t state = 0;
141 
142  if (pos >= 0)
143  /* Note, this may fail if the stream is not seekable, but that should
144  * not matter, as in this case we simply start where we currently are */
145  avio_seek(bc, pos, SEEK_SET);
146  while (!url_feof(bc)) {
147  state = (state << 8) | avio_r8(bc);
148  if ((state >> 56) != 'N')
149  continue;
150  switch (state) {
151  case MAIN_STARTCODE:
152  case STREAM_STARTCODE:
153  case SYNCPOINT_STARTCODE:
154  case INFO_STARTCODE:
155  case INDEX_STARTCODE:
156  return state;
157  }
158  }
159 
160  return 0;
161 }
162 
163 /**
164  * Find the given startcode.
165  * @param code the startcode
166  * @param pos the start position of the search, or -1 if the current position
167  * @return the position of the startcode or -1 if not found
168  */
169 static int64_t find_startcode(AVIOContext *bc, uint64_t code, int64_t pos)
170 {
171  for (;;) {
172  uint64_t startcode = find_any_startcode(bc, pos);
173  if (startcode == code)
174  return avio_tell(bc) - 8;
175  else if (startcode == 0)
176  return -1;
177  pos = -1;
178  }
179 }
180 
181 static int nut_probe(AVProbeData *p)
182 {
183  int i;
184  uint64_t code = 0;
185 
186  for (i = 0; i < p->buf_size; i++) {
187  code = (code << 8) | p->buf[i];
188  if (code == MAIN_STARTCODE)
189  return AVPROBE_SCORE_MAX;
190  }
191  return 0;
192 }
193 
194 #define GET_V(dst, check) \
195  do { \
196  tmp = ffio_read_varlen(bc); \
197  if (!(check)) { \
198  av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp); \
199  return AVERROR_INVALIDDATA; \
200  } \
201  dst = tmp; \
202  } while (0)
203 
204 static int skip_reserved(AVIOContext *bc, int64_t pos)
205 {
206  pos -= avio_tell(bc);
207  if (pos < 0) {
208  avio_seek(bc, pos, SEEK_CUR);
209  return AVERROR_INVALIDDATA;
210  } else {
211  while (pos--)
212  avio_r8(bc);
213  return 0;
214  }
215 }
216 
218 {
219  AVFormatContext *s = nut->avf;
220  AVIOContext *bc = s->pb;
221  uint64_t tmp, end;
222  unsigned int stream_count;
223  int i, j, count;
224  int tmp_stream, tmp_mul, tmp_pts, tmp_size, tmp_res, tmp_head_idx;
225 
226  end = get_packetheader(nut, bc, 1, MAIN_STARTCODE);
227  end += avio_tell(bc);
228 
229  tmp = ffio_read_varlen(bc);
230  if (tmp < 2 && tmp > NUT_VERSION) {
231  av_log(s, AV_LOG_ERROR, "Version %"PRId64" not supported.\n",
232  tmp);
233  return AVERROR(ENOSYS);
234  }
235 
236  GET_V(stream_count, tmp > 0 && tmp <= NUT_MAX_STREAMS);
237 
238  nut->max_distance = ffio_read_varlen(bc);
239  if (nut->max_distance > 65536) {
240  av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);
241  nut->max_distance = 65536;
242  }
243 
244  GET_V(nut->time_base_count, tmp > 0 && tmp < INT_MAX / sizeof(AVRational));
245  nut->time_base = av_malloc(nut->time_base_count * sizeof(AVRational));
246  if (!nut->time_base)
247  return AVERROR(ENOMEM);
248 
249  for (i = 0; i < nut->time_base_count; i++) {
250  GET_V(nut->time_base[i].num, tmp > 0 && tmp < (1ULL << 31));
251  GET_V(nut->time_base[i].den, tmp > 0 && tmp < (1ULL << 31));
252  if (av_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1) {
253  av_log(s, AV_LOG_ERROR, "time base invalid\n");
254  return AVERROR_INVALIDDATA;
255  }
256  }
257  tmp_pts = 0;
258  tmp_mul = 1;
259  tmp_stream = 0;
260  tmp_head_idx = 0;
261  for (i = 0; i < 256;) {
262  int tmp_flags = ffio_read_varlen(bc);
263  int tmp_fields = ffio_read_varlen(bc);
264 
265  if (tmp_fields > 0)
266  tmp_pts = get_s(bc);
267  if (tmp_fields > 1)
268  tmp_mul = ffio_read_varlen(bc);
269  if (tmp_fields > 2)
270  tmp_stream = ffio_read_varlen(bc);
271  if (tmp_fields > 3)
272  tmp_size = ffio_read_varlen(bc);
273  else
274  tmp_size = 0;
275  if (tmp_fields > 4)
276  tmp_res = ffio_read_varlen(bc);
277  else
278  tmp_res = 0;
279  if (tmp_fields > 5)
280  count = ffio_read_varlen(bc);
281  else
282  count = tmp_mul - tmp_size;
283  if (tmp_fields > 6)
284  get_s(bc);
285  if (tmp_fields > 7)
286  tmp_head_idx = ffio_read_varlen(bc);
287 
288  while (tmp_fields-- > 8)
289  ffio_read_varlen(bc);
290 
291  if (count == 0 || i + count > 256) {
292  av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
293  return AVERROR_INVALIDDATA;
294  }
295  if (tmp_stream >= stream_count) {
296  av_log(s, AV_LOG_ERROR, "illegal stream number\n");
297  return AVERROR_INVALIDDATA;
298  }
299 
300  for (j = 0; j < count; j++, i++) {
301  if (i == 'N') {
302  nut->frame_code[i].flags = FLAG_INVALID;
303  j--;
304  continue;
305  }
306  nut->frame_code[i].flags = tmp_flags;
307  nut->frame_code[i].pts_delta = tmp_pts;
308  nut->frame_code[i].stream_id = tmp_stream;
309  nut->frame_code[i].size_mul = tmp_mul;
310  nut->frame_code[i].size_lsb = tmp_size + j;
311  nut->frame_code[i].reserved_count = tmp_res;
312  nut->frame_code[i].header_idx = tmp_head_idx;
313  }
314  }
315  av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
316 
317  if (end > avio_tell(bc) + 4) {
318  int rem = 1024;
319  GET_V(nut->header_count, tmp < 128U);
320  nut->header_count++;
321  for (i = 1; i < nut->header_count; i++) {
322  uint8_t *hdr;
323  GET_V(nut->header_len[i], tmp > 0 && tmp < 256);
324  rem -= nut->header_len[i];
325  if (rem < 0) {
326  av_log(s, AV_LOG_ERROR, "invalid elision header\n");
327  return AVERROR_INVALIDDATA;
328  }
329  hdr = av_malloc(nut->header_len[i]);
330  if (!hdr)
331  return AVERROR(ENOMEM);
332  avio_read(bc, hdr, nut->header_len[i]);
333  nut->header[i] = hdr;
334  }
335  av_assert0(nut->header_len[0] == 0);
336  }
337 
338  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
339  av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
340  return AVERROR_INVALIDDATA;
341  }
342 
343  nut->stream = av_calloc(stream_count, sizeof(StreamContext));
344  if (!nut->stream)
345  return AVERROR(ENOMEM);
346  for (i = 0; i < stream_count; i++)
347  avformat_new_stream(s, NULL);
348 
349  return 0;
350 }
351 
353 {
354  AVFormatContext *s = nut->avf;
355  AVIOContext *bc = s->pb;
356  StreamContext *stc;
357  int class, stream_id;
358  uint64_t tmp, end;
359  AVStream *st;
360 
361  end = get_packetheader(nut, bc, 1, STREAM_STARTCODE);
362  end += avio_tell(bc);
363 
364  GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);
365  stc = &nut->stream[stream_id];
366  st = s->streams[stream_id];
367  if (!st)
368  return AVERROR(ENOMEM);
369 
370  class = ffio_read_varlen(bc);
371  tmp = get_fourcc(bc);
372  st->codec->codec_tag = tmp;
373  switch (class) {
374  case 0:
376  st->codec->codec_id = av_codec_get_id((const AVCodecTag * const []) {
379  0
380  },
381  tmp);
382  break;
383  case 1:
385  st->codec->codec_id = av_codec_get_id((const AVCodecTag * const []) {
388  0
389  },
390  tmp);
391  break;
392  case 2:
395  break;
396  case 3:
399  break;
400  default:
401  av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
402  return AVERROR(ENOSYS);
403  }
404  if (class < 3 && st->codec->codec_id == AV_CODEC_ID_NONE)
405  av_log(s, AV_LOG_ERROR,
406  "Unknown codec tag '0x%04x' for stream number %d\n",
407  (unsigned int) tmp, stream_id);
408 
409  GET_V(stc->time_base_id, tmp < nut->time_base_count);
410  GET_V(stc->msb_pts_shift, tmp < 16);
412  GET_V(stc->decode_delay, tmp < 1000); // sanity limit, raise this if Moore's law is true
413  st->codec->has_b_frames = stc->decode_delay;
414  ffio_read_varlen(bc); // stream flags
415 
416  GET_V(st->codec->extradata_size, tmp < (1 << 30));
417  if (st->codec->extradata_size) {
419  return AVERROR(ENOMEM);
420  avio_read(bc, st->codec->extradata, st->codec->extradata_size);
421  }
422 
423  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
424  GET_V(st->codec->width, tmp > 0);
425  GET_V(st->codec->height, tmp > 0);
428  if ((!st->sample_aspect_ratio.num) != (!st->sample_aspect_ratio.den)) {
429  av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n",
431  return AVERROR_INVALIDDATA;
432  }
433  ffio_read_varlen(bc); /* csp type */
434  } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
435  GET_V(st->codec->sample_rate, tmp > 0);
436  ffio_read_varlen(bc); // samplerate_den
437  GET_V(st->codec->channels, tmp > 0);
438  }
439  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
440  av_log(s, AV_LOG_ERROR,
441  "stream header %d checksum mismatch\n", stream_id);
442  return AVERROR_INVALIDDATA;
443  }
444  stc->time_base = &nut->time_base[stc->time_base_id];
445  avpriv_set_pts_info(s->streams[stream_id], 63, stc->time_base->num,
446  stc->time_base->den);
447  return 0;
448 }
449 
451  int stream_id)
452 {
453  int flag = 0, i;
454 
455  for (i = 0; ff_nut_dispositions[i].flag; ++i)
456  if (!strcmp(ff_nut_dispositions[i].str, value))
457  flag = ff_nut_dispositions[i].flag;
458  if (!flag)
459  av_log(avf, AV_LOG_INFO, "unknown disposition type '%s'\n", value);
460  for (i = 0; i < avf->nb_streams; ++i)
461  if (stream_id == i || stream_id == -1)
462  avf->streams[i]->disposition |= flag;
463 }
464 
466 {
467  AVFormatContext *s = nut->avf;
468  AVIOContext *bc = s->pb;
469  uint64_t tmp, chapter_start, chapter_len;
470  unsigned int stream_id_plus1, count;
471  int chapter_id, i;
472  int64_t value, end;
473  char name[256], str_value[1024], type_str[256];
474  const char *type;
475  AVChapter *chapter = NULL;
476  AVStream *st = NULL;
477  AVDictionary **metadata = NULL;
478 
479  end = get_packetheader(nut, bc, 1, INFO_STARTCODE);
480  end += avio_tell(bc);
481 
482  GET_V(stream_id_plus1, tmp <= s->nb_streams);
483  chapter_id = get_s(bc);
484  chapter_start = ffio_read_varlen(bc);
485  chapter_len = ffio_read_varlen(bc);
486  count = ffio_read_varlen(bc);
487 
488  if (chapter_id && !stream_id_plus1) {
489  int64_t start = chapter_start / nut->time_base_count;
490  chapter = avpriv_new_chapter(s, chapter_id,
491  nut->time_base[chapter_start %
492  nut->time_base_count],
493  start, start + chapter_len, NULL);
494  metadata = &chapter->metadata;
495  } else if (stream_id_plus1) {
496  st = s->streams[stream_id_plus1 - 1];
497  metadata = &st->metadata;
498  } else
499  metadata = &s->metadata;
500 
501  for (i = 0; i < count; i++) {
502  get_str(bc, name, sizeof(name));
503  value = get_s(bc);
504  if (value == -1) {
505  type = "UTF-8";
506  get_str(bc, str_value, sizeof(str_value));
507  } else if (value == -2) {
508  get_str(bc, type_str, sizeof(type_str));
509  type = type_str;
510  get_str(bc, str_value, sizeof(str_value));
511  } else if (value == -3) {
512  type = "s";
513  value = get_s(bc);
514  } else if (value == -4) {
515  type = "t";
516  value = ffio_read_varlen(bc);
517  } else if (value < -4) {
518  type = "r";
519  get_s(bc);
520  } else {
521  type = "v";
522  }
523 
524  if (stream_id_plus1 > s->nb_streams) {
525  av_log(s, AV_LOG_ERROR, "invalid stream id for info packet\n");
526  continue;
527  }
528 
529  if (!strcmp(type, "UTF-8")) {
530  if (chapter_id == 0 && !strcmp(name, "Disposition")) {
531  set_disposition_bits(s, str_value, stream_id_plus1 - 1);
532  continue;
533  }
534 
535  if (stream_id_plus1 && !strcmp(name, "r_frame_rate")) {
536  sscanf(str_value, "%d/%d", &st->r_frame_rate.num, &st->r_frame_rate.den);
537  if (st->r_frame_rate.num >= 1000LL*st->r_frame_rate.den)
538  st->r_frame_rate.num = st->r_frame_rate.den = 0;
539  continue;
540  }
541 
542  if (metadata && av_strcasecmp(name, "Uses") &&
543  av_strcasecmp(name, "Depends") && av_strcasecmp(name, "Replaces"))
544  av_dict_set(metadata, name, str_value, 0);
545  }
546  }
547 
548  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
549  av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
550  return AVERROR_INVALIDDATA;
551  }
552  return 0;
553 }
554 
555 static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr)
556 {
557  AVFormatContext *s = nut->avf;
558  AVIOContext *bc = s->pb;
559  int64_t end;
560  uint64_t tmp;
561  int ret;
562 
563  nut->last_syncpoint_pos = avio_tell(bc) - 8;
564 
565  end = get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
566  end += avio_tell(bc);
567 
568  tmp = ffio_read_varlen(bc);
569  *back_ptr = nut->last_syncpoint_pos - 16 * ffio_read_varlen(bc);
570  if (*back_ptr < 0)
571  return AVERROR_INVALIDDATA;
572 
573  ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count],
574  tmp / nut->time_base_count);
575 
576  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
577  av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
578  return AVERROR_INVALIDDATA;
579  }
580 
581  *ts = tmp / nut->time_base_count *
582  av_q2d(nut->time_base[tmp % nut->time_base_count]) * AV_TIME_BASE;
583 
584  if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts)) < 0)
585  return ret;
586 
587  return 0;
588 }
589 
590 //FIXME calculate exactly, this is just a good approximation.
591 static int64_t find_duration(NUTContext *nut, int64_t filesize)
592 {
593  AVFormatContext *s = nut->avf;
594  int64_t duration = 0;
595 
596  ff_find_last_ts(s, -1, &duration, NULL, nut_read_timestamp);
597 
598  if(duration > 0)
600  return duration;
601 }
602 
604 {
605  AVFormatContext *s = nut->avf;
606  AVIOContext *bc = s->pb;
607  uint64_t tmp, end;
608  int i, j, syncpoint_count;
609  int64_t filesize = avio_size(bc);
610  int64_t *syncpoints;
611  uint64_t max_pts;
612  int8_t *has_keyframe;
613  int ret = AVERROR_INVALIDDATA;
614 
615  if(filesize <= 0)
616  return -1;
617 
618  avio_seek(bc, filesize - 12, SEEK_SET);
619  avio_seek(bc, filesize - avio_rb64(bc), SEEK_SET);
620  if (avio_rb64(bc) != INDEX_STARTCODE) {
621  av_log(s, AV_LOG_ERROR, "no index at the end\n");
622 
623  if(s->duration<=0)
624  s->duration = find_duration(nut, filesize);
625  return ret;
626  }
627 
628  end = get_packetheader(nut, bc, 1, INDEX_STARTCODE);
629  end += avio_tell(bc);
630 
631  max_pts = ffio_read_varlen(bc);
632  s->duration = av_rescale_q(max_pts / nut->time_base_count,
633  nut->time_base[max_pts % nut->time_base_count],
636 
637  GET_V(syncpoint_count, tmp < INT_MAX / 8 && tmp > 0);
638  syncpoints = av_malloc_array(syncpoint_count, sizeof(int64_t));
639  has_keyframe = av_malloc_array(syncpoint_count + 1, sizeof(int8_t));
640  if (!syncpoints || !has_keyframe) {
641  ret = AVERROR(ENOMEM);
642  goto fail;
643  }
644  for (i = 0; i < syncpoint_count; i++) {
645  syncpoints[i] = ffio_read_varlen(bc);
646  if (syncpoints[i] <= 0)
647  goto fail;
648  if (i)
649  syncpoints[i] += syncpoints[i - 1];
650  }
651 
652  for (i = 0; i < s->nb_streams; i++) {
653  int64_t last_pts = -1;
654  for (j = 0; j < syncpoint_count;) {
655  uint64_t x = ffio_read_varlen(bc);
656  int type = x & 1;
657  int n = j;
658  x >>= 1;
659  if (type) {
660  int flag = x & 1;
661  x >>= 1;
662  if (n + x >= syncpoint_count + 1) {
663  av_log(s, AV_LOG_ERROR, "index overflow A %d + %"PRIu64" >= %d\n", n, x, syncpoint_count + 1);
664  goto fail;
665  }
666  while (x--)
667  has_keyframe[n++] = flag;
668  has_keyframe[n++] = !flag;
669  } else {
670  while (x != 1) {
671  if (n >= syncpoint_count + 1) {
672  av_log(s, AV_LOG_ERROR, "index overflow B\n");
673  goto fail;
674  }
675  has_keyframe[n++] = x & 1;
676  x >>= 1;
677  }
678  }
679  if (has_keyframe[0]) {
680  av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");
681  goto fail;
682  }
683  av_assert0(n <= syncpoint_count + 1);
684  for (; j < n && j < syncpoint_count; j++) {
685  if (has_keyframe[j]) {
686  uint64_t B, A = ffio_read_varlen(bc);
687  if (!A) {
688  A = ffio_read_varlen(bc);
689  B = ffio_read_varlen(bc);
690  // eor_pts[j][i] = last_pts + A + B
691  } else
692  B = 0;
693  av_add_index_entry(s->streams[i], 16 * syncpoints[j - 1],
694  last_pts + A, 0, 0, AVINDEX_KEYFRAME);
695  last_pts += A + B;
696  }
697  }
698  }
699  }
700 
701  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
702  av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
703  goto fail;
704  }
705  ret = 0;
706 
707 fail:
708  av_free(syncpoints);
709  av_free(has_keyframe);
710  return ret;
711 }
712 
714 {
715  NUTContext *nut = s->priv_data;
716  AVIOContext *bc = s->pb;
717  int64_t pos;
718  int initialized_stream_count;
719 
720  nut->avf = s;
721 
722  /* main header */
723  pos = 0;
724  do {
725  pos = find_startcode(bc, MAIN_STARTCODE, pos) + 1;
726  if (pos < 0 + 1) {
727  av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
728  return AVERROR_INVALIDDATA;
729  }
730  } while (decode_main_header(nut) < 0);
731 
732  /* stream headers */
733  pos = 0;
734  for (initialized_stream_count = 0; initialized_stream_count < s->nb_streams;) {
735  pos = find_startcode(bc, STREAM_STARTCODE, pos) + 1;
736  if (pos < 0 + 1) {
737  av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
738  return AVERROR_INVALIDDATA;
739  }
740  if (decode_stream_header(nut) >= 0)
741  initialized_stream_count++;
742  }
743 
744  /* info headers */
745  pos = 0;
746  for (;;) {
747  uint64_t startcode = find_any_startcode(bc, pos);
748  pos = avio_tell(bc);
749 
750  if (startcode == 0) {
751  av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
752  return AVERROR_INVALIDDATA;
753  } else if (startcode == SYNCPOINT_STARTCODE) {
754  nut->next_startcode = startcode;
755  break;
756  } else if (startcode != INFO_STARTCODE) {
757  continue;
758  }
759 
760  decode_info_header(nut);
761  }
762 
763  s->data_offset = pos - 8;
764 
765  if (bc->seekable) {
766  int64_t orig_pos = avio_tell(bc);
768  avio_seek(bc, orig_pos, SEEK_SET);
769  }
771 
773 
774  return 0;
775 }
776 
777 static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id,
778  uint8_t *header_idx, int frame_code)
779 {
780  AVFormatContext *s = nut->avf;
781  AVIOContext *bc = s->pb;
782  StreamContext *stc;
783  int size, flags, size_mul, pts_delta, i, reserved_count;
784  uint64_t tmp;
785 
786  if (avio_tell(bc) > nut->last_syncpoint_pos + nut->max_distance) {
787  av_log(s, AV_LOG_ERROR,
788  "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n",
789  avio_tell(bc), nut->last_syncpoint_pos, nut->max_distance);
790  return AVERROR_INVALIDDATA;
791  }
792 
793  flags = nut->frame_code[frame_code].flags;
794  size_mul = nut->frame_code[frame_code].size_mul;
795  size = nut->frame_code[frame_code].size_lsb;
796  *stream_id = nut->frame_code[frame_code].stream_id;
797  pts_delta = nut->frame_code[frame_code].pts_delta;
798  reserved_count = nut->frame_code[frame_code].reserved_count;
799  *header_idx = nut->frame_code[frame_code].header_idx;
800 
801  if (flags & FLAG_INVALID)
802  return AVERROR_INVALIDDATA;
803  if (flags & FLAG_CODED)
804  flags ^= ffio_read_varlen(bc);
805  if (flags & FLAG_STREAM_ID) {
806  GET_V(*stream_id, tmp < s->nb_streams);
807  }
808  stc = &nut->stream[*stream_id];
809  if (flags & FLAG_CODED_PTS) {
810  int coded_pts = ffio_read_varlen(bc);
811  // FIXME check last_pts validity?
812  if (coded_pts < (1 << stc->msb_pts_shift)) {
813  *pts = ff_lsb2full(stc, coded_pts);
814  } else
815  *pts = coded_pts - (1LL << stc->msb_pts_shift);
816  } else
817  *pts = stc->last_pts + pts_delta;
818  if (flags & FLAG_SIZE_MSB)
819  size += size_mul * ffio_read_varlen(bc);
820  if (flags & FLAG_MATCH_TIME)
821  get_s(bc);
822  if (flags & FLAG_HEADER_IDX)
823  *header_idx = ffio_read_varlen(bc);
824  if (flags & FLAG_RESERVED)
825  reserved_count = ffio_read_varlen(bc);
826  for (i = 0; i < reserved_count; i++)
827  ffio_read_varlen(bc);
828 
829  if (*header_idx >= (unsigned)nut->header_count) {
830  av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
831  return AVERROR_INVALIDDATA;
832  }
833  if (size > 4096)
834  *header_idx = 0;
835  size -= nut->header_len[*header_idx];
836 
837  if (flags & FLAG_CHECKSUM) {
838  avio_rb32(bc); // FIXME check this
839  } else if (size > 2 * nut->max_distance || FFABS(stc->last_pts - *pts) >
840  stc->max_pts_distance) {
841  av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
842  return AVERROR_INVALIDDATA;
843  }
844 
845  stc->last_pts = *pts;
846  stc->last_flags = flags;
847 
848  return size;
849 }
850 
851 static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code)
852 {
853  AVFormatContext *s = nut->avf;
854  AVIOContext *bc = s->pb;
855  int size, stream_id, discard;
856  int64_t pts, last_IP_pts;
857  StreamContext *stc;
858  uint8_t header_idx;
859 
860  size = decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
861  if (size < 0)
862  return size;
863 
864  stc = &nut->stream[stream_id];
865 
866  if (stc->last_flags & FLAG_KEY)
867  stc->skip_until_key_frame = 0;
868 
869  discard = s->streams[stream_id]->discard;
870  last_IP_pts = s->streams[stream_id]->last_IP_pts;
871  if ((discard >= AVDISCARD_NONKEY && !(stc->last_flags & FLAG_KEY)) ||
872  (discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE &&
873  last_IP_pts > pts) ||
874  discard >= AVDISCARD_ALL ||
875  stc->skip_until_key_frame) {
876  avio_skip(bc, size);
877  return 1;
878  }
879 
880  if (av_new_packet(pkt, size + nut->header_len[header_idx]) < 0)
881  return AVERROR(ENOMEM);
882  memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
883  pkt->pos = avio_tell(bc); // FIXME
884  avio_read(bc, pkt->data + nut->header_len[header_idx], size);
885 
886  pkt->stream_index = stream_id;
887  if (stc->last_flags & FLAG_KEY)
888  pkt->flags |= AV_PKT_FLAG_KEY;
889  pkt->pts = pts;
890 
891  return 0;
892 }
893 
895 {
896  NUTContext *nut = s->priv_data;
897  AVIOContext *bc = s->pb;
898  int i, frame_code = 0, ret, skip;
899  int64_t ts, back_ptr;
900 
901  for (;;) {
902  int64_t pos = avio_tell(bc);
903  uint64_t tmp = nut->next_startcode;
904  nut->next_startcode = 0;
905 
906  if (tmp) {
907  pos -= 8;
908  } else {
909  frame_code = avio_r8(bc);
910  if (url_feof(bc))
911  return AVERROR_EOF;
912  if (frame_code == 'N') {
913  tmp = frame_code;
914  for (i = 1; i < 8; i++)
915  tmp = (tmp << 8) + avio_r8(bc);
916  }
917  }
918  switch (tmp) {
919  case MAIN_STARTCODE:
920  case STREAM_STARTCODE:
921  case INDEX_STARTCODE:
922  skip = get_packetheader(nut, bc, 0, tmp);
923  avio_skip(bc, skip);
924  break;
925  case INFO_STARTCODE:
926  if (decode_info_header(nut) < 0)
927  goto resync;
928  break;
929  case SYNCPOINT_STARTCODE:
930  if (decode_syncpoint(nut, &ts, &back_ptr) < 0)
931  goto resync;
932  frame_code = avio_r8(bc);
933  case 0:
934  ret = decode_frame(nut, pkt, frame_code);
935  if (ret == 0)
936  return 0;
937  else if (ret == 1) // OK but discard packet
938  break;
939  default:
940 resync:
941  av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
942  tmp = find_any_startcode(bc, nut->last_syncpoint_pos + 1);
943  if (tmp == 0)
944  return AVERROR_INVALIDDATA;
945  av_log(s, AV_LOG_DEBUG, "sync\n");
946  nut->next_startcode = tmp;
947  }
948  }
949 }
950 
951 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
952  int64_t *pos_arg, int64_t pos_limit)
953 {
954  NUTContext *nut = s->priv_data;
955  AVIOContext *bc = s->pb;
956  int64_t pos, pts, back_ptr;
957  av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n",
958  stream_index, *pos_arg, pos_limit);
959 
960  pos = *pos_arg;
961  do {
962  pos = find_startcode(bc, SYNCPOINT_STARTCODE, pos) + 1;
963  if (pos < 1) {
964  av_log(s, AV_LOG_ERROR, "read_timestamp failed.\n");
965  return AV_NOPTS_VALUE;
966  }
967  } while (decode_syncpoint(nut, &pts, &back_ptr) < 0);
968  *pos_arg = pos - 1;
969  av_assert0(nut->last_syncpoint_pos == *pos_arg);
970 
971  av_log(s, AV_LOG_DEBUG, "return %"PRId64" %"PRId64"\n", pts, back_ptr);
972  if (stream_index == -2)
973  return back_ptr;
974  av_assert0(stream_index == -1);
975  return pts;
976 }
977 
978 static int read_seek(AVFormatContext *s, int stream_index,
979  int64_t pts, int flags)
980 {
981  NUTContext *nut = s->priv_data;
982  AVStream *st = s->streams[stream_index];
983  Syncpoint dummy = { .ts = pts * av_q2d(st->time_base) * AV_TIME_BASE };
984  Syncpoint nopts_sp = { .ts = AV_NOPTS_VALUE, .back_ptr = AV_NOPTS_VALUE };
985  Syncpoint *sp, *next_node[2] = { &nopts_sp, &nopts_sp };
986  int64_t pos, pos2, ts;
987  int i;
988 
989  if (st->index_entries) {
990  int index = av_index_search_timestamp(st, pts, flags);
991  if (index < 0)
992  index = av_index_search_timestamp(st, pts, flags ^ AVSEEK_FLAG_BACKWARD);
993  if (index < 0)
994  return -1;
995 
996  pos2 = st->index_entries[index].pos;
997  ts = st->index_entries[index].timestamp;
998  } else {
999  av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pts_cmp,
1000  (void **) next_node);
1001  av_log(s, AV_LOG_DEBUG, "%"PRIu64"-%"PRIu64" %"PRId64"-%"PRId64"\n",
1002  next_node[0]->pos, next_node[1]->pos, next_node[0]->ts,
1003  next_node[1]->ts);
1004  pos = ff_gen_search(s, -1, dummy.ts, next_node[0]->pos,
1005  next_node[1]->pos, next_node[1]->pos,
1006  next_node[0]->ts, next_node[1]->ts,
1008 
1009  if (!(flags & AVSEEK_FLAG_BACKWARD)) {
1010  dummy.pos = pos + 16;
1011  next_node[1] = &nopts_sp;
1012  av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
1013  (void **) next_node);
1014  pos2 = ff_gen_search(s, -2, dummy.pos, next_node[0]->pos,
1015  next_node[1]->pos, next_node[1]->pos,
1016  next_node[0]->back_ptr, next_node[1]->back_ptr,
1017  flags, &ts, nut_read_timestamp);
1018  if (pos2 >= 0)
1019  pos = pos2;
1020  // FIXME dir but I think it does not matter
1021  }
1022  dummy.pos = pos;
1023  sp = av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
1024  NULL);
1025 
1026  av_assert0(sp);
1027  pos2 = sp->back_ptr - 15;
1028  }
1029  av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
1030  pos = find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
1031  avio_seek(s->pb, pos, SEEK_SET);
1032  av_log(NULL, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
1033  if (pos2 > pos || pos2 + 15 < pos)
1034  av_log(NULL, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
1035  for (i = 0; i < s->nb_streams; i++)
1036  nut->stream[i].skip_until_key_frame = 1;
1037 
1038  return 0;
1039 }
1040 
1042 {
1043  NUTContext *nut = s->priv_data;
1044  int i;
1045 
1046  av_freep(&nut->time_base);
1047  av_freep(&nut->stream);
1048  ff_nut_free_sp(nut);
1049  for (i = 1; i < nut->header_count; i++)
1050  av_freep(&nut->header[i]);
1051 
1052  return 0;
1053 }
1054 
1056  .name = "nut",
1057  .long_name = NULL_IF_CONFIG_SMALL("NUT"),
1058  .flags = AVFMT_SEEK_TO_PTS,
1059  .priv_data_size = sizeof(NUTContext),
1060  .read_probe = nut_probe,
1064  .read_seek = read_seek,
1065  .extensions = "nut",
1066  .codec_tag = ff_nut_codec_tags,
1067 };