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