nutdec.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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. #include <strings.h>
  23. #include "libavutil/avstring.h"
  24. #include "libavutil/bswap.h"
  25. #include "libavutil/dict.h"
  26. #include "libavutil/mathematics.h"
  27. #include "libavutil/tree.h"
  28. #include "avio_internal.h"
  29. #include "nut.h"
  30. #undef NDEBUG
  31. #include <assert.h>
  32. #if FF_API_MAX_STREAMS
  33. #define NUT_MAX_STREAMS MAX_STREAMS
  34. #else
  35. #define NUT_MAX_STREAMS 256 /* arbitrary sanity check value */
  36. #endif
  37. static int get_str(AVIOContext *bc, char *string, unsigned int maxlen){
  38. unsigned int len= ffio_read_varlen(bc);
  39. if(len && maxlen)
  40. avio_read(bc, string, FFMIN(len, maxlen));
  41. while(len > maxlen){
  42. avio_r8(bc);
  43. len--;
  44. }
  45. if(maxlen)
  46. string[FFMIN(len, maxlen-1)]= 0;
  47. if(maxlen == len)
  48. return -1;
  49. else
  50. return 0;
  51. }
  52. static int64_t get_s(AVIOContext *bc){
  53. int64_t v = ffio_read_varlen(bc) + 1;
  54. if (v&1) return -(v>>1);
  55. else return (v>>1);
  56. }
  57. static uint64_t get_fourcc(AVIOContext *bc){
  58. unsigned int len= ffio_read_varlen(bc);
  59. if (len==2) return avio_rl16(bc);
  60. else if(len==4) return avio_rl32(bc);
  61. else return -1;
  62. }
  63. #ifdef TRACE
  64. static inline uint64_t get_v_trace(AVIOContext *bc, char *file, char *func, int line){
  65. uint64_t v= ffio_read_varlen(bc);
  66. av_log(NULL, AV_LOG_DEBUG, "get_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
  67. return v;
  68. }
  69. static inline int64_t get_s_trace(AVIOContext *bc, char *file, char *func, int line){
  70. int64_t v= get_s(bc);
  71. av_log(NULL, AV_LOG_DEBUG, "get_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
  72. return v;
  73. }
  74. static inline uint64_t get_vb_trace(AVIOContext *bc, char *file, char *func, int line){
  75. uint64_t v= get_vb(bc);
  76. av_log(NULL, AV_LOG_DEBUG, "get_vb %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
  77. return v;
  78. }
  79. #define ffio_read_varlen(bc) get_v_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
  80. #define get_s(bc) get_s_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
  81. #define get_vb(bc) get_vb_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
  82. #endif
  83. static int get_packetheader(NUTContext *nut, AVIOContext *bc, int calculate_checksum, uint64_t startcode)
  84. {
  85. int64_t size;
  86. // start= avio_tell(bc) - 8;
  87. startcode= av_be2ne64(startcode);
  88. startcode= ff_crc04C11DB7_update(0, (uint8_t*)&startcode, 8);
  89. ffio_init_checksum(bc, ff_crc04C11DB7_update, startcode);
  90. size= ffio_read_varlen(bc);
  91. if(size > 4096)
  92. avio_rb32(bc);
  93. if(ffio_get_checksum(bc) && size > 4096)
  94. return -1;
  95. ffio_init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
  96. return size;
  97. }
  98. static uint64_t find_any_startcode(AVIOContext *bc, int64_t pos){
  99. uint64_t state=0;
  100. if(pos >= 0)
  101. avio_seek(bc, pos, SEEK_SET); //note, this may fail if the stream is not seekable, but that should not matter, as in this case we simply start where we currently are
  102. while(!url_feof(bc)){
  103. state= (state<<8) | avio_r8(bc);
  104. if((state>>56) != 'N')
  105. continue;
  106. switch(state){
  107. case MAIN_STARTCODE:
  108. case STREAM_STARTCODE:
  109. case SYNCPOINT_STARTCODE:
  110. case INFO_STARTCODE:
  111. case INDEX_STARTCODE:
  112. return state;
  113. }
  114. }
  115. return 0;
  116. }
  117. /**
  118. * Find the given startcode.
  119. * @param code the startcode
  120. * @param pos the start position of the search, or -1 if the current position
  121. * @return the position of the startcode or -1 if not found
  122. */
  123. static int64_t find_startcode(AVIOContext *bc, uint64_t code, int64_t pos){
  124. for(;;){
  125. uint64_t startcode= find_any_startcode(bc, pos);
  126. if(startcode == code)
  127. return avio_tell(bc) - 8;
  128. else if(startcode == 0)
  129. return -1;
  130. pos=-1;
  131. }
  132. }
  133. static int nut_probe(AVProbeData *p){
  134. int i;
  135. uint64_t code= 0;
  136. for (i = 0; i < p->buf_size; i++) {
  137. code = (code << 8) | p->buf[i];
  138. if (code == MAIN_STARTCODE)
  139. return AVPROBE_SCORE_MAX;
  140. }
  141. return 0;
  142. }
  143. #define GET_V(dst, check) \
  144. tmp= ffio_read_varlen(bc);\
  145. if(!(check)){\
  146. av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp);\
  147. return -1;\
  148. }\
  149. dst= tmp;
  150. static int skip_reserved(AVIOContext *bc, int64_t pos){
  151. pos -= avio_tell(bc);
  152. if(pos<0){
  153. avio_seek(bc, pos, SEEK_CUR);
  154. return -1;
  155. }else{
  156. while(pos--)
  157. avio_r8(bc);
  158. return 0;
  159. }
  160. }
  161. static int decode_main_header(NUTContext *nut){
  162. AVFormatContext *s= nut->avf;
  163. AVIOContext *bc = s->pb;
  164. uint64_t tmp, end;
  165. unsigned int stream_count;
  166. int i, j, tmp_stream, tmp_mul, tmp_pts, tmp_size, count, tmp_res, tmp_head_idx;
  167. end= get_packetheader(nut, bc, 1, MAIN_STARTCODE);
  168. end += avio_tell(bc);
  169. GET_V(tmp , tmp >=2 && tmp <= 3)
  170. GET_V(stream_count , tmp > 0 && tmp <= NUT_MAX_STREAMS)
  171. nut->max_distance = ffio_read_varlen(bc);
  172. if(nut->max_distance > 65536){
  173. av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);
  174. nut->max_distance= 65536;
  175. }
  176. GET_V(nut->time_base_count, tmp>0 && tmp<INT_MAX / sizeof(AVRational))
  177. nut->time_base= av_malloc(nut->time_base_count * sizeof(AVRational));
  178. for(i=0; i<nut->time_base_count; i++){
  179. GET_V(nut->time_base[i].num, tmp>0 && tmp<(1ULL<<31))
  180. GET_V(nut->time_base[i].den, tmp>0 && tmp<(1ULL<<31))
  181. if(av_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1){
  182. av_log(s, AV_LOG_ERROR, "time base invalid\n");
  183. return AVERROR_INVALIDDATA;
  184. }
  185. }
  186. tmp_pts=0;
  187. tmp_mul=1;
  188. tmp_stream=0;
  189. tmp_head_idx= 0;
  190. for(i=0; i<256;){
  191. int tmp_flags = ffio_read_varlen(bc);
  192. int tmp_fields= ffio_read_varlen(bc);
  193. if(tmp_fields>0) tmp_pts = get_s(bc);
  194. if(tmp_fields>1) tmp_mul = ffio_read_varlen(bc);
  195. if(tmp_fields>2) tmp_stream= ffio_read_varlen(bc);
  196. if(tmp_fields>3) tmp_size = ffio_read_varlen(bc);
  197. else tmp_size = 0;
  198. if(tmp_fields>4) tmp_res = ffio_read_varlen(bc);
  199. else tmp_res = 0;
  200. if(tmp_fields>5) count = ffio_read_varlen(bc);
  201. else count = tmp_mul - tmp_size;
  202. if(tmp_fields>6) get_s(bc);
  203. if(tmp_fields>7) tmp_head_idx= ffio_read_varlen(bc);
  204. while(tmp_fields-- > 8)
  205. ffio_read_varlen(bc);
  206. if(count == 0 || i+count > 256){
  207. av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
  208. return AVERROR_INVALIDDATA;
  209. }
  210. if(tmp_stream >= stream_count){
  211. av_log(s, AV_LOG_ERROR, "illegal stream number\n");
  212. return AVERROR_INVALIDDATA;
  213. }
  214. for(j=0; j<count; j++,i++){
  215. if (i == 'N') {
  216. nut->frame_code[i].flags= FLAG_INVALID;
  217. j--;
  218. continue;
  219. }
  220. nut->frame_code[i].flags = tmp_flags ;
  221. nut->frame_code[i].pts_delta = tmp_pts ;
  222. nut->frame_code[i].stream_id = tmp_stream;
  223. nut->frame_code[i].size_mul = tmp_mul ;
  224. nut->frame_code[i].size_lsb = tmp_size+j;
  225. nut->frame_code[i].reserved_count = tmp_res ;
  226. nut->frame_code[i].header_idx = tmp_head_idx;
  227. }
  228. }
  229. assert(nut->frame_code['N'].flags == FLAG_INVALID);
  230. if(end > avio_tell(bc) + 4){
  231. int rem= 1024;
  232. GET_V(nut->header_count, tmp<128U)
  233. nut->header_count++;
  234. for(i=1; i<nut->header_count; i++){
  235. GET_V(nut->header_len[i], tmp>0 && tmp<256);
  236. rem -= nut->header_len[i];
  237. if(rem < 0){
  238. av_log(s, AV_LOG_ERROR, "invalid elision header\n");
  239. return AVERROR_INVALIDDATA;
  240. }
  241. nut->header[i]= av_malloc(nut->header_len[i]);
  242. avio_read(bc, nut->header[i], nut->header_len[i]);
  243. }
  244. assert(nut->header_len[0]==0);
  245. }
  246. if(skip_reserved(bc, end) || ffio_get_checksum(bc)){
  247. av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
  248. return AVERROR_INVALIDDATA;
  249. }
  250. nut->stream = av_mallocz(sizeof(StreamContext)*stream_count);
  251. for(i=0; i<stream_count; i++){
  252. av_new_stream(s, i);
  253. }
  254. return 0;
  255. }
  256. static int decode_stream_header(NUTContext *nut){
  257. AVFormatContext *s= nut->avf;
  258. AVIOContext *bc = s->pb;
  259. StreamContext *stc;
  260. int class, stream_id;
  261. uint64_t tmp, end;
  262. AVStream *st;
  263. end= get_packetheader(nut, bc, 1, STREAM_STARTCODE);
  264. end += avio_tell(bc);
  265. GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);
  266. stc= &nut->stream[stream_id];
  267. st = s->streams[stream_id];
  268. if (!st)
  269. return AVERROR(ENOMEM);
  270. class = ffio_read_varlen(bc);
  271. tmp = get_fourcc(bc);
  272. st->codec->codec_tag= tmp;
  273. switch(class)
  274. {
  275. case 0:
  276. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  277. st->codec->codec_id = av_codec_get_id(
  278. (const AVCodecTag * const []) { ff_codec_bmp_tags, ff_nut_video_tags, 0 },
  279. tmp);
  280. break;
  281. case 1:
  282. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  283. st->codec->codec_id = ff_codec_get_id(ff_codec_wav_tags, tmp);
  284. break;
  285. case 2:
  286. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  287. st->codec->codec_id = ff_codec_get_id(ff_nut_subtitle_tags, tmp);
  288. break;
  289. case 3:
  290. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  291. break;
  292. default:
  293. av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
  294. return -1;
  295. }
  296. if(class<3 && st->codec->codec_id == CODEC_ID_NONE)
  297. av_log(s, AV_LOG_ERROR, "Unknown codec tag '0x%04x' for stream number %d\n",
  298. (unsigned int)tmp, stream_id);
  299. GET_V(stc->time_base_id , tmp < nut->time_base_count);
  300. GET_V(stc->msb_pts_shift , tmp < 16);
  301. stc->max_pts_distance= ffio_read_varlen(bc);
  302. GET_V(stc->decode_delay , tmp < 1000); //sanity limit, raise this if Moore's law is true
  303. st->codec->has_b_frames= stc->decode_delay;
  304. ffio_read_varlen(bc); //stream flags
  305. GET_V(st->codec->extradata_size, tmp < (1<<30));
  306. if(st->codec->extradata_size){
  307. st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  308. avio_read(bc, st->codec->extradata, st->codec->extradata_size);
  309. }
  310. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
  311. GET_V(st->codec->width , tmp > 0)
  312. GET_V(st->codec->height, tmp > 0)
  313. st->sample_aspect_ratio.num= ffio_read_varlen(bc);
  314. st->sample_aspect_ratio.den= ffio_read_varlen(bc);
  315. if((!st->sample_aspect_ratio.num) != (!st->sample_aspect_ratio.den)){
  316. av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n", st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
  317. return -1;
  318. }
  319. ffio_read_varlen(bc); /* csp type */
  320. }else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO){
  321. GET_V(st->codec->sample_rate , tmp > 0)
  322. ffio_read_varlen(bc); // samplerate_den
  323. GET_V(st->codec->channels, tmp > 0)
  324. }
  325. if(skip_reserved(bc, end) || ffio_get_checksum(bc)){
  326. av_log(s, AV_LOG_ERROR, "stream header %d checksum mismatch\n", stream_id);
  327. return -1;
  328. }
  329. stc->time_base= &nut->time_base[stc->time_base_id];
  330. av_set_pts_info(s->streams[stream_id], 63, stc->time_base->num, stc->time_base->den);
  331. return 0;
  332. }
  333. static void set_disposition_bits(AVFormatContext* avf, char* value, int stream_id){
  334. int flag = 0, i;
  335. for (i=0; ff_nut_dispositions[i].flag; ++i) {
  336. if (!strcmp(ff_nut_dispositions[i].str, value))
  337. flag = ff_nut_dispositions[i].flag;
  338. }
  339. if (!flag)
  340. av_log(avf, AV_LOG_INFO, "unknown disposition type '%s'\n", value);
  341. for (i = 0; i < avf->nb_streams; ++i)
  342. if (stream_id == i || stream_id == -1)
  343. avf->streams[i]->disposition |= flag;
  344. }
  345. static int decode_info_header(NUTContext *nut){
  346. AVFormatContext *s= nut->avf;
  347. AVIOContext *bc = s->pb;
  348. uint64_t tmp, chapter_start, chapter_len;
  349. unsigned int stream_id_plus1, count;
  350. int chapter_id, i;
  351. int64_t value, end;
  352. char name[256], str_value[1024], type_str[256];
  353. const char *type;
  354. AVChapter *chapter= NULL;
  355. AVStream *st= NULL;
  356. AVDictionary **metadata = NULL;
  357. end= get_packetheader(nut, bc, 1, INFO_STARTCODE);
  358. end += avio_tell(bc);
  359. GET_V(stream_id_plus1, tmp <= s->nb_streams)
  360. chapter_id = get_s(bc);
  361. chapter_start= ffio_read_varlen(bc);
  362. chapter_len = ffio_read_varlen(bc);
  363. count = ffio_read_varlen(bc);
  364. if(chapter_id && !stream_id_plus1){
  365. int64_t start= chapter_start / nut->time_base_count;
  366. chapter= ff_new_chapter(s, chapter_id,
  367. nut->time_base[chapter_start % nut->time_base_count],
  368. start, start + chapter_len, NULL);
  369. metadata = &chapter->metadata;
  370. } else if(stream_id_plus1) {
  371. st= s->streams[stream_id_plus1 - 1];
  372. metadata = &st->metadata;
  373. } else
  374. metadata = &s->metadata;
  375. for(i=0; i<count; i++){
  376. get_str(bc, name, sizeof(name));
  377. value= get_s(bc);
  378. if(value == -1){
  379. type= "UTF-8";
  380. get_str(bc, str_value, sizeof(str_value));
  381. }else if(value == -2){
  382. get_str(bc, type_str, sizeof(type_str));
  383. type= type_str;
  384. get_str(bc, str_value, sizeof(str_value));
  385. }else if(value == -3){
  386. type= "s";
  387. value= get_s(bc);
  388. }else if(value == -4){
  389. type= "t";
  390. value= ffio_read_varlen(bc);
  391. }else if(value < -4){
  392. type= "r";
  393. get_s(bc);
  394. }else{
  395. type= "v";
  396. }
  397. if (stream_id_plus1 > s->nb_streams) {
  398. av_log(s, AV_LOG_ERROR, "invalid stream id for info packet\n");
  399. continue;
  400. }
  401. if(!strcmp(type, "UTF-8")){
  402. if(chapter_id==0 && !strcmp(name, "Disposition")) {
  403. set_disposition_bits(s, str_value, stream_id_plus1 - 1);
  404. continue;
  405. }
  406. if(metadata && strcasecmp(name,"Uses")
  407. && strcasecmp(name,"Depends") && strcasecmp(name,"Replaces"))
  408. av_dict_set(metadata, name, str_value, 0);
  409. }
  410. }
  411. if(skip_reserved(bc, end) || ffio_get_checksum(bc)){
  412. av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
  413. return -1;
  414. }
  415. return 0;
  416. }
  417. static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr){
  418. AVFormatContext *s= nut->avf;
  419. AVIOContext *bc = s->pb;
  420. int64_t end, tmp;
  421. nut->last_syncpoint_pos= avio_tell(bc)-8;
  422. end= get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
  423. end += avio_tell(bc);
  424. tmp= ffio_read_varlen(bc);
  425. *back_ptr= nut->last_syncpoint_pos - 16*ffio_read_varlen(bc);
  426. if(*back_ptr < 0)
  427. return -1;
  428. ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count], tmp / nut->time_base_count);
  429. if(skip_reserved(bc, end) || ffio_get_checksum(bc)){
  430. av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
  431. return -1;
  432. }
  433. *ts= tmp / s->nb_streams * av_q2d(nut->time_base[tmp % s->nb_streams])*AV_TIME_BASE;
  434. ff_nut_add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts);
  435. return 0;
  436. }
  437. static int find_and_decode_index(NUTContext *nut){
  438. AVFormatContext *s= nut->avf;
  439. AVIOContext *bc = s->pb;
  440. uint64_t tmp, end;
  441. int i, j, syncpoint_count;
  442. int64_t filesize= avio_size(bc);
  443. int64_t *syncpoints;
  444. int8_t *has_keyframe;
  445. int ret= -1;
  446. avio_seek(bc, filesize-12, SEEK_SET);
  447. avio_seek(bc, filesize-avio_rb64(bc), SEEK_SET);
  448. if(avio_rb64(bc) != INDEX_STARTCODE){
  449. av_log(s, AV_LOG_ERROR, "no index at the end\n");
  450. return -1;
  451. }
  452. end= get_packetheader(nut, bc, 1, INDEX_STARTCODE);
  453. end += avio_tell(bc);
  454. ffio_read_varlen(bc); //max_pts
  455. GET_V(syncpoint_count, tmp < INT_MAX/8 && tmp > 0)
  456. syncpoints= av_malloc(sizeof(int64_t)*syncpoint_count);
  457. has_keyframe= av_malloc(sizeof(int8_t)*(syncpoint_count+1));
  458. for(i=0; i<syncpoint_count; i++){
  459. syncpoints[i] = ffio_read_varlen(bc);
  460. if(syncpoints[i] <= 0)
  461. goto fail;
  462. if(i)
  463. syncpoints[i] += syncpoints[i-1];
  464. }
  465. for(i=0; i<s->nb_streams; i++){
  466. int64_t last_pts= -1;
  467. for(j=0; j<syncpoint_count;){
  468. uint64_t x= ffio_read_varlen(bc);
  469. int type= x&1;
  470. int n= j;
  471. x>>=1;
  472. if(type){
  473. int flag= x&1;
  474. x>>=1;
  475. if(n+x >= syncpoint_count + 1){
  476. av_log(s, AV_LOG_ERROR, "index overflow A\n");
  477. goto fail;
  478. }
  479. while(x--)
  480. has_keyframe[n++]= flag;
  481. has_keyframe[n++]= !flag;
  482. }else{
  483. while(x != 1){
  484. if(n>=syncpoint_count + 1){
  485. av_log(s, AV_LOG_ERROR, "index overflow B\n");
  486. goto fail;
  487. }
  488. has_keyframe[n++]= x&1;
  489. x>>=1;
  490. }
  491. }
  492. if(has_keyframe[0]){
  493. av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");
  494. goto fail;
  495. }
  496. assert(n<=syncpoint_count+1);
  497. for(; j<n && j<syncpoint_count; j++){
  498. if(has_keyframe[j]){
  499. uint64_t B, A= ffio_read_varlen(bc);
  500. if(!A){
  501. A= ffio_read_varlen(bc);
  502. B= ffio_read_varlen(bc);
  503. //eor_pts[j][i] = last_pts + A + B
  504. }else
  505. B= 0;
  506. av_add_index_entry(
  507. s->streams[i],
  508. 16*syncpoints[j-1],
  509. last_pts + A,
  510. 0,
  511. 0,
  512. AVINDEX_KEYFRAME);
  513. last_pts += A + B;
  514. }
  515. }
  516. }
  517. }
  518. if(skip_reserved(bc, end) || ffio_get_checksum(bc)){
  519. av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
  520. goto fail;
  521. }
  522. ret= 0;
  523. fail:
  524. av_free(syncpoints);
  525. av_free(has_keyframe);
  526. return ret;
  527. }
  528. static int nut_read_header(AVFormatContext *s, AVFormatParameters *ap)
  529. {
  530. NUTContext *nut = s->priv_data;
  531. AVIOContext *bc = s->pb;
  532. int64_t pos;
  533. int initialized_stream_count;
  534. nut->avf= s;
  535. /* main header */
  536. pos=0;
  537. do{
  538. pos= find_startcode(bc, MAIN_STARTCODE, pos)+1;
  539. if (pos<0+1){
  540. av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
  541. return AVERROR_INVALIDDATA;
  542. }
  543. }while(decode_main_header(nut) < 0);
  544. /* stream headers */
  545. pos=0;
  546. for(initialized_stream_count=0; initialized_stream_count < s->nb_streams;){
  547. pos= find_startcode(bc, STREAM_STARTCODE, pos)+1;
  548. if (pos<0+1){
  549. av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
  550. return AVERROR_INVALIDDATA;
  551. }
  552. if(decode_stream_header(nut) >= 0)
  553. initialized_stream_count++;
  554. }
  555. /* info headers */
  556. pos=0;
  557. for(;;){
  558. uint64_t startcode= find_any_startcode(bc, pos);
  559. pos= avio_tell(bc);
  560. if(startcode==0){
  561. av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
  562. return AVERROR_INVALIDDATA;
  563. }else if(startcode == SYNCPOINT_STARTCODE){
  564. nut->next_startcode= startcode;
  565. break;
  566. }else if(startcode != INFO_STARTCODE){
  567. continue;
  568. }
  569. decode_info_header(nut);
  570. }
  571. s->data_offset= pos-8;
  572. if(bc->seekable){
  573. int64_t orig_pos= avio_tell(bc);
  574. find_and_decode_index(nut);
  575. avio_seek(bc, orig_pos, SEEK_SET);
  576. }
  577. assert(nut->next_startcode == SYNCPOINT_STARTCODE);
  578. ff_metadata_conv_ctx(s, NULL, ff_nut_metadata_conv);
  579. return 0;
  580. }
  581. static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id, uint8_t *header_idx, int frame_code){
  582. AVFormatContext *s= nut->avf;
  583. AVIOContext *bc = s->pb;
  584. StreamContext *stc;
  585. int size, flags, size_mul, pts_delta, i, reserved_count;
  586. uint64_t tmp;
  587. if(avio_tell(bc) > nut->last_syncpoint_pos + nut->max_distance){
  588. av_log(s, AV_LOG_ERROR, "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n", avio_tell(bc), nut->last_syncpoint_pos, nut->max_distance);
  589. return AVERROR_INVALIDDATA;
  590. }
  591. flags = nut->frame_code[frame_code].flags;
  592. size_mul = nut->frame_code[frame_code].size_mul;
  593. size = nut->frame_code[frame_code].size_lsb;
  594. *stream_id = nut->frame_code[frame_code].stream_id;
  595. pts_delta = nut->frame_code[frame_code].pts_delta;
  596. reserved_count = nut->frame_code[frame_code].reserved_count;
  597. *header_idx = nut->frame_code[frame_code].header_idx;
  598. if(flags & FLAG_INVALID)
  599. return AVERROR_INVALIDDATA;
  600. if(flags & FLAG_CODED)
  601. flags ^= ffio_read_varlen(bc);
  602. if(flags & FLAG_STREAM_ID){
  603. GET_V(*stream_id, tmp < s->nb_streams)
  604. }
  605. stc= &nut->stream[*stream_id];
  606. if(flags&FLAG_CODED_PTS){
  607. int coded_pts= ffio_read_varlen(bc);
  608. //FIXME check last_pts validity?
  609. if(coded_pts < (1<<stc->msb_pts_shift)){
  610. *pts=ff_lsb2full(stc, coded_pts);
  611. }else
  612. *pts=coded_pts - (1<<stc->msb_pts_shift);
  613. }else
  614. *pts= stc->last_pts + pts_delta;
  615. if(flags&FLAG_SIZE_MSB){
  616. size += size_mul*ffio_read_varlen(bc);
  617. }
  618. if(flags&FLAG_MATCH_TIME)
  619. get_s(bc);
  620. if(flags&FLAG_HEADER_IDX)
  621. *header_idx= ffio_read_varlen(bc);
  622. if(flags&FLAG_RESERVED)
  623. reserved_count= ffio_read_varlen(bc);
  624. for(i=0; i<reserved_count; i++)
  625. ffio_read_varlen(bc);
  626. if(*header_idx >= (unsigned)nut->header_count){
  627. av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
  628. return AVERROR_INVALIDDATA;
  629. }
  630. if(size > 4096)
  631. *header_idx=0;
  632. size -= nut->header_len[*header_idx];
  633. if(flags&FLAG_CHECKSUM){
  634. avio_rb32(bc); //FIXME check this
  635. }else if(size > 2*nut->max_distance || FFABS(stc->last_pts - *pts) > stc->max_pts_distance){
  636. av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
  637. return AVERROR_INVALIDDATA;
  638. }
  639. stc->last_pts= *pts;
  640. stc->last_flags= flags;
  641. return size;
  642. }
  643. static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code){
  644. AVFormatContext *s= nut->avf;
  645. AVIOContext *bc = s->pb;
  646. int size, stream_id, discard;
  647. int64_t pts, last_IP_pts;
  648. StreamContext *stc;
  649. uint8_t header_idx;
  650. size= decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
  651. if(size < 0)
  652. return size;
  653. stc= &nut->stream[stream_id];
  654. if (stc->last_flags & FLAG_KEY)
  655. stc->skip_until_key_frame=0;
  656. discard= s->streams[ stream_id ]->discard;
  657. last_IP_pts= s->streams[ stream_id ]->last_IP_pts;
  658. if( (discard >= AVDISCARD_NONKEY && !(stc->last_flags & FLAG_KEY))
  659. ||(discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE && last_IP_pts > pts)
  660. || discard >= AVDISCARD_ALL
  661. || stc->skip_until_key_frame){
  662. avio_skip(bc, size);
  663. return 1;
  664. }
  665. av_new_packet(pkt, size + nut->header_len[header_idx]);
  666. memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
  667. pkt->pos= avio_tell(bc); //FIXME
  668. avio_read(bc, pkt->data + nut->header_len[header_idx], size);
  669. pkt->stream_index = stream_id;
  670. if (stc->last_flags & FLAG_KEY)
  671. pkt->flags |= AV_PKT_FLAG_KEY;
  672. pkt->pts = pts;
  673. return 0;
  674. }
  675. static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
  676. {
  677. NUTContext *nut = s->priv_data;
  678. AVIOContext *bc = s->pb;
  679. int i, frame_code=0, ret, skip;
  680. int64_t ts, back_ptr;
  681. for(;;){
  682. int64_t pos= avio_tell(bc);
  683. uint64_t tmp= nut->next_startcode;
  684. nut->next_startcode=0;
  685. if(tmp){
  686. pos-=8;
  687. }else{
  688. frame_code = avio_r8(bc);
  689. if(url_feof(bc))
  690. return -1;
  691. if(frame_code == 'N'){
  692. tmp= frame_code;
  693. for(i=1; i<8; i++)
  694. tmp = (tmp<<8) + avio_r8(bc);
  695. }
  696. }
  697. switch(tmp){
  698. case MAIN_STARTCODE:
  699. case STREAM_STARTCODE:
  700. case INDEX_STARTCODE:
  701. skip= get_packetheader(nut, bc, 0, tmp);
  702. avio_skip(bc, skip);
  703. break;
  704. case INFO_STARTCODE:
  705. if(decode_info_header(nut)<0)
  706. goto resync;
  707. break;
  708. case SYNCPOINT_STARTCODE:
  709. if(decode_syncpoint(nut, &ts, &back_ptr)<0)
  710. goto resync;
  711. frame_code = avio_r8(bc);
  712. case 0:
  713. ret= decode_frame(nut, pkt, frame_code);
  714. if(ret==0)
  715. return 0;
  716. else if(ret==1) //ok but discard packet
  717. break;
  718. default:
  719. resync:
  720. av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
  721. tmp= find_any_startcode(bc, nut->last_syncpoint_pos+1);
  722. if(tmp==0)
  723. return AVERROR_INVALIDDATA;
  724. av_log(s, AV_LOG_DEBUG, "sync\n");
  725. nut->next_startcode= tmp;
  726. }
  727. }
  728. }
  729. static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index, int64_t *pos_arg, int64_t pos_limit){
  730. NUTContext *nut = s->priv_data;
  731. AVIOContext *bc = s->pb;
  732. int64_t pos, pts, back_ptr;
  733. av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n", stream_index, *pos_arg, pos_limit);
  734. pos= *pos_arg;
  735. do{
  736. pos= find_startcode(bc, SYNCPOINT_STARTCODE, pos)+1;
  737. if(pos < 1){
  738. assert(nut->next_startcode == 0);
  739. av_log(s, AV_LOG_ERROR, "read_timestamp failed.\n");
  740. return AV_NOPTS_VALUE;
  741. }
  742. }while(decode_syncpoint(nut, &pts, &back_ptr) < 0);
  743. *pos_arg = pos-1;
  744. assert(nut->last_syncpoint_pos == *pos_arg);
  745. av_log(s, AV_LOG_DEBUG, "return %"PRId64" %"PRId64"\n", pts,back_ptr );
  746. if (stream_index == -1) return pts;
  747. else if(stream_index == -2) return back_ptr;
  748. assert(0);
  749. }
  750. static int read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags){
  751. NUTContext *nut = s->priv_data;
  752. AVStream *st= s->streams[stream_index];
  753. Syncpoint dummy={.ts= pts*av_q2d(st->time_base)*AV_TIME_BASE};
  754. Syncpoint nopts_sp= {.ts= AV_NOPTS_VALUE, .back_ptr= AV_NOPTS_VALUE};
  755. Syncpoint *sp, *next_node[2]= {&nopts_sp, &nopts_sp};
  756. int64_t pos, pos2, ts;
  757. int i;
  758. if(st->index_entries){
  759. int index= av_index_search_timestamp(st, pts, flags);
  760. if(index<0)
  761. return -1;
  762. pos2= st->index_entries[index].pos;
  763. ts = st->index_entries[index].timestamp;
  764. }else{
  765. av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pts_cmp,
  766. (void **) next_node);
  767. av_log(s, AV_LOG_DEBUG, "%"PRIu64"-%"PRIu64" %"PRId64"-%"PRId64"\n", next_node[0]->pos, next_node[1]->pos,
  768. next_node[0]->ts , next_node[1]->ts);
  769. pos= av_gen_search(s, -1, dummy.ts, next_node[0]->pos, next_node[1]->pos, next_node[1]->pos,
  770. next_node[0]->ts , next_node[1]->ts, AVSEEK_FLAG_BACKWARD, &ts, nut_read_timestamp);
  771. if(!(flags & AVSEEK_FLAG_BACKWARD)){
  772. dummy.pos= pos+16;
  773. next_node[1]= &nopts_sp;
  774. av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
  775. (void **) next_node);
  776. pos2= av_gen_search(s, -2, dummy.pos, next_node[0]->pos , next_node[1]->pos, next_node[1]->pos,
  777. next_node[0]->back_ptr, next_node[1]->back_ptr, flags, &ts, nut_read_timestamp);
  778. if(pos2>=0)
  779. pos= pos2;
  780. //FIXME dir but I think it does not matter
  781. }
  782. dummy.pos= pos;
  783. sp= av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
  784. NULL);
  785. assert(sp);
  786. pos2= sp->back_ptr - 15;
  787. }
  788. av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
  789. pos= find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
  790. avio_seek(s->pb, pos, SEEK_SET);
  791. av_log(NULL, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
  792. if(pos2 > pos || pos2 + 15 < pos){
  793. av_log(NULL, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
  794. }
  795. for(i=0; i<s->nb_streams; i++)
  796. nut->stream[i].skip_until_key_frame=1;
  797. return 0;
  798. }
  799. static int nut_read_close(AVFormatContext *s)
  800. {
  801. NUTContext *nut = s->priv_data;
  802. int i;
  803. av_freep(&nut->time_base);
  804. av_freep(&nut->stream);
  805. ff_nut_free_sp(nut);
  806. for(i = 1; i < nut->header_count; i++)
  807. av_freep(&nut->header[i]);
  808. return 0;
  809. }
  810. #if CONFIG_NUT_DEMUXER
  811. AVInputFormat ff_nut_demuxer = {
  812. .name = "nut",
  813. .long_name = NULL_IF_CONFIG_SMALL("NUT format"),
  814. .priv_data_size = sizeof(NUTContext),
  815. .read_probe = nut_probe,
  816. .read_header = nut_read_header,
  817. .read_packet = nut_read_packet,
  818. .read_close = nut_read_close,
  819. .read_seek = read_seek,
  820. .extensions = "nut",
  821. .codec_tag = (const AVCodecTag * const []) { ff_codec_bmp_tags, ff_nut_video_tags, ff_codec_wav_tags, ff_nut_subtitle_tags, 0 },
  822. };
  823. #endif