nutdec.c 30 KB

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