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  return AVERROR_INVALIDDATA; \
207  } \
208  dst = tmp; \
209  } while (0)
210 
211 static int skip_reserved(AVIOContext *bc, int64_t pos)
212 {
213  pos -= avio_tell(bc);
214  if (pos < 0) {
215  avio_seek(bc, pos, SEEK_CUR);
216  return AVERROR_INVALIDDATA;
217  } else {
218  while (pos--) {
219  if (bc->eof_reached)
220  return AVERROR_INVALIDDATA;
221  avio_r8(bc);
222  }
223  return 0;
224  }
225 }
226 
228 {
229  AVFormatContext *s = nut->avf;
230  AVIOContext *bc = s->pb;
231  uint64_t tmp, end;
232  unsigned int stream_count;
233  int i, j, count;
234  int tmp_stream, tmp_mul, tmp_pts, tmp_size, tmp_res, tmp_head_idx;
235 
236  end = get_packetheader(nut, bc, 1, MAIN_STARTCODE);
237  end += avio_tell(bc);
238 
239  nut->version = ffio_read_varlen(bc);
240  if (nut->version < NUT_MIN_VERSION &&
241  nut->version > NUT_MAX_VERSION) {
242  av_log(s, AV_LOG_ERROR, "Version %d not supported.\n",
243  nut->version);
244  return AVERROR(ENOSYS);
245  }
246  if (nut->version > 3)
247  nut->minor_version = ffio_read_varlen(bc);
248 
249  GET_V(stream_count, tmp > 0 && tmp <= NUT_MAX_STREAMS);
250 
251  nut->max_distance = ffio_read_varlen(bc);
252  if (nut->max_distance > 65536) {
253  av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);
254  nut->max_distance = 65536;
255  }
256 
257  GET_V(nut->time_base_count, tmp > 0 && tmp < INT_MAX / sizeof(AVRational));
258  nut->time_base = av_malloc_array(nut->time_base_count, sizeof(AVRational));
259  if (!nut->time_base)
260  return AVERROR(ENOMEM);
261 
262  for (i = 0; i < nut->time_base_count; i++) {
263  GET_V(nut->time_base[i].num, tmp > 0 && tmp < (1ULL << 31));
264  GET_V(nut->time_base[i].den, tmp > 0 && tmp < (1ULL << 31));
265  if (av_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1) {
266  av_log(s, AV_LOG_ERROR, "time base invalid\n");
267  return AVERROR_INVALIDDATA;
268  }
269  }
270  tmp_pts = 0;
271  tmp_mul = 1;
272  tmp_stream = 0;
273  tmp_head_idx = 0;
274  for (i = 0; i < 256;) {
275  int tmp_flags = ffio_read_varlen(bc);
276  int tmp_fields = ffio_read_varlen(bc);
277 
278  if (tmp_fields > 0)
279  tmp_pts = get_s(bc);
280  if (tmp_fields > 1)
281  tmp_mul = ffio_read_varlen(bc);
282  if (tmp_fields > 2)
283  tmp_stream = ffio_read_varlen(bc);
284  if (tmp_fields > 3)
285  tmp_size = ffio_read_varlen(bc);
286  else
287  tmp_size = 0;
288  if (tmp_fields > 4)
289  tmp_res = ffio_read_varlen(bc);
290  else
291  tmp_res = 0;
292  if (tmp_fields > 5)
293  count = ffio_read_varlen(bc);
294  else
295  count = tmp_mul - tmp_size;
296  if (tmp_fields > 6)
297  get_s(bc);
298  if (tmp_fields > 7)
299  tmp_head_idx = ffio_read_varlen(bc);
300 
301  while (tmp_fields-- > 8) {
302  if (bc->eof_reached) {
303  av_log(s, AV_LOG_ERROR, "reached EOF while decoding main header\n");
304  return AVERROR_INVALIDDATA;
305  }
306  ffio_read_varlen(bc);
307  }
308 
309  if (count <= 0 || count > 256 - (i <= 'N') - i) {
310  av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
311  return AVERROR_INVALIDDATA;
312  }
313  if (tmp_stream >= stream_count) {
314  av_log(s, AV_LOG_ERROR, "illegal stream number\n");
315  return AVERROR_INVALIDDATA;
316  }
317 
318  for (j = 0; j < count; j++, i++) {
319  if (i == 'N') {
320  nut->frame_code[i].flags = FLAG_INVALID;
321  j--;
322  continue;
323  }
324  nut->frame_code[i].flags = tmp_flags;
325  nut->frame_code[i].pts_delta = tmp_pts;
326  nut->frame_code[i].stream_id = tmp_stream;
327  nut->frame_code[i].size_mul = tmp_mul;
328  nut->frame_code[i].size_lsb = tmp_size + j;
329  nut->frame_code[i].reserved_count = tmp_res;
330  nut->frame_code[i].header_idx = tmp_head_idx;
331  }
332  }
333  av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
334 
335  if (end > avio_tell(bc) + 4) {
336  int rem = 1024;
337  GET_V(nut->header_count, tmp < 128U);
338  nut->header_count++;
339  for (i = 1; i < nut->header_count; i++) {
340  uint8_t *hdr;
341  GET_V(nut->header_len[i], tmp > 0 && tmp < 256);
342  rem -= nut->header_len[i];
343  if (rem < 0) {
344  av_log(s, AV_LOG_ERROR, "invalid elision header\n");
345  return AVERROR_INVALIDDATA;
346  }
347  hdr = av_malloc(nut->header_len[i]);
348  if (!hdr)
349  return AVERROR(ENOMEM);
350  avio_read(bc, hdr, nut->header_len[i]);
351  nut->header[i] = hdr;
352  }
353  av_assert0(nut->header_len[0] == 0);
354  }
355 
356  // flags had been effectively introduced in version 4
357  if (nut->version > 3 && end > avio_tell(bc) + 4) {
358  nut->flags = ffio_read_varlen(bc);
359  }
360 
361  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
362  av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
363  return AVERROR_INVALIDDATA;
364  }
365 
366  nut->stream = av_calloc(stream_count, sizeof(StreamContext));
367  if (!nut->stream)
368  return AVERROR(ENOMEM);
369  for (i = 0; i < stream_count; i++)
371 
372  return 0;
373 }
374 
376 {
377  AVFormatContext *s = nut->avf;
378  AVIOContext *bc = s->pb;
379  StreamContext *stc;
380  int class, stream_id;
381  uint64_t tmp, end;
382  AVStream *st;
383 
384  end = get_packetheader(nut, bc, 1, STREAM_STARTCODE);
385  end += avio_tell(bc);
386 
387  GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);
388  stc = &nut->stream[stream_id];
389  st = s->streams[stream_id];
390  if (!st)
391  return AVERROR(ENOMEM);
392 
393  class = ffio_read_varlen(bc);
394  tmp = get_fourcc(bc);
395  st->codec->codec_tag = tmp;
396  switch (class) {
397  case 0:
399  st->codec->codec_id = av_codec_get_id((const AVCodecTag * const []) {
403  0
404  },
405  tmp);
406  break;
407  case 1:
409  st->codec->codec_id = av_codec_get_id((const AVCodecTag * const []) {
413  0
414  },
415  tmp);
416  break;
417  case 2:
420  break;
421  case 3:
424  break;
425  default:
426  av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
427  return AVERROR(ENOSYS);
428  }
429  if (class < 3 && st->codec->codec_id == AV_CODEC_ID_NONE)
430  av_log(s, AV_LOG_ERROR,
431  "Unknown codec tag '0x%04x' for stream number %d\n",
432  (unsigned int) tmp, stream_id);
433 
434  GET_V(stc->time_base_id, tmp < nut->time_base_count);
435  GET_V(stc->msb_pts_shift, tmp < 16);
437  GET_V(stc->decode_delay, tmp < 1000); // sanity limit, raise this if Moore's law is true
438  st->codec->has_b_frames = stc->decode_delay;
439  ffio_read_varlen(bc); // stream flags
440 
441  GET_V(st->codec->extradata_size, tmp < (1 << 30));
442  if (st->codec->extradata_size) {
443  if (ff_get_extradata(st->codec, bc, st->codec->extradata_size) < 0)
444  return AVERROR(ENOMEM);
445  }
446 
447  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
448  GET_V(st->codec->width, tmp > 0);
449  GET_V(st->codec->height, tmp > 0);
452  if ((!st->sample_aspect_ratio.num) != (!st->sample_aspect_ratio.den)) {
453  av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n",
455  return AVERROR_INVALIDDATA;
456  }
457  ffio_read_varlen(bc); /* csp type */
458  } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
459  GET_V(st->codec->sample_rate, tmp > 0);
460  ffio_read_varlen(bc); // samplerate_den
461  GET_V(st->codec->channels, tmp > 0);
462  }
463  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
464  av_log(s, AV_LOG_ERROR,
465  "stream header %d checksum mismatch\n", stream_id);
466  return AVERROR_INVALIDDATA;
467  }
468  stc->time_base = &nut->time_base[stc->time_base_id];
469  avpriv_set_pts_info(s->streams[stream_id], 63, stc->time_base->num,
470  stc->time_base->den);
471  return 0;
472 }
473 
475  int stream_id)
476 {
477  int flag = 0, i;
478 
479  for (i = 0; ff_nut_dispositions[i].flag; ++i)
480  if (!strcmp(ff_nut_dispositions[i].str, value))
481  flag = ff_nut_dispositions[i].flag;
482  if (!flag)
483  av_log(avf, AV_LOG_INFO, "unknown disposition type '%s'\n", value);
484  for (i = 0; i < avf->nb_streams; ++i)
485  if (stream_id == i || stream_id == -1)
486  avf->streams[i]->disposition |= flag;
487 }
488 
490 {
491  AVFormatContext *s = nut->avf;
492  AVIOContext *bc = s->pb;
493  uint64_t tmp, chapter_start, chapter_len;
494  unsigned int stream_id_plus1, count;
495  int chapter_id, i, ret;
496  int64_t value, end;
497  char name[256], str_value[1024], type_str[256];
498  const char *type;
499  int *event_flags = NULL;
500  AVChapter *chapter = NULL;
501  AVStream *st = NULL;
502  AVDictionary **metadata = NULL;
503  int metadata_flag = 0;
504 
505  end = get_packetheader(nut, bc, 1, INFO_STARTCODE);
506  end += avio_tell(bc);
507 
508  GET_V(stream_id_plus1, tmp <= s->nb_streams);
509  chapter_id = get_s(bc);
510  chapter_start = ffio_read_varlen(bc);
511  chapter_len = ffio_read_varlen(bc);
512  count = ffio_read_varlen(bc);
513 
514  if (chapter_id && !stream_id_plus1) {
515  int64_t start = chapter_start / nut->time_base_count;
516  chapter = avpriv_new_chapter(s, chapter_id,
517  nut->time_base[chapter_start %
518  nut->time_base_count],
519  start, start + chapter_len, NULL);
520  if (!chapter) {
521  av_log(s, AV_LOG_ERROR, "Could not create chapter.\n");
522  return AVERROR(ENOMEM);
523  }
524  metadata = &chapter->metadata;
525  } else if (stream_id_plus1) {
526  st = s->streams[stream_id_plus1 - 1];
527  metadata = &st->metadata;
528  event_flags = &st->event_flags;
529  metadata_flag = AVSTREAM_EVENT_FLAG_METADATA_UPDATED;
530  } else {
531  metadata = &s->metadata;
532  event_flags = &s->event_flags;
533  metadata_flag = AVFMT_EVENT_FLAG_METADATA_UPDATED;
534  }
535 
536  for (i = 0; i < count; i++) {
537  ret = get_str(bc, name, sizeof(name));
538  if (ret < 0) {
539  av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
540  return ret;
541  }
542  value = get_s(bc);
543  str_value[0] = 0;
544 
545  if (value == -1) {
546  type = "UTF-8";
547  get_str(bc, str_value, sizeof(str_value));
548  } else if (value == -2) {
549  get_str(bc, type_str, sizeof(type_str));
550  type = type_str;
551  get_str(bc, str_value, sizeof(str_value));
552  } else if (value == -3) {
553  type = "s";
554  value = get_s(bc);
555  } else if (value == -4) {
556  type = "t";
557  value = ffio_read_varlen(bc);
558  } else if (value < -4) {
559  type = "r";
560  get_s(bc);
561  } else {
562  type = "v";
563  }
564 
565  if (stream_id_plus1 > s->nb_streams) {
566  av_log(s, AV_LOG_ERROR, "invalid stream id for info packet\n");
567  continue;
568  }
569 
570  if (!strcmp(type, "UTF-8")) {
571  if (chapter_id == 0 && !strcmp(name, "Disposition")) {
572  set_disposition_bits(s, str_value, stream_id_plus1 - 1);
573  continue;
574  }
575 
576  if (stream_id_plus1 && !strcmp(name, "r_frame_rate")) {
577  sscanf(str_value, "%d/%d", &st->r_frame_rate.num, &st->r_frame_rate.den);
578  if (st->r_frame_rate.num >= 1000LL*st->r_frame_rate.den ||
579  st->r_frame_rate.num < 0 || st->r_frame_rate.num < 0)
580  st->r_frame_rate.num = st->r_frame_rate.den = 0;
581  continue;
582  }
583 
584  if (metadata && av_strcasecmp(name, "Uses") &&
585  av_strcasecmp(name, "Depends") && av_strcasecmp(name, "Replaces")) {
586  if (event_flags)
587  *event_flags |= metadata_flag;
588  av_dict_set(metadata, name, str_value, 0);
589  }
590  }
591  }
592 
593  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
594  av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
595  return AVERROR_INVALIDDATA;
596  }
597  return 0;
598 }
599 
600 static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr)
601 {
602  AVFormatContext *s = nut->avf;
603  AVIOContext *bc = s->pb;
604  int64_t end;
605  uint64_t tmp;
606  int ret;
607 
608  nut->last_syncpoint_pos = avio_tell(bc) - 8;
609 
610  end = get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
611  end += avio_tell(bc);
612 
613  tmp = ffio_read_varlen(bc);
614  *back_ptr = nut->last_syncpoint_pos - 16 * ffio_read_varlen(bc);
615  if (*back_ptr < 0)
616  return AVERROR_INVALIDDATA;
617 
618  ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count],
619  tmp / nut->time_base_count);
620 
621  if (nut->flags & NUT_BROADCAST) {
622  tmp = ffio_read_varlen(bc);
623  av_log(s, AV_LOG_VERBOSE, "Syncpoint wallclock %"PRId64"\n",
624  av_rescale_q(tmp / nut->time_base_count,
625  nut->time_base[tmp % nut->time_base_count],
626  AV_TIME_BASE_Q));
627  }
628 
629  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
630  av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
631  return AVERROR_INVALIDDATA;
632  }
633 
634  *ts = tmp / nut->time_base_count *
635  av_q2d(nut->time_base[tmp % nut->time_base_count]) * AV_TIME_BASE;
636 
637  if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts)) < 0)
638  return ret;
639 
640  return 0;
641 }
642 
643 //FIXME calculate exactly, this is just a good approximation.
644 static int64_t find_duration(NUTContext *nut, int64_t filesize)
645 {
646  AVFormatContext *s = nut->avf;
647  int64_t duration = 0;
648 
649  ff_find_last_ts(s, -1, &duration, NULL, nut_read_timestamp);
650 
651  if(duration > 0)
653  return duration;
654 }
655 
657 {
658  AVFormatContext *s = nut->avf;
659  AVIOContext *bc = s->pb;
660  uint64_t tmp, end;
661  int i, j, syncpoint_count;
662  int64_t filesize = avio_size(bc);
663  int64_t *syncpoints;
664  uint64_t max_pts;
665  int8_t *has_keyframe;
666  int ret = AVERROR_INVALIDDATA;
667 
668  if(filesize <= 0)
669  return -1;
670 
671  avio_seek(bc, filesize - 12, SEEK_SET);
672  avio_seek(bc, filesize - avio_rb64(bc), SEEK_SET);
673  if (avio_rb64(bc) != INDEX_STARTCODE) {
674  av_log(s, AV_LOG_ERROR, "no index at the end\n");
675 
676  if(s->duration<=0)
677  s->duration = find_duration(nut, filesize);
678  return ret;
679  }
680 
681  end = get_packetheader(nut, bc, 1, INDEX_STARTCODE);
682  end += avio_tell(bc);
683 
684  max_pts = ffio_read_varlen(bc);
685  s->duration = av_rescale_q(max_pts / nut->time_base_count,
686  nut->time_base[max_pts % nut->time_base_count],
689 
690  GET_V(syncpoint_count, tmp < INT_MAX / 8 && tmp > 0);
691  syncpoints = av_malloc_array(syncpoint_count, sizeof(int64_t));
692  has_keyframe = av_malloc_array(syncpoint_count + 1, sizeof(int8_t));
693  if (!syncpoints || !has_keyframe) {
694  ret = AVERROR(ENOMEM);
695  goto fail;
696  }
697  for (i = 0; i < syncpoint_count; i++) {
698  syncpoints[i] = ffio_read_varlen(bc);
699  if (syncpoints[i] <= 0)
700  goto fail;
701  if (i)
702  syncpoints[i] += syncpoints[i - 1];
703  }
704 
705  for (i = 0; i < s->nb_streams; i++) {
706  int64_t last_pts = -1;
707  for (j = 0; j < syncpoint_count;) {
708  uint64_t x = ffio_read_varlen(bc);
709  int type = x & 1;
710  int n = j;
711  x >>= 1;
712  if (type) {
713  int flag = x & 1;
714  x >>= 1;
715  if (n + x >= syncpoint_count + 1) {
716  av_log(s, AV_LOG_ERROR, "index overflow A %d + %"PRIu64" >= %d\n", n, x, syncpoint_count + 1);
717  goto fail;
718  }
719  while (x--)
720  has_keyframe[n++] = flag;
721  has_keyframe[n++] = !flag;
722  } else {
723  while (x != 1) {
724  if (n >= syncpoint_count + 1) {
725  av_log(s, AV_LOG_ERROR, "index overflow B\n");
726  goto fail;
727  }
728  has_keyframe[n++] = x & 1;
729  x >>= 1;
730  }
731  }
732  if (has_keyframe[0]) {
733  av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");
734  goto fail;
735  }
736  av_assert0(n <= syncpoint_count + 1);
737  for (; j < n && j < syncpoint_count; j++) {
738  if (has_keyframe[j]) {
739  uint64_t B, A = ffio_read_varlen(bc);
740  if (!A) {
741  A = ffio_read_varlen(bc);
742  B = ffio_read_varlen(bc);
743  // eor_pts[j][i] = last_pts + A + B
744  } else
745  B = 0;
746  av_add_index_entry(s->streams[i], 16 * syncpoints[j - 1],
747  last_pts + A, 0, 0, AVINDEX_KEYFRAME);
748  last_pts += A + B;
749  }
750  }
751  }
752  }
753 
754  if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
755  av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
756  goto fail;
757  }
758  ret = 0;
759 
760 fail:
761  av_free(syncpoints);
762  av_free(has_keyframe);
763  return ret;
764 }
765 
767 {
768  NUTContext *nut = s->priv_data;
769  int i;
770 
771  av_freep(&nut->time_base);
772  av_freep(&nut->stream);
773  ff_nut_free_sp(nut);
774  for (i = 1; i < nut->header_count; i++)
775  av_freep(&nut->header[i]);
776 
777  return 0;
778 }
779 
781 {
782  NUTContext *nut = s->priv_data;
783  AVIOContext *bc = s->pb;
784  int64_t pos;
785  int initialized_stream_count;
786 
787  nut->avf = s;
788 
789  /* main header */
790  pos = 0;
791  do {
792  pos = find_startcode(bc, MAIN_STARTCODE, pos) + 1;
793  if (pos < 0 + 1) {
794  av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
795  goto fail;
796  }
797  } while (decode_main_header(nut) < 0);
798 
799  /* stream headers */
800  pos = 0;
801  for (initialized_stream_count = 0; initialized_stream_count < s->nb_streams;) {
802  pos = find_startcode(bc, STREAM_STARTCODE, pos) + 1;
803  if (pos < 0 + 1) {
804  av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
805  goto fail;
806  }
807  if (decode_stream_header(nut) >= 0)
808  initialized_stream_count++;
809  }
810 
811  /* info headers */
812  pos = 0;
813  for (;;) {
814  uint64_t startcode = find_any_startcode(bc, pos);
815  pos = avio_tell(bc);
816 
817  if (startcode == 0) {
818  av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
819  goto fail;
820  } else if (startcode == SYNCPOINT_STARTCODE) {
821  nut->next_startcode = startcode;
822  break;
823  } else if (startcode != INFO_STARTCODE) {
824  continue;
825  }
826 
827  decode_info_header(nut);
828  }
829 
830  s->internal->data_offset = pos - 8;
831 
832  if (bc->seekable) {
833  int64_t orig_pos = avio_tell(bc);
835  avio_seek(bc, orig_pos, SEEK_SET);
836  }
838 
840 
841  return 0;
842 
843 fail:
844  nut_read_close(s);
845 
846  return AVERROR_INVALIDDATA;
847 }
848 
849 static int read_sm_data(AVFormatContext *s, AVIOContext *bc, AVPacket *pkt, int is_meta, int64_t maxpos)
850 {
851  int count = ffio_read_varlen(bc);
852  int skip_start = 0;
853  int skip_end = 0;
854  int channels = 0;
855  int64_t channel_layout = 0;
856  int sample_rate = 0;
857  int width = 0;
858  int height = 0;
859  int i, ret;
860 
861  for (i=0; i<count; i++) {
862  uint8_t name[256], str_value[256], type_str[256];
863  int value;
864  if (avio_tell(bc) >= maxpos)
865  return AVERROR_INVALIDDATA;
866  ret = get_str(bc, name, sizeof(name));
867  if (ret < 0) {
868  av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
869  return ret;
870  }
871  value = get_s(bc);
872 
873  if (value == -1) {
874  get_str(bc, str_value, sizeof(str_value));
875  av_log(s, AV_LOG_WARNING, "Unknown string %s / %s\n", name, str_value);
876  } else if (value == -2) {
877  uint8_t *dst = NULL;
878  int64_t v64, value_len;
879 
880  get_str(bc, type_str, sizeof(type_str));
881  value_len = ffio_read_varlen(bc);
882  if (avio_tell(bc) + value_len >= maxpos)
883  return AVERROR_INVALIDDATA;
884  if (!strcmp(name, "Palette")) {
885  dst = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, value_len);
886  } else if (!strcmp(name, "Extradata")) {
887  dst = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, value_len);
888  } else if (sscanf(name, "CodecSpecificSide%"SCNd64"", &v64) == 1) {
890  if(!dst)
891  return AVERROR(ENOMEM);
892  AV_WB64(dst, v64);
893  dst += 8;
894  } else if (!strcmp(name, "ChannelLayout") && value_len == 8) {
895  channel_layout = avio_rl64(bc);
896  continue;
897  } else {
898  av_log(s, AV_LOG_WARNING, "Unknown data %s / %s\n", name, type_str);
899  avio_skip(bc, value_len);
900  continue;
901  }
902  if(!dst)
903  return AVERROR(ENOMEM);
904  avio_read(bc, dst, value_len);
905  } else if (value == -3) {
906  value = get_s(bc);
907  } else if (value == -4) {
908  value = ffio_read_varlen(bc);
909  } else if (value < -4) {
910  get_s(bc);
911  } else {
912  if (!strcmp(name, "SkipStart")) {
913  skip_start = value;
914  } else if (!strcmp(name, "SkipEnd")) {
915  skip_end = value;
916  } else if (!strcmp(name, "Channels")) {
917  channels = value;
918  } else if (!strcmp(name, "SampleRate")) {
919  sample_rate = value;
920  } else if (!strcmp(name, "Width")) {
921  width = value;
922  } else if (!strcmp(name, "Height")) {
923  height = value;
924  } else {
925  av_log(s, AV_LOG_WARNING, "Unknown integer %s\n", name);
926  }
927  }
928  }
929 
930  if (channels || channel_layout || sample_rate || width || height) {
932  if (!dst)
933  return AVERROR(ENOMEM);
934  bytestream_put_le32(&dst,
936  AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT*(!!channel_layout) +
937  AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE*(!!sample_rate) +
938  AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS*(!!(width|height))
939  );
940  if (channels)
941  bytestream_put_le32(&dst, channels);
942  if (channel_layout)
943  bytestream_put_le64(&dst, channel_layout);
944  if (sample_rate)
945  bytestream_put_le32(&dst, sample_rate);
946  if (width || height){
947  bytestream_put_le32(&dst, width);
948  bytestream_put_le32(&dst, height);
949  }
950  }
951 
952  if (skip_start || skip_end) {
954  if (!dst)
955  return AVERROR(ENOMEM);
956  AV_WL32(dst, skip_start);
957  AV_WL32(dst+4, skip_end);
958  }
959 
960  return 0;
961 }
962 
963 static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id,
964  uint8_t *header_idx, int frame_code)
965 {
966  AVFormatContext *s = nut->avf;
967  AVIOContext *bc = s->pb;
968  StreamContext *stc;
969  int size, flags, size_mul, pts_delta, i, reserved_count;
970  uint64_t tmp;
971 
972  if (!(nut->flags & NUT_PIPE) &&
973  avio_tell(bc) > nut->last_syncpoint_pos + nut->max_distance) {
974  av_log(s, AV_LOG_ERROR,
975  "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n",
976  avio_tell(bc), nut->last_syncpoint_pos, nut->max_distance);
977  return AVERROR_INVALIDDATA;
978  }
979 
980  flags = nut->frame_code[frame_code].flags;
981  size_mul = nut->frame_code[frame_code].size_mul;
982  size = nut->frame_code[frame_code].size_lsb;
983  *stream_id = nut->frame_code[frame_code].stream_id;
984  pts_delta = nut->frame_code[frame_code].pts_delta;
985  reserved_count = nut->frame_code[frame_code].reserved_count;
986  *header_idx = nut->frame_code[frame_code].header_idx;
987 
988  if (flags & FLAG_INVALID)
989  return AVERROR_INVALIDDATA;
990  if (flags & FLAG_CODED)
991  flags ^= ffio_read_varlen(bc);
992  if (flags & FLAG_STREAM_ID) {
993  GET_V(*stream_id, tmp < s->nb_streams);
994  }
995  stc = &nut->stream[*stream_id];
996  if (flags & FLAG_CODED_PTS) {
997  int coded_pts = ffio_read_varlen(bc);
998  // FIXME check last_pts validity?
999  if (coded_pts < (1 << stc->msb_pts_shift)) {
1000  *pts = ff_lsb2full(stc, coded_pts);
1001  } else
1002  *pts = coded_pts - (1LL << stc->msb_pts_shift);
1003  } else
1004  *pts = stc->last_pts + pts_delta;
1005  if (flags & FLAG_SIZE_MSB)
1006  size += size_mul * ffio_read_varlen(bc);
1007  if (flags & FLAG_MATCH_TIME)
1008  get_s(bc);
1009  if (flags & FLAG_HEADER_IDX)
1010  *header_idx = ffio_read_varlen(bc);
1011  if (flags & FLAG_RESERVED)
1012  reserved_count = ffio_read_varlen(bc);
1013  for (i = 0; i < reserved_count; i++) {
1014  if (bc->eof_reached) {
1015  av_log(s, AV_LOG_ERROR, "reached EOF while decoding frame header\n");
1016  return AVERROR_INVALIDDATA;
1017  }
1018  ffio_read_varlen(bc);
1019  }
1020 
1021  if (*header_idx >= (unsigned)nut->header_count) {
1022  av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
1023  return AVERROR_INVALIDDATA;
1024  }
1025  if (size > 4096)
1026  *header_idx = 0;
1027  size -= nut->header_len[*header_idx];
1028 
1029  if (flags & FLAG_CHECKSUM) {
1030  avio_rb32(bc); // FIXME check this
1031  } else if (!(nut->flags & NUT_PIPE) &&
1032  size > 2 * nut->max_distance ||
1033  FFABS(stc->last_pts - *pts) > stc->max_pts_distance) {
1034  av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
1035  return AVERROR_INVALIDDATA;
1036  }
1037 
1038  stc->last_pts = *pts;
1039  stc->last_flags = flags;
1040 
1041  return size;
1042 }
1043 
1044 static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code)
1045 {
1046  AVFormatContext *s = nut->avf;
1047  AVIOContext *bc = s->pb;
1048  int size, stream_id, discard, ret;
1049  int64_t pts, last_IP_pts;
1050  StreamContext *stc;
1051  uint8_t header_idx;
1052 
1053  size = decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
1054  if (size < 0)
1055  return size;
1056 
1057  stc = &nut->stream[stream_id];
1058 
1059  if (stc->last_flags & FLAG_KEY)
1060  stc->skip_until_key_frame = 0;
1061 
1062  discard = s->streams[stream_id]->discard;
1063  last_IP_pts = s->streams[stream_id]->last_IP_pts;
1064  if ((discard >= AVDISCARD_NONKEY && !(stc->last_flags & FLAG_KEY)) ||
1065  (discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE &&
1066  last_IP_pts > pts) ||
1067  discard >= AVDISCARD_ALL ||
1068  stc->skip_until_key_frame) {
1069  avio_skip(bc, size);
1070  return 1;
1071  }
1072 
1073  ret = av_new_packet(pkt, size + nut->header_len[header_idx]);
1074  if (ret < 0)
1075  return ret;
1076  memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
1077  pkt->pos = avio_tell(bc); // FIXME
1078  if (stc->last_flags & FLAG_SM_DATA) {
1079  int sm_size;
1080  if (read_sm_data(s, bc, pkt, 0, pkt->pos + size) < 0)
1081  return AVERROR_INVALIDDATA;
1082  if (read_sm_data(s, bc, pkt, 1, pkt->pos + size) < 0)
1083  return AVERROR_INVALIDDATA;
1084  sm_size = avio_tell(bc) - pkt->pos;
1085  size -= sm_size;
1086  pkt->size -= sm_size;
1087  }
1088 
1089  ret = avio_read(bc, pkt->data + nut->header_len[header_idx], size);
1090  if (ret != size) {
1091  if (ret < 0)
1092  return ret;
1093  }
1094  av_shrink_packet(pkt, nut->header_len[header_idx] + ret);
1095 
1096  pkt->stream_index = stream_id;
1097  if (stc->last_flags & FLAG_KEY)
1098  pkt->flags |= AV_PKT_FLAG_KEY;
1099  pkt->pts = pts;
1100 
1101  return 0;
1102 }
1103 
1105 {
1106  NUTContext *nut = s->priv_data;
1107  AVIOContext *bc = s->pb;
1108  int i, frame_code = 0, ret, skip;
1109  int64_t ts, back_ptr;
1110 
1111  for (;;) {
1112  int64_t pos = avio_tell(bc);
1113  uint64_t tmp = nut->next_startcode;
1114  nut->next_startcode = 0;
1115 
1116  if (tmp) {
1117  pos -= 8;
1118  } else {
1119  frame_code = avio_r8(bc);
1120  if (avio_feof(bc))
1121  return AVERROR_EOF;
1122  if (frame_code == 'N') {
1123  tmp = frame_code;
1124  for (i = 1; i < 8; i++)
1125  tmp = (tmp << 8) + avio_r8(bc);
1126  }
1127  }
1128  switch (tmp) {
1129  case MAIN_STARTCODE:
1130  case STREAM_STARTCODE:
1131  case INDEX_STARTCODE:
1132  skip = get_packetheader(nut, bc, 0, tmp);
1133  avio_skip(bc, skip);
1134  break;
1135  case INFO_STARTCODE:
1136  if (decode_info_header(nut) < 0)
1137  goto resync;
1138  break;
1139  case SYNCPOINT_STARTCODE:
1140  if (decode_syncpoint(nut, &ts, &back_ptr) < 0)
1141  goto resync;
1142  frame_code = avio_r8(bc);
1143  case 0:
1144  ret = decode_frame(nut, pkt, frame_code);
1145  if (ret == 0)
1146  return 0;
1147  else if (ret == 1) // OK but discard packet
1148  break;
1149  default:
1150 resync:
1151  av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
1152  tmp = find_any_startcode(bc, FFMAX(nut->last_syncpoint_pos, nut->last_resync_pos) + 1);
1153  nut->last_resync_pos = avio_tell(bc);
1154  if (tmp == 0)
1155  return AVERROR_INVALIDDATA;
1156  av_log(s, AV_LOG_DEBUG, "sync\n");
1157  nut->next_startcode = tmp;
1158  }
1159  }
1160 }
1161 
1162 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
1163  int64_t *pos_arg, int64_t pos_limit)
1164 {
1165  NUTContext *nut = s->priv_data;
1166  AVIOContext *bc = s->pb;
1167  int64_t pos, pts, back_ptr;
1168  av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n",
1169  stream_index, *pos_arg, pos_limit);
1170 
1171  pos = *pos_arg;
1172  do {
1173  pos = find_startcode(bc, SYNCPOINT_STARTCODE, pos) + 1;
1174  if (pos < 1) {
1175  av_log(s, AV_LOG_ERROR, "read_timestamp failed.\n");
1176  return AV_NOPTS_VALUE;
1177  }
1178  } while (decode_syncpoint(nut, &pts, &back_ptr) < 0);
1179  *pos_arg = pos - 1;
1180  av_assert0(nut->last_syncpoint_pos == *pos_arg);
1181 
1182  av_log(s, AV_LOG_DEBUG, "return %"PRId64" %"PRId64"\n", pts, back_ptr);
1183  if (stream_index == -2)
1184  return back_ptr;
1185  av_assert0(stream_index == -1);
1186  return pts;
1187 }
1188 
1189 static int read_seek(AVFormatContext *s, int stream_index,
1190  int64_t pts, int flags)
1191 {
1192  NUTContext *nut = s->priv_data;
1193  AVStream *st = s->streams[stream_index];
1194  Syncpoint dummy = { .ts = pts * av_q2d(st->time_base) * AV_TIME_BASE };
1195  Syncpoint nopts_sp = { .ts = AV_NOPTS_VALUE, .back_ptr = AV_NOPTS_VALUE };
1196  Syncpoint *sp, *next_node[2] = { &nopts_sp, &nopts_sp };
1197  int64_t pos, pos2, ts;
1198  int i;
1199 
1200  if (nut->flags & NUT_PIPE) {
1201  return AVERROR(ENOSYS);
1202  }
1203 
1204  if (st->index_entries) {
1205  int index = av_index_search_timestamp(st, pts, flags);
1206  if (index < 0)
1207  index = av_index_search_timestamp(st, pts, flags ^ AVSEEK_FLAG_BACKWARD);
1208  if (index < 0)
1209  return -1;
1210 
1211  pos2 = st->index_entries[index].pos;
1212  ts = st->index_entries[index].timestamp;
1213  } else {
1214  av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pts_cmp,
1215  (void **) next_node);
1216  av_log(s, AV_LOG_DEBUG, "%"PRIu64"-%"PRIu64" %"PRId64"-%"PRId64"\n",
1217  next_node[0]->pos, next_node[1]->pos, next_node[0]->ts,
1218  next_node[1]->ts);
1219  pos = ff_gen_search(s, -1, dummy.ts, next_node[0]->pos,
1220  next_node[1]->pos, next_node[1]->pos,
1221  next_node[0]->ts, next_node[1]->ts,
1223 
1224  if (!(flags & AVSEEK_FLAG_BACKWARD)) {
1225  dummy.pos = pos + 16;
1226  next_node[1] = &nopts_sp;
1227  av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
1228  (void **) next_node);
1229  pos2 = ff_gen_search(s, -2, dummy.pos, next_node[0]->pos,
1230  next_node[1]->pos, next_node[1]->pos,
1231  next_node[0]->back_ptr, next_node[1]->back_ptr,
1232  flags, &ts, nut_read_timestamp);
1233  if (pos2 >= 0)
1234  pos = pos2;
1235  // FIXME dir but I think it does not matter
1236  }
1237  dummy.pos = pos;
1238  sp = av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
1239  NULL);
1240 
1241  av_assert0(sp);
1242  pos2 = sp->back_ptr - 15;
1243  }
1244  av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
1245  pos = find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
1246  avio_seek(s->pb, pos, SEEK_SET);
1247  nut->last_syncpoint_pos = pos;
1248  av_log(NULL, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
1249  if (pos2 > pos || pos2 + 15 < pos)
1250  av_log(NULL, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
1251  for (i = 0; i < s->nb_streams; i++)
1252  nut->stream[i].skip_until_key_frame = 1;
1253 
1254  nut->last_resync_pos = 0;
1255 
1256  return 0;
1257 }
1258 
1260  .name = "nut",
1261  .long_name = NULL_IF_CONFIG_SMALL("NUT"),
1262  .flags = AVFMT_SEEK_TO_PTS,
1263  .priv_data_size = sizeof(NUTContext),
1264  .read_probe = nut_probe,
1268  .read_seek = read_seek,
1269  .extensions = "nut",
1270  .codec_tag = ff_nut_codec_tags,
1271 };