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  if (bc->eof_reached)
51  len = maxlen;
52  }
53 
54  if (maxlen)
55  string[FFMIN(len, maxlen - 1)] = 0;
56 
57  if (bc->eof_reached)
58  return AVERROR_EOF;
59  if (maxlen == len)
60  return -1;
61  else
62  return 0;
63 }
64 
65 static int64_t get_s(AVIOContext *bc)
66 {
67  int64_t v = ffio_read_varlen(bc) + 1;
68 
69  if (v & 1)
70  return -(v >> 1);
71  else
72  return (v >> 1);
73 }
74 
75 static uint64_t get_fourcc(AVIOContext *bc)
76 {
77  unsigned int len = ffio_read_varlen(bc);
78 
79  if (len == 2)
80  return avio_rl16(bc);
81  else if (len == 4)
82  return avio_rl32(bc);
83  else {
84  av_log(NULL, AV_LOG_ERROR, "Unsupported fourcc length %d\n", len);
85  return -1;
86  }
87 }
88 
89 #ifdef TRACE
90 static inline uint64_t get_v_trace(AVIOContext *bc, const char *file,
91  const char *func, int line)
92 {
93  uint64_t v = ffio_read_varlen(bc);
94 
95  av_log(NULL, AV_LOG_DEBUG, "get_v %5"PRId64" / %"PRIX64" in %s %s:%d\n",
96  v, v, file, func, line);
97  return v;
98 }
99 
100 static inline int64_t get_s_trace(AVIOContext *bc, const char *file,
101  const char *func, int line)
102 {
103  int64_t v = get_s(bc);
104 
105  av_log(NULL, AV_LOG_DEBUG, "get_s %5"PRId64" / %"PRIX64" in %s %s:%d\n",
106  v, v, file, func, line);
107  return v;
108 }
109 
110 static inline uint64_t get_4cc_trace(AVIOContext *bc, char *file,
111  char *func, int line)
112 {
113  uint64_t v = get_fourcc(bc);
114 
115  av_log(NULL, AV_LOG_DEBUG, "get_fourcc %5"PRId64" / %"PRIX64" in %s %s:%d\n",
116  v, v, file, func, line);
117  return v;
118 }
119 #define ffio_read_varlen(bc) get_v_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
120 #define get_s(bc) get_s_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
121 #define get_fourcc(bc) get_4cc_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
122 #endif
123 
125  int calculate_checksum, uint64_t startcode)
126 {
127  int64_t size;
128 // start = avio_tell(bc) - 8;
129 
130  startcode = av_be2ne64(startcode);
131  startcode = ff_crc04C11DB7_update(0, (uint8_t*) &startcode, 8);
132 
134  size = ffio_read_varlen(bc);
135  if (size > 4096)
136  avio_rb32(bc);
137  if (ffio_get_checksum(bc) && size > 4096)
138  return -1;
139 
140  ffio_init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
141 
142  return size;
143 }
144 
145 static uint64_t find_any_startcode(AVIOContext *bc, int64_t pos)
146 {
147  uint64_t state = 0;
148 
149  if (pos >= 0)
150  /* Note, this may fail if the stream is not seekable, but that should
151  * not matter, as in this case we simply start where we currently are */
152  avio_seek(bc, pos, SEEK_SET);
153  while (!avio_feof(bc)) {
154  state = (state << 8) | avio_r8(bc);
155  if ((state >> 56) != 'N')
156  continue;
157  switch (state) {
158  case MAIN_STARTCODE:
159  case STREAM_STARTCODE:
160  case SYNCPOINT_STARTCODE:
161  case INFO_STARTCODE:
162  case INDEX_STARTCODE:
163  return state;
164  }
165  }
166 
167  return 0;
168 }
169 
170 /**
171  * Find the given startcode.
172  * @param code the startcode
173  * @param pos the start position of the search, or -1 if the current position
174  * @return the position of the startcode or -1 if not found
175  */
176 static int64_t find_startcode(AVIOContext *bc, uint64_t code, int64_t pos)
177 {
178  for (;;) {
179  uint64_t startcode = find_any_startcode(bc, pos);
180  if (startcode == code)
181  return avio_tell(bc) - 8;
182  else if (startcode == 0)
183  return -1;
184  pos = -1;
185  }
186 }
187 
188 static int nut_probe(AVProbeData *p)
189 {
190  int i;
191 
192  for (i = 0; i < p->buf_size-8; i++) {
193  if (AV_RB32(p->buf+i) != MAIN_STARTCODE>>32)
194  continue;
195  if (AV_RB32(p->buf+i+4) == (MAIN_STARTCODE & 0xFFFFFFFF))
196  return AVPROBE_SCORE_MAX;
197  }
198  return 0;
199 }
200 
201 #define GET_V(dst, check) \
202  do { \
203  tmp = ffio_read_varlen(bc); \
204  if (!(check)) { \
205  av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp); \
206  ret = AVERROR_INVALIDDATA; \
207  goto fail; \
208  } \
209  dst = tmp; \
210  } while (0)
211 
212 static int skip_reserved(AVIOContext *bc, int64_t pos)
213 {
214  pos -= avio_tell(bc);
215  if (pos < 0) {
216  avio_seek(bc, pos, SEEK_CUR);
217  return AVERROR_INVALIDDATA;
218  } else {
219  while (pos--) {
220  if (bc->eof_reached)
221  return AVERROR_INVALIDDATA;
222  avio_r8(bc);
223  }
224  return 0;
225  }
226 }
227 
229 {
230  AVFormatContext *s = nut->avf;
231  AVIOContext *bc = s->pb;
232  uint64_t tmp, end;
233  unsigned int stream_count;
234  int i, j, count, ret;
235  int tmp_stream, tmp_mul, tmp_pts, tmp_size, tmp_res, tmp_head_idx;
236 
237  end = get_packetheader(nut, bc, 1, MAIN_STARTCODE);
238  end += avio_tell(bc);
239 
240  nut->version = ffio_read_varlen(bc);
241  if (nut->version < NUT_MIN_VERSION &&
242  nut->version > NUT_MAX_VERSION) {
243  av_log(s, AV_LOG_ERROR, "Version %d not supported.\n",
244  nut->version);
245  return AVERROR(ENOSYS);
246  }
247  if (nut->version > 3)
248  nut->minor_version = ffio_read_varlen(bc);
249 
250  GET_V(stream_count, tmp > 0 && tmp <= NUT_MAX_STREAMS);
251 
252  nut->max_distance = ffio_read_varlen(bc);
253  if (nut->max_distance > 65536) {
254  av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);
255  nut->max_distance = 65536;
256  }
257 
258  GET_V(nut->time_base_count, tmp > 0 && tmp < INT_MAX / sizeof(AVRational));
259  nut->time_base = av_malloc_array(nut->time_base_count, sizeof(AVRational));
260  if (!nut->time_base)
261  return AVERROR(ENOMEM);
262 
263  for (i = 0; i < nut->time_base_count; i++) {
264  GET_V(nut->time_base[i].num, tmp > 0 && tmp < (1ULL << 31));
265  GET_V(nut->time_base[i].den, tmp > 0 && tmp < (1ULL << 31));
266  if (av_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1) {
267  av_log(s, AV_LOG_ERROR, "time base invalid\n");
268  ret = AVERROR_INVALIDDATA;
269  goto fail;
270  }
271  }
272  tmp_pts = 0;
273  tmp_mul = 1;
274  tmp_stream = 0;
275  tmp_head_idx = 0;
276  for (i = 0; i < 256;) {
277  int tmp_flags = ffio_read_varlen(bc);
278  int tmp_fields = ffio_read_varlen(bc);
279 
280  if (tmp_fields > 0)
281  tmp_pts = get_s(bc);
282  if (tmp_fields > 1)
283  tmp_mul = ffio_read_varlen(bc);
284  if (tmp_fields > 2)
285  tmp_stream = ffio_read_varlen(bc);
286  if (tmp_fields > 3)
287  tmp_size = ffio_read_varlen(bc);
288  else
289  tmp_size = 0;
290  if (tmp_fields > 4)
291  tmp_res = ffio_read_varlen(bc);
292  else
293  tmp_res = 0;
294  if (tmp_fields > 5)
295  count = ffio_read_varlen(bc);
296  else
297  count = tmp_mul - tmp_size;
298  if (tmp_fields > 6)
299  get_s(bc);
300  if (tmp_fields > 7)
301  tmp_head_idx = ffio_read_varlen(bc);
302 
303  while (tmp_fields-- > 8) {
304  if (bc->eof_reached) {
305  av_log(s, AV_LOG_ERROR, "reached EOF while decoding main header\n");
306  ret = AVERROR_INVALIDDATA;
307  goto fail;
308  }
309  ffio_read_varlen(bc);
310  }
311 
312  if (count <= 0 || count > 256 - (i <= 'N') - i) {
313  av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
314  ret = AVERROR_INVALIDDATA;
315  goto fail;
316  }
317  if (tmp_stream >= stream_count) {
318  av_log(s, AV_LOG_ERROR, "illegal stream number\n");
319  ret = AVERROR_INVALIDDATA;
320  goto fail;
321  }
322 
323  for (j = 0; j < count; j++, i++) {
324  if (i == 'N') {
325  nut->frame_code[i].flags = FLAG_INVALID;
326  j--;
327  continue;
328  }
329  nut->frame_code[i].flags = tmp_flags;
330  nut->frame_code[i].pts_delta = tmp_pts;
331  nut->frame_code[i].stream_id = tmp_stream;
332  nut->frame_code[i].size_mul = tmp_mul;
333  nut->frame_code[i].size_lsb = tmp_size + j;
334  nut->frame_code[i].reserved_count = tmp_res;
335  nut->frame_code[i].header_idx = tmp_head_idx;
336  }
337  }
338  av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
339 
340  if (end > avio_tell(bc) + 4) {
341  int rem = 1024;
342  GET_V(nut->header_count, tmp < 128U);
343  nut->header_count++;
344  for (i = 1; i < nut->header_count; i++) {
345  uint8_t *hdr;
346  GET_V(nut->header_len[i], tmp > 0 && tmp < 256);
347  rem -= nut->header_len[i];
348  if (rem < 0) {
349  av_log(s, AV_LOG_ERROR, "invalid elision header\n");
350  ret = AVERROR_INVALIDDATA;
351  goto fail;
352  }
353  hdr = av_malloc(nut->header_len[i]);
354  if (!hdr) {
355  ret = AVERROR(ENOMEM);
356  goto fail;
357  }
358  avio_read(bc, hdr, nut->header_len[i]);
359  nut->header[i] = hdr;
360  }
361  av_assert0(nut->header_len[0] == 0);
362  }
363 
364  // flags had been effectively introduced in version 4
365  if (nut->version > 3 && end > avio_tell(bc) + 4) {
366  nut->flags = ffio_read_varlen(bc);
367  }
368 
369  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
370  av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
371  ret = AVERROR_INVALIDDATA;
372  goto fail;
373  }
374 
375  nut->stream = av_calloc(stream_count, sizeof(StreamContext));
376  if (!nut->stream) {
377  ret = AVERROR(ENOMEM);
378  goto fail;
379  }
380  for (i = 0; i < stream_count; i++)
382 
383  return 0;
384 fail:
385  av_freep(&nut->time_base);
386  for (i = 1; i < nut->header_count; i++) {
387  av_freep(&nut->header[i]);
388  }
389  nut->header_count = 0;
390  return ret;
391 }
392 
394 {
395  AVFormatContext *s = nut->avf;
396  AVIOContext *bc = s->pb;
397  StreamContext *stc;
398  int class, stream_id, ret;
399  uint64_t tmp, end;
400  AVStream *st = NULL;
401 
402  end = get_packetheader(nut, bc, 1, STREAM_STARTCODE);
403  end += avio_tell(bc);
404 
405  GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);
406  stc = &nut->stream[stream_id];
407  st = s->streams[stream_id];
408  if (!st)
409  return AVERROR(ENOMEM);
410 
411  class = ffio_read_varlen(bc);
412  tmp = get_fourcc(bc);
413  st->codec->codec_tag = tmp;
414  switch (class) {
415  case 0:
417  st->codec->codec_id = av_codec_get_id((const AVCodecTag * const []) {
421  0
422  },
423  tmp);
424  break;
425  case 1:
427  st->codec->codec_id = av_codec_get_id((const AVCodecTag * const []) {
431  0
432  },
433  tmp);
434  break;
435  case 2:
438  break;
439  case 3:
442  break;
443  default:
444  av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
445  return AVERROR(ENOSYS);
446  }
447  if (class < 3 && st->codec->codec_id == AV_CODEC_ID_NONE)
448  av_log(s, AV_LOG_ERROR,
449  "Unknown codec tag '0x%04x' for stream number %d\n",
450  (unsigned int) tmp, stream_id);
451 
452  GET_V(stc->time_base_id, tmp < nut->time_base_count);
453  GET_V(stc->msb_pts_shift, tmp < 16);
455  GET_V(stc->decode_delay, tmp < 1000); // sanity limit, raise this if Moore's law is true
456  st->codec->has_b_frames = stc->decode_delay;
457  ffio_read_varlen(bc); // stream flags
458 
459  GET_V(st->codec->extradata_size, tmp < (1 << 30));
460  if (st->codec->extradata_size) {
461  if (ff_get_extradata(st->codec, bc, st->codec->extradata_size) < 0)
462  return AVERROR(ENOMEM);
463  }
464 
465  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
466  GET_V(st->codec->width, tmp > 0);
467  GET_V(st->codec->height, tmp > 0);
470  if ((!st->sample_aspect_ratio.num) != (!st->sample_aspect_ratio.den)) {
471  av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n",
473  ret = AVERROR_INVALIDDATA;
474  goto fail;
475  }
476  ffio_read_varlen(bc); /* csp type */
477  } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
478  GET_V(st->codec->sample_rate, tmp > 0);
479  ffio_read_varlen(bc); // samplerate_den
480  GET_V(st->codec->channels, tmp > 0);
481  }
482  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
483  av_log(s, AV_LOG_ERROR,
484  "stream header %d checksum mismatch\n", stream_id);
485  ret = AVERROR_INVALIDDATA;
486  goto fail;
487  }
488  stc->time_base = &nut->time_base[stc->time_base_id];
489  avpriv_set_pts_info(s->streams[stream_id], 63, stc->time_base->num,
490  stc->time_base->den);
491  return 0;
492 fail:
493  if (st && st->codec) {
494  av_freep(&st->codec->extradata);
495  st->codec->extradata_size = 0;
496  }
497  return ret;
498 }
499 
501  int stream_id)
502 {
503  int flag = 0, i;
504 
505  for (i = 0; ff_nut_dispositions[i].flag; ++i)
506  if (!strcmp(ff_nut_dispositions[i].str, value))
507  flag = ff_nut_dispositions[i].flag;
508  if (!flag)
509  av_log(avf, AV_LOG_INFO, "unknown disposition type '%s'\n", value);
510  for (i = 0; i < avf->nb_streams; ++i)
511  if (stream_id == i || stream_id == -1)
512  avf->streams[i]->disposition |= flag;
513 }
514 
516 {
517  AVFormatContext *s = nut->avf;
518  AVIOContext *bc = s->pb;
519  uint64_t tmp, chapter_start, chapter_len;
520  unsigned int stream_id_plus1, count;
521  int chapter_id, i, ret = 0;
522  int64_t value, end;
523  char name[256], str_value[1024], type_str[256];
524  const char *type;
525  int *event_flags = NULL;
526  AVChapter *chapter = NULL;
527  AVStream *st = NULL;
528  AVDictionary **metadata = NULL;
529  int metadata_flag = 0;
530 
531  end = get_packetheader(nut, bc, 1, INFO_STARTCODE);
532  end += avio_tell(bc);
533 
534  GET_V(stream_id_plus1, tmp <= s->nb_streams);
535  chapter_id = get_s(bc);
536  chapter_start = ffio_read_varlen(bc);
537  chapter_len = ffio_read_varlen(bc);
538  count = ffio_read_varlen(bc);
539 
540  if (chapter_id && !stream_id_plus1) {
541  int64_t start = chapter_start / nut->time_base_count;
542  chapter = avpriv_new_chapter(s, chapter_id,
543  nut->time_base[chapter_start %
544  nut->time_base_count],
545  start, start + chapter_len, NULL);
546  if (!chapter) {
547  av_log(s, AV_LOG_ERROR, "Could not create chapter.\n");
548  return AVERROR(ENOMEM);
549  }
550  metadata = &chapter->metadata;
551  } else if (stream_id_plus1) {
552  st = s->streams[stream_id_plus1 - 1];
553  metadata = &st->metadata;
554  event_flags = &st->event_flags;
555  metadata_flag = AVSTREAM_EVENT_FLAG_METADATA_UPDATED;
556  } else {
557  metadata = &s->metadata;
558  event_flags = &s->event_flags;
559  metadata_flag = AVFMT_EVENT_FLAG_METADATA_UPDATED;
560  }
561 
562  for (i = 0; i < count; i++) {
563  ret = get_str(bc, name, sizeof(name));
564  if (ret < 0) {
565  av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
566  return ret;
567  }
568  value = get_s(bc);
569  str_value[0] = 0;
570 
571  if (value == -1) {
572  type = "UTF-8";
573  ret = get_str(bc, str_value, sizeof(str_value));
574  } else if (value == -2) {
575  ret = get_str(bc, type_str, sizeof(type_str));
576  if (ret < 0) {
577  av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
578  return ret;
579  }
580  type = type_str;
581  ret = get_str(bc, str_value, sizeof(str_value));
582  } else if (value == -3) {
583  type = "s";
584  value = get_s(bc);
585  } else if (value == -4) {
586  type = "t";
587  value = ffio_read_varlen(bc);
588  } else if (value < -4) {
589  type = "r";
590  get_s(bc);
591  } else {
592  type = "v";
593  }
594 
595  if (ret < 0) {
596  av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
597  return ret;
598  }
599 
600  if (stream_id_plus1 > s->nb_streams) {
601  av_log(s, AV_LOG_ERROR, "invalid stream id for info packet\n");
602  continue;
603  }
604 
605  if (!strcmp(type, "UTF-8")) {
606  if (chapter_id == 0 && !strcmp(name, "Disposition")) {
607  set_disposition_bits(s, str_value, stream_id_plus1 - 1);
608  continue;
609  }
610 
611  if (stream_id_plus1 && !strcmp(name, "r_frame_rate")) {
612  sscanf(str_value, "%d/%d", &st->r_frame_rate.num, &st->r_frame_rate.den);
613  if (st->r_frame_rate.num >= 1000LL*st->r_frame_rate.den ||
614  st->r_frame_rate.num < 0 || st->r_frame_rate.num < 0)
615  st->r_frame_rate.num = st->r_frame_rate.den = 0;
616  continue;
617  }
618 
619  if (metadata && av_strcasecmp(name, "Uses") &&
620  av_strcasecmp(name, "Depends") && av_strcasecmp(name, "Replaces")) {
621  if (event_flags)
622  *event_flags |= metadata_flag;
623  av_dict_set(metadata, name, str_value, 0);
624  }
625  }
626  }
627 
628  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
629  av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
630  return AVERROR_INVALIDDATA;
631  }
632 fail:
633  return FFMIN(ret, 0);
634 }
635 
636 static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr)
637 {
638  AVFormatContext *s = nut->avf;
639  AVIOContext *bc = s->pb;
640  int64_t end;
641  uint64_t tmp;
642  int ret;
643 
644  nut->last_syncpoint_pos = avio_tell(bc) - 8;
645 
646  end = get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
647  end += avio_tell(bc);
648 
649  tmp = ffio_read_varlen(bc);
650  *back_ptr = nut->last_syncpoint_pos - 16 * ffio_read_varlen(bc);
651  if (*back_ptr < 0)
652  return AVERROR_INVALIDDATA;
653 
654  ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count],
655  tmp / nut->time_base_count);
656 
657  if (nut->flags & NUT_BROADCAST) {
658  tmp = ffio_read_varlen(bc);
659  av_log(s, AV_LOG_VERBOSE, "Syncpoint wallclock %"PRId64"\n",
660  av_rescale_q(tmp / nut->time_base_count,
661  nut->time_base[tmp % nut->time_base_count],
662  AV_TIME_BASE_Q));
663  }
664 
665  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
666  av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
667  return AVERROR_INVALIDDATA;
668  }
669 
670  *ts = tmp / nut->time_base_count *
671  av_q2d(nut->time_base[tmp % nut->time_base_count]) * AV_TIME_BASE;
672 
673  if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts)) < 0)
674  return ret;
675 
676  return 0;
677 }
678 
679 //FIXME calculate exactly, this is just a good approximation.
680 static int64_t find_duration(NUTContext *nut, int64_t filesize)
681 {
682  AVFormatContext *s = nut->avf;
683  int64_t duration = 0;
684 
685  ff_find_last_ts(s, -1, &duration, NULL, nut_read_timestamp);
686 
687  if(duration > 0)
689  return duration;
690 }
691 
693 {
694  AVFormatContext *s = nut->avf;
695  AVIOContext *bc = s->pb;
696  uint64_t tmp, end;
697  int i, j, syncpoint_count;
698  int64_t filesize = avio_size(bc);
699  int64_t *syncpoints = NULL;
700  uint64_t max_pts;
701  int8_t *has_keyframe = NULL;
702  int ret = AVERROR_INVALIDDATA;
703 
704  if(filesize <= 0)
705  return -1;
706 
707  avio_seek(bc, filesize - 12, SEEK_SET);
708  avio_seek(bc, filesize - avio_rb64(bc), SEEK_SET);
709  if (avio_rb64(bc) != INDEX_STARTCODE) {
710  av_log(s, AV_LOG_ERROR, "no index at the end\n");
711 
712  if(s->duration<=0)
713  s->duration = find_duration(nut, filesize);
714  return ret;
715  }
716 
717  end = get_packetheader(nut, bc, 1, INDEX_STARTCODE);
718  end += avio_tell(bc);
719 
720  max_pts = ffio_read_varlen(bc);
721  s->duration = av_rescale_q(max_pts / nut->time_base_count,
722  nut->time_base[max_pts % nut->time_base_count],
725 
726  GET_V(syncpoint_count, tmp < INT_MAX / 8 && tmp > 0);
727  syncpoints = av_malloc_array(syncpoint_count, sizeof(int64_t));
728  has_keyframe = av_malloc_array(syncpoint_count + 1, sizeof(int8_t));
729  if (!syncpoints || !has_keyframe) {
730  ret = AVERROR(ENOMEM);
731  goto fail;
732  }
733  for (i = 0; i < syncpoint_count; i++) {
734  syncpoints[i] = ffio_read_varlen(bc);
735  if (syncpoints[i] <= 0)
736  goto fail;
737  if (i)
738  syncpoints[i] += syncpoints[i - 1];
739  }
740 
741  for (i = 0; i < s->nb_streams; i++) {
742  int64_t last_pts = -1;
743  for (j = 0; j < syncpoint_count;) {
744  uint64_t x = ffio_read_varlen(bc);
745  int type = x & 1;
746  int n = j;
747  x >>= 1;
748  if (type) {
749  int flag = x & 1;
750  x >>= 1;
751  if (n + x >= syncpoint_count + 1) {
752  av_log(s, AV_LOG_ERROR, "index overflow A %d + %"PRIu64" >= %d\n", n, x, syncpoint_count + 1);
753  goto fail;
754  }
755  while (x--)
756  has_keyframe[n++] = flag;
757  has_keyframe[n++] = !flag;
758  } else {
759  if (x <= 1) {
760  av_log(s, AV_LOG_ERROR, "index: x %"PRIu64" is invalid\n", x);
761  goto fail;
762  }
763  while (x != 1) {
764  if (n >= syncpoint_count + 1) {
765  av_log(s, AV_LOG_ERROR, "index overflow B\n");
766  goto fail;
767  }
768  has_keyframe[n++] = x & 1;
769  x >>= 1;
770  }
771  }
772  if (has_keyframe[0]) {
773  av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");
774  goto fail;
775  }
776  av_assert0(n <= syncpoint_count + 1);
777  for (; j < n && j < syncpoint_count; j++) {
778  if (has_keyframe[j]) {
779  uint64_t B, A = ffio_read_varlen(bc);
780  if (!A) {
781  A = ffio_read_varlen(bc);
782  B = ffio_read_varlen(bc);
783  // eor_pts[j][i] = last_pts + A + B
784  } else
785  B = 0;
786  av_add_index_entry(s->streams[i], 16 * syncpoints[j - 1],
787  last_pts + A, 0, 0, AVINDEX_KEYFRAME);
788  last_pts += A + B;
789  }
790  }
791  }
792  }
793 
794  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
795  av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
796  goto fail;
797  }
798  ret = 0;
799 
800 fail:
801  av_free(syncpoints);
802  av_free(has_keyframe);
803  return ret;
804 }
805 
807 {
808  NUTContext *nut = s->priv_data;
809  int i;
810 
811  av_freep(&nut->time_base);
812  av_freep(&nut->stream);
813  ff_nut_free_sp(nut);
814  for (i = 1; i < nut->header_count; i++)
815  av_freep(&nut->header[i]);
816 
817  return 0;
818 }
819 
821 {
822  NUTContext *nut = s->priv_data;
823  AVIOContext *bc = s->pb;
824  int64_t pos;
825  int initialized_stream_count;
826 
827  nut->avf = s;
828 
829  /* main header */
830  pos = 0;
831  do {
832  pos = find_startcode(bc, MAIN_STARTCODE, pos) + 1;
833  if (pos < 0 + 1) {
834  av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
835  goto fail;
836  }
837  } while (decode_main_header(nut) < 0);
838 
839  /* stream headers */
840  pos = 0;
841  for (initialized_stream_count = 0; initialized_stream_count < s->nb_streams;) {
842  pos = find_startcode(bc, STREAM_STARTCODE, pos) + 1;
843  if (pos < 0 + 1) {
844  av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
845  goto fail;
846  }
847  if (decode_stream_header(nut) >= 0)
848  initialized_stream_count++;
849  }
850 
851  /* info headers */
852  pos = 0;
853  for (;;) {
854  uint64_t startcode = find_any_startcode(bc, pos);
855  pos = avio_tell(bc);
856 
857  if (startcode == 0) {
858  av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
859  goto fail;
860  } else if (startcode == SYNCPOINT_STARTCODE) {
861  nut->next_startcode = startcode;
862  break;
863  } else if (startcode != INFO_STARTCODE) {
864  continue;
865  }
866 
867  decode_info_header(nut);
868  }
869 
870  s->internal->data_offset = pos - 8;
871 
872  if (bc->seekable) {
873  int64_t orig_pos = avio_tell(bc);
875  avio_seek(bc, orig_pos, SEEK_SET);
876  }
878 
880 
881  return 0;
882 
883 fail:
884  nut_read_close(s);
885 
886  return AVERROR_INVALIDDATA;
887 }
888 
889 static int read_sm_data(AVFormatContext *s, AVIOContext *bc, AVPacket *pkt, int is_meta, int64_t maxpos)
890 {
891  int count = ffio_read_varlen(bc);
892  int skip_start = 0;
893  int skip_end = 0;
894  int channels = 0;
895  int64_t channel_layout = 0;
896  int sample_rate = 0;
897  int width = 0;
898  int height = 0;
899  int i, ret;
900 
901  for (i=0; i<count; i++) {
902  uint8_t name[256], str_value[256], type_str[256];
903  int value;
904  if (avio_tell(bc) >= maxpos)
905  return AVERROR_INVALIDDATA;
906  ret = get_str(bc, name, sizeof(name));
907  if (ret < 0) {
908  av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
909  return ret;
910  }
911  value = get_s(bc);
912 
913  if (value == -1) {
914  ret = get_str(bc, str_value, sizeof(str_value));
915  if (ret < 0) {
916  av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
917  return ret;
918  }
919  av_log(s, AV_LOG_WARNING, "Unknown string %s / %s\n", name, str_value);
920  } else if (value == -2) {
921  uint8_t *dst = NULL;
922  int64_t v64, value_len;
923 
924  ret = get_str(bc, type_str, sizeof(type_str));
925  if (ret < 0) {
926  av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
927  return ret;
928  }
929  value_len = ffio_read_varlen(bc);
930  if (avio_tell(bc) + value_len >= maxpos)
931  return AVERROR_INVALIDDATA;
932  if (!strcmp(name, "Palette")) {
933  dst = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, value_len);
934  } else if (!strcmp(name, "Extradata")) {
935  dst = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, value_len);
936  } else if (sscanf(name, "CodecSpecificSide%"SCNd64"", &v64) == 1) {
938  if(!dst)
939  return AVERROR(ENOMEM);
940  AV_WB64(dst, v64);
941  dst += 8;
942  } else if (!strcmp(name, "ChannelLayout") && value_len == 8) {
943  channel_layout = avio_rl64(bc);
944  continue;
945  } else {
946  av_log(s, AV_LOG_WARNING, "Unknown data %s / %s\n", name, type_str);
947  avio_skip(bc, value_len);
948  continue;
949  }
950  if(!dst)
951  return AVERROR(ENOMEM);
952  avio_read(bc, dst, value_len);
953  } else if (value == -3) {
954  value = get_s(bc);
955  } else if (value == -4) {
956  value = ffio_read_varlen(bc);
957  } else if (value < -4) {
958  get_s(bc);
959  } else {
960  if (!strcmp(name, "SkipStart")) {
961  skip_start = value;
962  } else if (!strcmp(name, "SkipEnd")) {
963  skip_end = value;
964  } else if (!strcmp(name, "Channels")) {
965  channels = value;
966  } else if (!strcmp(name, "SampleRate")) {
967  sample_rate = value;
968  } else if (!strcmp(name, "Width")) {
969  width = value;
970  } else if (!strcmp(name, "Height")) {
971  height = value;
972  } else {
973  av_log(s, AV_LOG_WARNING, "Unknown integer %s\n", name);
974  }
975  }
976  }
977 
978  if (channels || channel_layout || sample_rate || width || height) {
980  if (!dst)
981  return AVERROR(ENOMEM);
982  bytestream_put_le32(&dst,
984  AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT*(!!channel_layout) +
985  AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE*(!!sample_rate) +
986  AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS*(!!(width|height))
987  );
988  if (channels)
989  bytestream_put_le32(&dst, channels);
990  if (channel_layout)
991  bytestream_put_le64(&dst, channel_layout);
992  if (sample_rate)
993  bytestream_put_le32(&dst, sample_rate);
994  if (width || height){
995  bytestream_put_le32(&dst, width);
996  bytestream_put_le32(&dst, height);
997  }
998  }
999 
1000  if (skip_start || skip_end) {
1002  if (!dst)
1003  return AVERROR(ENOMEM);
1004  AV_WL32(dst, skip_start);
1005  AV_WL32(dst+4, skip_end);
1006  }
1007 
1008  if (avio_tell(bc) >= maxpos)
1009  return AVERROR_INVALIDDATA;
1010 
1011  return 0;
1012 }
1013 
1014 static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id,
1015  uint8_t *header_idx, int frame_code)
1016 {
1017  AVFormatContext *s = nut->avf;
1018  AVIOContext *bc = s->pb;
1019  StreamContext *stc;
1020  int size, flags, size_mul, pts_delta, i, reserved_count, ret;
1021  uint64_t tmp;
1022 
1023  if (!(nut->flags & NUT_PIPE) &&
1024  avio_tell(bc) > nut->last_syncpoint_pos + nut->max_distance) {
1025  av_log(s, AV_LOG_ERROR,
1026  "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n",
1027  avio_tell(bc), nut->last_syncpoint_pos, nut->max_distance);
1028  return AVERROR_INVALIDDATA;
1029  }
1030 
1031  flags = nut->frame_code[frame_code].flags;
1032  size_mul = nut->frame_code[frame_code].size_mul;
1033  size = nut->frame_code[frame_code].size_lsb;
1034  *stream_id = nut->frame_code[frame_code].stream_id;
1035  pts_delta = nut->frame_code[frame_code].pts_delta;
1036  reserved_count = nut->frame_code[frame_code].reserved_count;
1037  *header_idx = nut->frame_code[frame_code].header_idx;
1038 
1039  if (flags & FLAG_INVALID)
1040  return AVERROR_INVALIDDATA;
1041  if (flags & FLAG_CODED)
1042  flags ^= ffio_read_varlen(bc);
1043  if (flags & FLAG_STREAM_ID) {
1044  GET_V(*stream_id, tmp < s->nb_streams);
1045  }
1046  stc = &nut->stream[*stream_id];
1047  if (flags & FLAG_CODED_PTS) {
1048  int coded_pts = ffio_read_varlen(bc);
1049  // FIXME check last_pts validity?
1050  if (coded_pts < (1 << stc->msb_pts_shift)) {
1051  *pts = ff_lsb2full(stc, coded_pts);
1052  } else
1053  *pts = coded_pts - (1LL << stc->msb_pts_shift);
1054  } else
1055  *pts = stc->last_pts + pts_delta;
1056  if (flags & FLAG_SIZE_MSB)
1057  size += size_mul * ffio_read_varlen(bc);
1058  if (flags & FLAG_MATCH_TIME)
1059  get_s(bc);
1060  if (flags & FLAG_HEADER_IDX)
1061  *header_idx = ffio_read_varlen(bc);
1062  if (flags & FLAG_RESERVED)
1063  reserved_count = ffio_read_varlen(bc);
1064  for (i = 0; i < reserved_count; i++) {
1065  if (bc->eof_reached) {
1066  av_log(s, AV_LOG_ERROR, "reached EOF while decoding frame header\n");
1067  return AVERROR_INVALIDDATA;
1068  }
1069  ffio_read_varlen(bc);
1070  }
1071 
1072  if (*header_idx >= (unsigned)nut->header_count) {
1073  av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
1074  return AVERROR_INVALIDDATA;
1075  }
1076  if (size > 4096)
1077  *header_idx = 0;
1078  size -= nut->header_len[*header_idx];
1079 
1080  if (flags & FLAG_CHECKSUM) {
1081  avio_rb32(bc); // FIXME check this
1082  } else if (!(nut->flags & NUT_PIPE) &&
1083  size > 2 * nut->max_distance ||
1084  FFABS(stc->last_pts - *pts) > stc->max_pts_distance) {
1085  av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
1086  return AVERROR_INVALIDDATA;
1087  }
1088 
1089  stc->last_pts = *pts;
1090  stc->last_flags = flags;
1091 
1092  return size;
1093 fail:
1094  return ret;
1095 }
1096 
1097 static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code)
1098 {
1099  AVFormatContext *s = nut->avf;
1100  AVIOContext *bc = s->pb;
1101  int size, stream_id, discard, ret;
1102  int64_t pts, last_IP_pts;
1103  StreamContext *stc;
1104  uint8_t header_idx;
1105 
1106  size = decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
1107  if (size < 0)
1108  return size;
1109 
1110  stc = &nut->stream[stream_id];
1111 
1112  if (stc->last_flags & FLAG_KEY)
1113  stc->skip_until_key_frame = 0;
1114 
1115  discard = s->streams[stream_id]->discard;
1116  last_IP_pts = s->streams[stream_id]->last_IP_pts;
1117  if ((discard >= AVDISCARD_NONKEY && !(stc->last_flags & FLAG_KEY)) ||
1118  (discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE &&
1119  last_IP_pts > pts) ||
1120  discard >= AVDISCARD_ALL ||
1121  stc->skip_until_key_frame) {
1122  avio_skip(bc, size);
1123  return 1;
1124  }
1125 
1126  ret = av_new_packet(pkt, size + nut->header_len[header_idx]);
1127  if (ret < 0)
1128  return ret;
1129  memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
1130  pkt->pos = avio_tell(bc); // FIXME
1131  if (stc->last_flags & FLAG_SM_DATA) {
1132  int sm_size;
1133  if (read_sm_data(s, bc, pkt, 0, pkt->pos + size) < 0) {
1134  ret = AVERROR_INVALIDDATA;
1135  goto fail;
1136  }
1137  if (read_sm_data(s, bc, pkt, 1, pkt->pos + size) < 0) {
1138  ret = AVERROR_INVALIDDATA;
1139  goto fail;
1140  }
1141  sm_size = avio_tell(bc) - pkt->pos;
1142  size -= sm_size;
1143  pkt->size -= sm_size;
1144  }
1145 
1146  ret = avio_read(bc, pkt->data + nut->header_len[header_idx], size);
1147  if (ret != size) {
1148  if (ret < 0)
1149  goto fail;
1150  }
1151  av_shrink_packet(pkt, nut->header_len[header_idx] + ret);
1152 
1153  pkt->stream_index = stream_id;
1154  if (stc->last_flags & FLAG_KEY)
1155  pkt->flags |= AV_PKT_FLAG_KEY;
1156  pkt->pts = pts;
1157 
1158  return 0;
1159 fail:
1160  av_free_packet(pkt);
1161  return ret;
1162 }
1163 
1165 {
1166  NUTContext *nut = s->priv_data;
1167  AVIOContext *bc = s->pb;
1168  int i, frame_code = 0, ret, skip;
1169  int64_t ts, back_ptr;
1170 
1171  for (;;) {
1172  int64_t pos = avio_tell(bc);
1173  uint64_t tmp = nut->next_startcode;
1174  nut->next_startcode = 0;
1175 
1176  if (tmp) {
1177  pos -= 8;
1178  } else {
1179  frame_code = avio_r8(bc);
1180  if (avio_feof(bc))
1181  return AVERROR_EOF;
1182  if (frame_code == 'N') {
1183  tmp = frame_code;
1184  for (i = 1; i < 8; i++)
1185  tmp = (tmp << 8) + avio_r8(bc);
1186  }
1187  }
1188  switch (tmp) {
1189  case MAIN_STARTCODE:
1190  case STREAM_STARTCODE:
1191  case INDEX_STARTCODE:
1192  skip = get_packetheader(nut, bc, 0, tmp);
1193  avio_skip(bc, skip);
1194  break;
1195  case INFO_STARTCODE:
1196  if (decode_info_header(nut) < 0)
1197  goto resync;
1198  break;
1199  case SYNCPOINT_STARTCODE:
1200  if (decode_syncpoint(nut, &ts, &back_ptr) < 0)
1201  goto resync;
1202  frame_code = avio_r8(bc);
1203  case 0:
1204  ret = decode_frame(nut, pkt, frame_code);
1205  if (ret == 0)
1206  return 0;
1207  else if (ret == 1) // OK but discard packet
1208  break;
1209  default:
1210 resync:
1211  av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
1212  tmp = find_any_startcode(bc, FFMAX(nut->last_syncpoint_pos, nut->last_resync_pos) + 1);
1213  nut->last_resync_pos = avio_tell(bc);
1214  if (tmp == 0)
1215  return AVERROR_INVALIDDATA;
1216  av_log(s, AV_LOG_DEBUG, "sync\n");
1217  nut->next_startcode = tmp;
1218  }
1219  }
1220 }
1221 
1222 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
1223  int64_t *pos_arg, int64_t pos_limit)
1224 {
1225  NUTContext *nut = s->priv_data;
1226  AVIOContext *bc = s->pb;
1227  int64_t pos, pts, back_ptr;
1228  av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n",
1229  stream_index, *pos_arg, pos_limit);
1230 
1231  pos = *pos_arg;
1232  do {
1233  pos = find_startcode(bc, SYNCPOINT_STARTCODE, pos) + 1;
1234  if (pos < 1) {
1235  av_log(s, AV_LOG_ERROR, "read_timestamp failed.\n");
1236  return AV_NOPTS_VALUE;
1237  }
1238  } while (decode_syncpoint(nut, &pts, &back_ptr) < 0);
1239  *pos_arg = pos - 1;
1240  av_assert0(nut->last_syncpoint_pos == *pos_arg);
1241 
1242  av_log(s, AV_LOG_DEBUG, "return %"PRId64" %"PRId64"\n", pts, back_ptr);
1243  if (stream_index == -2)
1244  return back_ptr;
1245  av_assert0(stream_index == -1);
1246  return pts;
1247 }
1248 
1249 static int read_seek(AVFormatContext *s, int stream_index,
1250  int64_t pts, int flags)
1251 {
1252  NUTContext *nut = s->priv_data;
1253  AVStream *st = s->streams[stream_index];
1254  Syncpoint dummy = { .ts = pts * av_q2d(st->time_base) * AV_TIME_BASE };
1255  Syncpoint nopts_sp = { .ts = AV_NOPTS_VALUE, .back_ptr = AV_NOPTS_VALUE };
1256  Syncpoint *sp, *next_node[2] = { &nopts_sp, &nopts_sp };
1257  int64_t pos, pos2, ts;
1258  int i;
1259 
1260  if (nut->flags & NUT_PIPE) {
1261  return AVERROR(ENOSYS);
1262  }
1263 
1264  if (st->index_entries) {
1265  int index = av_index_search_timestamp(st, pts, flags);
1266  if (index < 0)
1267  index = av_index_search_timestamp(st, pts, flags ^ AVSEEK_FLAG_BACKWARD);
1268  if (index < 0)
1269  return -1;
1270 
1271  pos2 = st->index_entries[index].pos;
1272  ts = st->index_entries[index].timestamp;
1273  } else {
1274  av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pts_cmp,
1275  (void **) next_node);
1276  av_log(s, AV_LOG_DEBUG, "%"PRIu64"-%"PRIu64" %"PRId64"-%"PRId64"\n",
1277  next_node[0]->pos, next_node[1]->pos, next_node[0]->ts,
1278  next_node[1]->ts);
1279  pos = ff_gen_search(s, -1, dummy.ts, next_node[0]->pos,
1280  next_node[1]->pos, next_node[1]->pos,
1281  next_node[0]->ts, next_node[1]->ts,
1283  if (pos < 0)
1284  return pos;
1285 
1286  if (!(flags & AVSEEK_FLAG_BACKWARD)) {
1287  dummy.pos = pos + 16;
1288  next_node[1] = &nopts_sp;
1289  av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
1290  (void **) next_node);
1291  pos2 = ff_gen_search(s, -2, dummy.pos, next_node[0]->pos,
1292  next_node[1]->pos, next_node[1]->pos,
1293  next_node[0]->back_ptr, next_node[1]->back_ptr,
1294  flags, &ts, nut_read_timestamp);
1295  if (pos2 >= 0)
1296  pos = pos2;
1297  // FIXME dir but I think it does not matter
1298  }
1299  dummy.pos = pos;
1300  sp = av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
1301  NULL);
1302 
1303  av_assert0(sp);
1304  pos2 = sp->back_ptr - 15;
1305  }
1306  av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
1307  pos = find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
1308  avio_seek(s->pb, pos, SEEK_SET);
1309  nut->last_syncpoint_pos = pos;
1310  av_log(NULL, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
1311  if (pos2 > pos || pos2 + 15 < pos)
1312  av_log(NULL, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
1313  for (i = 0; i < s->nb_streams; i++)
1314  nut->stream[i].skip_until_key_frame = 1;
1315 
1316  nut->last_resync_pos = 0;
1317 
1318  return 0;
1319 }
1320 
1322  .name = "nut",
1323  .long_name = NULL_IF_CONFIG_SMALL("NUT"),
1324  .flags = AVFMT_SEEK_TO_PTS,
1325  .priv_data_size = sizeof(NUTContext),
1326  .read_probe = nut_probe,
1330  .read_seek = read_seek,
1331  .extensions = "nut",
1332  .codec_tag = ff_nut_codec_tags,
1333 };
#define AVSEEK_FLAG_BACKWARD
Definition: avformat.h:2277
uint8_t header_len[128]
Definition: nut.h:97
#define NULL
Definition: coverity.c:32
uint64_t ffio_read_varlen(AVIOContext *bc)
Definition: aviobuf.c:765
discard all frames except keyframes
Definition: avcodec.h:688
float v
const char * s
Definition: avisynth_c.h:631
Bytestream IO Context.
Definition: avio.h:111
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
#define MAIN_STARTCODE
Definition: nut.h:29
void ff_metadata_conv_ctx(AVFormatContext *ctx, const AVMetadataConv *d_conv, const AVMetadataConv *s_conv)
Definition: metadata.c:59
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:282
#define AVSTREAM_EVENT_FLAG_METADATA_UPDATED
The call resulted in updated metadata.
Definition: avformat.h:966
void av_free_packet(AVPacket *pkt)
Free a packet.
Definition: avpacket.c:280
int64_t last_syncpoint_pos
Definition: nut.h:104
int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp, int size, int distance, int flags)
Add an index entry into a sorted list.
Definition: utils.c:1745
enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
Definition: utils.c:2773
enum AVDurationEstimationMethod duration_estimation_method
The duration field can be estimated through various ways, and this field can be used to know how the ...
Definition: avformat.h:1632
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
int64_t pos
byte position in stream, -1 if unknown
Definition: avcodec.h:1448
void av_shrink_packet(AVPacket *pkt, int size)
Reduce packet size, correctly zeroing padding.
Definition: avpacket.c:103
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4083
const AVCodecTag ff_nut_audio_extra_tags[]
Definition: nut.c:181
int64_t pos
Definition: avformat.h:784
int ff_get_extradata(AVCodecContext *avctx, AVIOContext *pb, int size)
Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end which is always set to 0 and f...
Definition: utils.c:2945
int event_flags
Flags for the user to detect events happening on the stream.
Definition: avformat.h:965
int64_t data_offset
offset of the first packet
Definition: internal.h:80
static int get_str(AVIOContext *bc, char *string, unsigned int maxlen)
Definition: nutdec.c:41
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:914
int num
numerator
Definition: rational.h:44
int size
Definition: avcodec.h:1424
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:204
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition: avformat.h:1045
AVFormatInternal * internal
An opaque field for libavformat internal usage.
Definition: avformat.h:1698
Definition: nut.h:58
#define NUT_MAX_STREAMS
Definition: nutdec.c:36
int64_t ts
Definition: nut.h:62
int event_flags
Flags for the user to detect events happening on the file.
Definition: avformat.h:1560
static void set_disposition_bits(AVFormatContext *avf, char *value, int stream_id)
Definition: nutdec.c:500
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: aviobuf.c:277
discard all
Definition: avcodec.h:689
static AVPacket pkt
uint8_t stream_id
Definition: nut.h:67
AVDictionary * metadata
Definition: avformat.h:1240
static int decode_main_header(NUTContext *nut)
Definition: nutdec.c:228
const uint8_t * header[128]
Definition: nut.h:98
AVChapter * avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
Add a new chapter.
Definition: utils.c:3845
Format I/O context.
Definition: avformat.h:1273
static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id, uint8_t *header_idx, int frame_code)
Definition: nutdec.c:1014
#define AV_WB64(p, v)
Definition: intreadwrite.h:433
static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index, int64_t *pos_arg, int64_t pos_limit)
Definition: nutdec.c:1222
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
Public dictionary API.
void * av_tree_find(const AVTreeNode *t, void *key, int(*cmp)(void *key, const void *b), void *next[2])
Definition: tree.c:39
uint8_t
AVRational * time_base
Definition: nut.h:107
static int nb_streams
Definition: ffprobe.c:226
#define av_malloc(s)
Opaque data information usually continuous.
Definition: avutil.h:195
int decode_delay
Definition: nut.h:83
uint16_t flags
Definition: nut.h:66
static int nut_probe(AVProbeData *p)
Definition: nutdec.c:188
A tree container.
enum AVCodecID av_codec_get_id(const struct AVCodecTag *const *tags, unsigned int tag)
Get the AVCodecID for the given codec tag tag.
const AVCodecTag ff_codec_movvideo_tags[]
Definition: isom.c:71
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:690
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:90
#define NUT_MAX_VERSION
Definition: nut.h:39
static int64_t last_pts
#define STREAM_STARTCODE
Definition: nut.h:30
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1617
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:3749
int64_t last_resync_pos
Definition: nut.h:105
#define NUT_PIPE
Definition: nut.h:114
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_RB32
Definition: bytestream.h:87
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1341
const AVMetadataConv ff_nut_metadata_conv[]
Definition: nut.c:297
static double av_q2d(AVRational a)
Convert rational to double.
Definition: rational.h:80
uint8_t * data
Definition: avcodec.h:1423
int last_flags
Definition: nut.h:76
static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code)
Definition: nutdec.c:1097
#define AVERROR_EOF
End of file.
Definition: error.h:55
#define sp
Definition: regdef.h:63
static av_cold int read_close(AVFormatContext *ctx)
Definition: libcdio.c:145
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
const AVCodecTag ff_nut_data_tags[]
Definition: nut.c:37
ptrdiff_t size
Definition: opengl_enc.c:101
uint64_t avio_rb64(AVIOContext *s)
Definition: aviobuf.c:757
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:390
static int64_t duration
Definition: ffplay.c:326
#define A(x)
Definition: vp56_arith.h:28
#define av_log(a,...)
int ff_nut_sp_pos_cmp(const Syncpoint *a, const Syncpoint *b)
Definition: nut.c:240
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:538
AVFormatContext * avf
Definition: nut.h:93
int flag
Definition: checkasm.c:76
int64_t last_pts
Definition: nut.h:78
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1469
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:140
#define U(x)
Definition: vp56_arith.h:37
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition: avpacket.c:83
#define AVINDEX_KEYFRAME
Definition: avformat.h:791
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1485
int has_b_frames
Size of the frame reordering buffer in the decoder.
Definition: avcodec.h:1812
void ff_nut_free_sp(NUTContext *nut)
Definition: nut.c:281
int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags)
Get the index for a specific timestamp.
Definition: utils.c:1844
#define NUT_BROADCAST
Definition: nut.h:113
unsigned int avio_rl32(AVIOContext *s)
Definition: aviobuf.c:659
discard all bidirectional frames
Definition: avcodec.h:686
An AV_PKT_DATA_PARAM_CHANGE side data packet is laid out as follows:
Definition: avcodec.h:1243
#define AVERROR(e)
Definition: error.h:43
uint64_t pos
Definition: nut.h:59
int64_t timestamp
Timestamp in AVStream.time_base units, preferably the time from which on correctly decoded frames are...
Definition: avformat.h:785
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:175
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
Definition: graph2dot.c:48
simple assert() macros that are a bit more flexible than ISO C assert().
int64_t av_gcd(int64_t a, int64_t b)
Return the greatest common divisor of a and b.
Definition: mathematics.c:55
static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: nutdec.c:1164
const AVCodecTag ff_nut_audio_tags[]
Definition: nut.c:190
int header_count
Definition: nut.h:106
AVRational * time_base
Definition: nut.h:80
#define NUT_MIN_VERSION
Definition: nut.h:41
static int decode_stream_header(NUTContext *nut)
Definition: nutdec.c:393
#define av_be2ne64(x)
Definition: bswap.h:94
GLsizei count
Definition: opengl_enc.c:109
const AVCodecTag ff_codec_wav_tags[]
Definition: riff.c:378
#define FFMAX(a, b)
Definition: common.h:79
#define fail()
Definition: checkasm.h:57
Definition: nut.h:44
int ff_nut_sp_pts_cmp(const Syncpoint *a, const Syncpoint *b)
Definition: nut.c:245
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1429
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:529
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:861
static int nut_read_close(AVFormatContext *s)
Definition: nutdec.c:806
int buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:451
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:450
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1329
void ffio_init_checksum(AVIOContext *s, unsigned long(*update_checksum)(unsigned long c, const uint8_t *p, unsigned int len), unsigned long checksum)
Definition: aviobuf.c:517
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:160
void ff_nut_reset_ts(NUTContext *nut, AVRational time_base, int64_t val)
Definition: nut.c:222
int flags
Definition: nut.h:115
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:246
#define FFMIN(a, b)
Definition: common.h:81
const AVCodecTag ff_codec_bmp_tags[]
Definition: riff.c:32
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition: avstring.c:213
uint8_t header_idx
Definition: nut.h:72
static int read_probe(AVProbeData *pd)
Definition: jvdec.c:55
int width
picture width / height.
Definition: avcodec.h:1681
static uint64_t find_any_startcode(AVIOContext *bc, int64_t pos)
Definition: nutdec.c:145
GLsizei GLboolean const GLfloat * value
Definition: opengl_enc.c:109
uint16_t size_lsb
Definition: nut.h:69
unsigned long ff_crc04C11DB7_update(unsigned long checksum, const uint8_t *buf, unsigned int len)
Definition: aviobuf.c:497
int16_t pts_delta
Definition: nut.h:70
static int find_and_decode_index(NUTContext *nut)
Definition: nutdec.c:692
int64_t ff_lsb2full(StreamContext *stream, int64_t lsb)
Definition: nut.c:233
static struct @197 state
internal header for RIFF based (de)muxers do NOT include this in end user applications ...
static uint64_t get_fourcc(AVIOContext *bc)
Definition: nutdec.c:75
static int get_packetheader(NUTContext *nut, AVIOContext *bc, int calculate_checksum, uint64_t startcode)
Definition: nutdec.c:124
#define AVFMT_EVENT_FLAG_METADATA_UPDATED
The call resulted in updated metadata.
Definition: avformat.h:1561
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
Definition: common.h:68
struct AVTreeNode * syncpoints
Definition: nut.h:108
int n
Definition: avisynth_c.h:547
AVDictionary * metadata
Definition: avformat.h:916
static int nut_read_header(AVFormatContext *s)
Definition: nutdec.c:820
#define INDEX_STARTCODE
Definition: nut.h:32
uint16_t size_mul
Definition: nut.h:68
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:623
static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr)
Definition: nutdec.c:636
Stream structure.
Definition: avformat.h:842
int msb_pts_shift
Definition: nut.h:81
static int read_packet(void *opaque, uint8_t *buf, int buf_size)
Definition: avio_reading.c:42
static int read_sm_data(AVFormatContext *s, AVIOContext *bc, AVPacket *pkt, int is_meta, int64_t maxpos)
Definition: nutdec.c:889
sample_rate
#define AV_LOG_INFO
Standard information.
Definition: log.h:187
enum AVMediaType codec_type
Definition: avcodec.h:1510
static int resync(AVIOContext *pb)
Definition: gifdec.c:84
const AVCodecTag ff_nut_subtitle_tags[]
Definition: nut.c:28
enum AVCodecID codec_id
Definition: avcodec.h:1519
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:252
int sample_rate
samples per second
Definition: avcodec.h:2262
AVIOContext * pb
I/O context.
Definition: avformat.h:1315
int max_pts_distance
Definition: nut.h:82
unsigned int codec_tag
fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
Definition: avcodec.h:1534
Definition: nut.h:54
Data found in BlockAdditional element of matroska container.
Definition: avcodec.h:1349
GLint GLenum type
Definition: opengl_enc.c:105
int extradata_size
Definition: avcodec.h:1618
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:69
#define GET_V(dst, check)
Definition: nutdec.c:201
BYTE int const BYTE int int int height
Definition: avisynth_c.h:676
int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, int64_t pos_min, int64_t pos_max, int64_t pos_limit, int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret, int64_t(*read_timestamp)(struct AVFormatContext *, int, int64_t *, int64_t))
Perform a binary search using read_timestamp().
Definition: utils.c:1965
int index
Definition: gxfenc.c:89
rational number numerator/denominator
Definition: rational.h:43
Recommmends skipping the specified number of samples.
Definition: avcodec.h:1314
byte swapping routines
unsigned long ffio_get_checksum(AVIOContext *s)
Definition: aviobuf.c:509
int(* func)(AVBPrint *dst, const char *in, const char *arg)
Definition: jacosubdec.c:67
StreamContext * stream
Definition: nut.h:100
static int skip_reserved(AVIOContext *bc, int64_t pos)
Definition: nutdec.c:212
#define AVFMT_SEEK_TO_PTS
Seeking is based on PTS.
Definition: avformat.h:506
static int64_t find_startcode(AVIOContext *bc, uint64_t code, int64_t pos)
Find the given startcode.
Definition: nutdec.c:176
This structure contains the data a format has to probe a file.
Definition: avformat.h:448
static int read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags)
Definition: nutdec.c:1249
int ff_find_last_ts(AVFormatContext *s, int stream_index, int64_t *ts, int64_t *pos, int64_t(*read_timestamp)(struct AVFormatContext *, int, int64_t *, int64_t))
Definition: utils.c:1927
#define INFO_STARTCODE
Definition: nut.h:33
void * av_calloc(size_t nmemb, size_t size)
Allocate a block of nmemb * size bytes with alignment suitable for all memory accesses (including vec...
Definition: mem.c:260
static int64_t pts
Global timestamp for the audio frames.
int version
Definition: nut.h:116
static int flags
Definition: cpu.c:47
Duration accurately estimated from PTSes.
Definition: avformat.h:1258
int skip_until_key_frame
Definition: nut.h:77
static int64_t find_duration(NUTContext *nut, int64_t filesize)
Definition: nutdec.c:680
const Dispositions ff_nut_dispositions[]
Definition: nut.c:287
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:460
unsigned int avio_rl16(AVIOContext *s)
Definition: aviobuf.c:643
uint64_t next_startcode
Definition: nut.h:99
static int decode_info_header(NUTContext *nut)
Definition: nutdec.c:515
FrameCode frame_code[256]
Definition: nut.h:96
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:905
const AVCodecTag ff_nut_video_tags[]
Definition: nut.c:42
int ff_nut_add_sp(NUTContext *nut, int64_t pos, int64_t back_ptr, int64_t ts)
Definition: nut.c:250
int den
denominator
Definition: rational.h:45
#define SYNCPOINT_STARTCODE
Definition: nut.h:31
int flag
Definition: nut.h:130
Definition: vf_geq.c:46
#define av_free(p)
int eof_reached
true if eof reached
Definition: avio.h:139
int len
AVInputFormat ff_nut_demuxer
Definition: nutdec.c:1321
int channels
number of audio channels
Definition: avcodec.h:2263
static int64_t get_s(AVIOContext *bc)
Definition: nutdec.c:65
void * priv_data
Format private data.
Definition: avformat.h:1301
int time_base_id
Definition: nut.h:79
int64_t duration
Duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:1368
int64_t last_IP_pts
Definition: avformat.h:1020
#define av_freep(p)
void INT64 start
Definition: avisynth_c.h:553
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:628
#define av_malloc_array(a, b)
int avio_feof(AVIOContext *s)
feof() equivalent for AVIOContext.
Definition: aviobuf.c:301
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size)
Allocate new information of a packet.
Definition: avpacket.c:299
int stream_index
Definition: avcodec.h:1425
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:884
int dummy
Definition: motion-test.c:64
uint64_t back_ptr
Definition: nut.h:60
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition: avformat.h:907
AVRational r_frame_rate
Real base framerate of the stream.
Definition: avformat.h:1061
const AVCodecTag *const ff_nut_codec_tags[]
Definition: nut.c:217
This structure stores compressed data.
Definition: avcodec.h:1400
uint64_t avio_rl64(AVIOContext *s)
Definition: aviobuf.c:667
unsigned int time_base_count
Definition: nut.h:103
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1416
int minor_version
Definition: nut.h:117
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:240
uint8_t reserved_count
Definition: nut.h:71
#define AV_WL32(p, v)
Definition: intreadwrite.h:426
const char * name
Definition: opengl_enc.c:103
unsigned int max_distance
Definition: nut.h:102
static int width