You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

809 lines
26KB

  1. /*
  2. * NSV demuxer
  3. * Copyright (c) 2004 The Libav Project
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/attributes.h"
  22. #include "libavutil/mathematics.h"
  23. #include "avformat.h"
  24. #include "internal.h"
  25. #include "riff.h"
  26. #include "libavutil/dict.h"
  27. //#define DEBUG_DUMP_INDEX // XXX dumbdriving-271.nsv breaks with it commented!!
  28. #define CHECK_SUBSEQUENT_NSVS
  29. //#define DISABLE_AUDIO
  30. /* max bytes to crawl for trying to resync
  31. * stupid streaming servers don't start at chunk boundaries...
  32. */
  33. #define NSV_MAX_RESYNC (500*1024)
  34. #define NSV_MAX_RESYNC_TRIES 300
  35. /*
  36. * First version by Francois Revol - revol@free.fr
  37. * References:
  38. * (1) http://www.multimedia.cx/nsv-format.txt
  39. * seems someone came to the same conclusions as me, and updated it:
  40. * (2) http://www.stud.ktu.lt/~vitslav/nsv/nsv-format.txt
  41. * http://www.stud.ktu.lt/~vitslav/nsv/
  42. * official docs
  43. * (3) http://ultravox.aol.com/NSVFormat.rtf
  44. * Sample files:
  45. * (S1) http://www.nullsoft.com/nsv/samples/
  46. * http://www.nullsoft.com/nsv/samples/faster.nsv
  47. * http://streamripper.sourceforge.net/openbb/read.php?TID=492&page=4
  48. */
  49. /*
  50. * notes on the header (Francois Revol):
  51. *
  52. * It is followed by strings, then a table, but nothing tells
  53. * where the table begins according to (1). After checking faster.nsv,
  54. * I believe NVSf[16-19] gives the size of the strings data
  55. * (that is the offset of the data table after the header).
  56. * After checking all samples from (S1) all confirms this.
  57. *
  58. * Then, about NSVf[12-15], faster.nsf has 179700. When veiwing it in VLC,
  59. * I noticed there was about 1 NVSs chunk/s, so I ran
  60. * strings faster.nsv | grep NSVs | wc -l
  61. * which gave me 180. That leads me to think that NSVf[12-15] might be the
  62. * file length in milliseconds.
  63. * Let's try that:
  64. * for f in *.nsv; do HTIME="$(od -t x4 "$f" | head -1 | sed 's/.* //')"; echo "'$f' $((0x$HTIME))s = $((0x$HTIME/1000/60)):$((0x$HTIME/1000%60))"; done
  65. * except for nstrailer (which doesn't have an NSVf header), it repports correct time.
  66. *
  67. * nsvtrailer.nsv (S1) does not have any NSVf header, only NSVs chunks,
  68. * so the header seems to not be mandatory. (for streaming).
  69. *
  70. * index slice duration check (excepts nsvtrailer.nsv):
  71. * for f in [^n]*.nsv; do
  72. * DUR="$(avconv -i "$f" 2> /dev/null | grep 'NSVf duration' | cut -d ' ' -f 4)"
  73. * IC="$(avconv -i "$f" 2> /dev/null | grep 'INDEX ENTRIES' | cut -d ' ' -f 2)"
  74. * echo "duration $DUR, slite time $(($DUR/$IC))"
  75. * done
  76. */
  77. /*
  78. * TODO:
  79. * - handle timestamps !!!
  80. * - use index
  81. * - mime-type in probe()
  82. * - seek
  83. */
  84. #if 0
  85. struct NSVf_header {
  86. uint32_t chunk_tag; /* 'NSVf' */
  87. uint32_t chunk_size;
  88. uint32_t file_size; /* max 4GB ??? no one learns anything it seems :^) */
  89. uint32_t file_length; //unknown1; /* what about MSB of file_size ? */
  90. uint32_t info_strings_size; /* size of the info strings */ //unknown2;
  91. uint32_t table_entries;
  92. uint32_t table_entries_used; /* the left ones should be -1 */
  93. };
  94. struct NSVs_header {
  95. uint32_t chunk_tag; /* 'NSVs' */
  96. uint32_t v4cc; /* or 'NONE' */
  97. uint32_t a4cc; /* or 'NONE' */
  98. uint16_t vwidth; /* assert(vwidth%16==0) */
  99. uint16_t vheight; /* assert(vheight%16==0) */
  100. uint8_t framerate; /* value = (framerate&0x80)?frtable[frameratex0x7f]:framerate */
  101. uint16_t unknown;
  102. };
  103. struct nsv_avchunk_header {
  104. uint8_t vchunk_size_lsb;
  105. uint16_t vchunk_size_msb; /* value = (vchunk_size_msb << 4) | (vchunk_size_lsb >> 4) */
  106. uint16_t achunk_size;
  107. };
  108. struct nsv_pcm_header {
  109. uint8_t bits_per_sample;
  110. uint8_t channel_count;
  111. uint16_t sample_rate;
  112. };
  113. #endif
  114. /* variation from avi.h */
  115. /*typedef struct CodecTag {
  116. int id;
  117. unsigned int tag;
  118. } CodecTag;*/
  119. /* tags */
  120. #define T_NSVF MKTAG('N', 'S', 'V', 'f') /* file header */
  121. #define T_NSVS MKTAG('N', 'S', 'V', 's') /* chunk header */
  122. #define T_TOC2 MKTAG('T', 'O', 'C', '2') /* extra index marker */
  123. #define T_NONE MKTAG('N', 'O', 'N', 'E') /* null a/v 4CC */
  124. #define T_SUBT MKTAG('S', 'U', 'B', 'T') /* subtitle aux data */
  125. #define T_ASYN MKTAG('A', 'S', 'Y', 'N') /* async a/v aux marker */
  126. #define T_KEYF MKTAG('K', 'E', 'Y', 'F') /* video keyframe aux marker (addition) */
  127. #define TB_NSVF MKBETAG('N', 'S', 'V', 'f')
  128. #define TB_NSVS MKBETAG('N', 'S', 'V', 's')
  129. /* hardcoded stream indexes */
  130. #define NSV_ST_VIDEO 0
  131. #define NSV_ST_AUDIO 1
  132. #define NSV_ST_SUBT 2
  133. enum NSVStatus {
  134. NSV_UNSYNC,
  135. NSV_FOUND_NSVF,
  136. NSV_HAS_READ_NSVF,
  137. NSV_FOUND_NSVS,
  138. NSV_HAS_READ_NSVS,
  139. NSV_FOUND_BEEF,
  140. NSV_GOT_VIDEO,
  141. NSV_GOT_AUDIO,
  142. };
  143. typedef struct NSVStream {
  144. int frame_offset; /* current frame (video) or byte (audio) counter
  145. (used to compute the pts) */
  146. int scale;
  147. int rate;
  148. int sample_size; /* audio only data */
  149. int start;
  150. int new_frame_offset; /* temporary storage (used during seek) */
  151. int cum_len; /* temporary storage (used during seek) */
  152. } NSVStream;
  153. typedef struct {
  154. int base_offset;
  155. int NSVf_end;
  156. uint32_t *nsvs_file_offset;
  157. int index_entries;
  158. enum NSVStatus state;
  159. AVPacket ahead[2]; /* [v, a] if .data is !NULL there is something */
  160. /* cached */
  161. int64_t duration;
  162. uint32_t vtag, atag;
  163. uint16_t vwidth, vheight;
  164. int16_t avsync;
  165. AVRational framerate;
  166. uint32_t *nsvs_timestamps;
  167. //DVDemuxContext* dv_demux;
  168. } NSVContext;
  169. static const AVCodecTag nsv_codec_video_tags[] = {
  170. { CODEC_ID_VP3, MKTAG('V', 'P', '3', ' ') },
  171. { CODEC_ID_VP3, MKTAG('V', 'P', '3', '0') },
  172. { CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') },
  173. { CODEC_ID_VP5, MKTAG('V', 'P', '5', ' ') },
  174. { CODEC_ID_VP5, MKTAG('V', 'P', '5', '0') },
  175. { CODEC_ID_VP6, MKTAG('V', 'P', '6', ' ') },
  176. { CODEC_ID_VP6, MKTAG('V', 'P', '6', '0') },
  177. { CODEC_ID_VP6, MKTAG('V', 'P', '6', '1') },
  178. { CODEC_ID_VP6, MKTAG('V', 'P', '6', '2') },
  179. /*
  180. { CODEC_ID_VP4, MKTAG('V', 'P', '4', ' ') },
  181. { CODEC_ID_VP4, MKTAG('V', 'P', '4', '0') },
  182. */
  183. { CODEC_ID_MPEG4, MKTAG('X', 'V', 'I', 'D') }, /* cf sample xvid decoder from nsv_codec_sdk.zip */
  184. { CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B', '3') },
  185. { CODEC_ID_NONE, 0 },
  186. };
  187. static const AVCodecTag nsv_codec_audio_tags[] = {
  188. { CODEC_ID_MP3, MKTAG('M', 'P', '3', ' ') },
  189. { CODEC_ID_AAC, MKTAG('A', 'A', 'C', ' ') },
  190. { CODEC_ID_AAC, MKTAG('A', 'A', 'C', 'P') },
  191. { CODEC_ID_SPEEX, MKTAG('S', 'P', 'X', ' ') },
  192. { CODEC_ID_PCM_U16LE, MKTAG('P', 'C', 'M', ' ') },
  193. { CODEC_ID_NONE, 0 },
  194. };
  195. //static int nsv_load_index(AVFormatContext *s);
  196. static int nsv_read_chunk(AVFormatContext *s, int fill_header);
  197. #define print_tag(str, tag, size) \
  198. av_dlog(NULL, "%s: tag=%c%c%c%c\n", \
  199. str, tag & 0xff, \
  200. (tag >> 8) & 0xff, \
  201. (tag >> 16) & 0xff, \
  202. (tag >> 24) & 0xff);
  203. /* try to find something we recognize, and set the state accordingly */
  204. static int nsv_resync(AVFormatContext *s)
  205. {
  206. NSVContext *nsv = s->priv_data;
  207. AVIOContext *pb = s->pb;
  208. uint32_t v = 0;
  209. int i;
  210. av_dlog(s, "%s(), offset = %"PRId64", state = %d\n", __FUNCTION__, avio_tell(pb), nsv->state);
  211. //nsv->state = NSV_UNSYNC;
  212. for (i = 0; i < NSV_MAX_RESYNC; i++) {
  213. if (pb->eof_reached) {
  214. av_dlog(s, "NSV EOF\n");
  215. nsv->state = NSV_UNSYNC;
  216. return -1;
  217. }
  218. v <<= 8;
  219. v |= avio_r8(pb);
  220. if (i < 8) {
  221. av_dlog(s, "NSV resync: [%d] = %02x\n", i, v & 0x0FF);
  222. }
  223. if ((v & 0x0000ffff) == 0xefbe) { /* BEEF */
  224. av_dlog(s, "NSV resynced on BEEF after %d bytes\n", i+1);
  225. nsv->state = NSV_FOUND_BEEF;
  226. return 0;
  227. }
  228. /* we read as big endian, thus the MK*BE* */
  229. if (v == TB_NSVF) { /* NSVf */
  230. av_dlog(s, "NSV resynced on NSVf after %d bytes\n", i+1);
  231. nsv->state = NSV_FOUND_NSVF;
  232. return 0;
  233. }
  234. if (v == MKBETAG('N', 'S', 'V', 's')) { /* NSVs */
  235. av_dlog(s, "NSV resynced on NSVs after %d bytes\n", i+1);
  236. nsv->state = NSV_FOUND_NSVS;
  237. return 0;
  238. }
  239. }
  240. av_dlog(s, "NSV sync lost\n");
  241. return -1;
  242. }
  243. static int nsv_parse_NSVf_header(AVFormatContext *s)
  244. {
  245. NSVContext *nsv = s->priv_data;
  246. AVIOContext *pb = s->pb;
  247. unsigned int av_unused file_size;
  248. unsigned int size;
  249. int64_t duration;
  250. int strings_size;
  251. int table_entries;
  252. int table_entries_used;
  253. av_dlog(s, "%s()\n", __FUNCTION__);
  254. nsv->state = NSV_UNSYNC; /* in case we fail */
  255. size = avio_rl32(pb);
  256. if (size < 28)
  257. return -1;
  258. nsv->NSVf_end = size;
  259. //s->file_size = (uint32_t)avio_rl32(pb);
  260. file_size = (uint32_t)avio_rl32(pb);
  261. av_dlog(s, "NSV NSVf chunk_size %u\n", size);
  262. av_dlog(s, "NSV NSVf file_size %u\n", file_size);
  263. nsv->duration = duration = avio_rl32(pb); /* in ms */
  264. av_dlog(s, "NSV NSVf duration %"PRId64" ms\n", duration);
  265. // XXX: store it in AVStreams
  266. strings_size = avio_rl32(pb);
  267. table_entries = avio_rl32(pb);
  268. table_entries_used = avio_rl32(pb);
  269. av_dlog(s, "NSV NSVf info-strings size: %d, table entries: %d, bis %d\n",
  270. strings_size, table_entries, table_entries_used);
  271. if (pb->eof_reached)
  272. return -1;
  273. av_dlog(s, "NSV got header; filepos %"PRId64"\n", avio_tell(pb));
  274. if (strings_size > 0) {
  275. char *strings; /* last byte will be '\0' to play safe with str*() */
  276. char *p, *endp;
  277. char *token, *value;
  278. char quote;
  279. p = strings = av_mallocz((size_t)strings_size + 1);
  280. if (!p)
  281. return AVERROR(ENOMEM);
  282. endp = strings + strings_size;
  283. avio_read(pb, strings, strings_size);
  284. while (p < endp) {
  285. while (*p == ' ')
  286. p++; /* strip out spaces */
  287. if (p >= endp-2)
  288. break;
  289. token = p;
  290. p = strchr(p, '=');
  291. if (!p || p >= endp-2)
  292. break;
  293. *p++ = '\0';
  294. quote = *p++;
  295. value = p;
  296. p = strchr(p, quote);
  297. if (!p || p >= endp)
  298. break;
  299. *p++ = '\0';
  300. av_dlog(s, "NSV NSVf INFO: %s='%s'\n", token, value);
  301. av_dict_set(&s->metadata, token, value, 0);
  302. }
  303. av_free(strings);
  304. }
  305. if (pb->eof_reached)
  306. return -1;
  307. av_dlog(s, "NSV got infos; filepos %"PRId64"\n", avio_tell(pb));
  308. if (table_entries_used > 0) {
  309. int i;
  310. nsv->index_entries = table_entries_used;
  311. if((unsigned)table_entries_used >= UINT_MAX / sizeof(uint32_t))
  312. return -1;
  313. nsv->nsvs_file_offset = av_malloc((unsigned)table_entries_used * sizeof(uint32_t));
  314. if (!nsv->nsvs_file_offset)
  315. return AVERROR(ENOMEM);
  316. for(i=0;i<table_entries_used;i++)
  317. nsv->nsvs_file_offset[i] = avio_rl32(pb) + size;
  318. if(table_entries > table_entries_used &&
  319. avio_rl32(pb) == MKTAG('T','O','C','2')) {
  320. nsv->nsvs_timestamps = av_malloc((unsigned)table_entries_used*sizeof(uint32_t));
  321. if (!nsv->nsvs_timestamps)
  322. return AVERROR(ENOMEM);
  323. for(i=0;i<table_entries_used;i++) {
  324. nsv->nsvs_timestamps[i] = avio_rl32(pb);
  325. }
  326. }
  327. }
  328. av_dlog(s, "NSV got index; filepos %"PRId64"\n", avio_tell(pb));
  329. #ifdef DEBUG_DUMP_INDEX
  330. #define V(v) ((v<0x20 || v > 127)?'.':v)
  331. /* dump index */
  332. av_dlog(s, "NSV %d INDEX ENTRIES:\n", table_entries);
  333. av_dlog(s, "NSV [dataoffset][fileoffset]\n", table_entries);
  334. for (i = 0; i < table_entries; i++) {
  335. unsigned char b[8];
  336. avio_seek(pb, size + nsv->nsvs_file_offset[i], SEEK_SET);
  337. avio_read(pb, b, 8);
  338. av_dlog(s, "NSV [0x%08lx][0x%08lx]: %02x %02x %02x %02x %02x %02x %02x %02x"
  339. "%c%c%c%c%c%c%c%c\n",
  340. nsv->nsvs_file_offset[i], size + nsv->nsvs_file_offset[i],
  341. b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
  342. V(b[0]), V(b[1]), V(b[2]), V(b[3]), V(b[4]), V(b[5]), V(b[6]), V(b[7]) );
  343. }
  344. //avio_seek(pb, size, SEEK_SET); /* go back to end of header */
  345. #undef V
  346. #endif
  347. avio_seek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */
  348. if (pb->eof_reached)
  349. return -1;
  350. nsv->state = NSV_HAS_READ_NSVF;
  351. return 0;
  352. }
  353. static int nsv_parse_NSVs_header(AVFormatContext *s)
  354. {
  355. NSVContext *nsv = s->priv_data;
  356. AVIOContext *pb = s->pb;
  357. uint32_t vtag, atag;
  358. uint16_t vwidth, vheight;
  359. AVRational framerate;
  360. int i;
  361. AVStream *st;
  362. NSVStream *nst;
  363. av_dlog(s, "%s()\n", __FUNCTION__);
  364. vtag = avio_rl32(pb);
  365. atag = avio_rl32(pb);
  366. vwidth = avio_rl16(pb);
  367. vheight = avio_rl16(pb);
  368. i = avio_r8(pb);
  369. av_dlog(s, "NSV NSVs framerate code %2x\n", i);
  370. if(i&0x80) { /* odd way of giving native framerates from docs */
  371. int t=(i & 0x7F)>>2;
  372. if(t<16) framerate = (AVRational){1, t+1};
  373. else framerate = (AVRational){t-15, 1};
  374. if(i&1){
  375. framerate.num *= 1000;
  376. framerate.den *= 1001;
  377. }
  378. if((i&3)==3) framerate.num *= 24;
  379. else if((i&3)==2) framerate.num *= 25;
  380. else framerate.num *= 30;
  381. }
  382. else
  383. framerate= (AVRational){i, 1};
  384. nsv->avsync = avio_rl16(pb);
  385. nsv->framerate = framerate;
  386. print_tag("NSV NSVs vtag", vtag, 0);
  387. print_tag("NSV NSVs atag", atag, 0);
  388. av_dlog(s, "NSV NSVs vsize %dx%d\n", vwidth, vheight);
  389. /* XXX change to ap != NULL ? */
  390. if (s->nb_streams == 0) { /* streams not yet published, let's do that */
  391. nsv->vtag = vtag;
  392. nsv->atag = atag;
  393. nsv->vwidth = vwidth;
  394. nsv->vheight = vwidth;
  395. if (vtag != T_NONE) {
  396. int i;
  397. st = avformat_new_stream(s, NULL);
  398. if (!st)
  399. goto fail;
  400. st->id = NSV_ST_VIDEO;
  401. nst = av_mallocz(sizeof(NSVStream));
  402. if (!nst)
  403. goto fail;
  404. st->priv_data = nst;
  405. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  406. st->codec->codec_tag = vtag;
  407. st->codec->codec_id = ff_codec_get_id(nsv_codec_video_tags, vtag);
  408. st->codec->width = vwidth;
  409. st->codec->height = vheight;
  410. st->codec->bits_per_coded_sample = 24; /* depth XXX */
  411. avpriv_set_pts_info(st, 64, framerate.den, framerate.num);
  412. st->start_time = 0;
  413. st->duration = av_rescale(nsv->duration, framerate.num, 1000*framerate.den);
  414. for(i=0;i<nsv->index_entries;i++) {
  415. if(nsv->nsvs_timestamps) {
  416. av_add_index_entry(st, nsv->nsvs_file_offset[i], nsv->nsvs_timestamps[i],
  417. 0, 0, AVINDEX_KEYFRAME);
  418. } else {
  419. int64_t ts = av_rescale(i*nsv->duration/nsv->index_entries, framerate.num, 1000*framerate.den);
  420. av_add_index_entry(st, nsv->nsvs_file_offset[i], ts, 0, 0, AVINDEX_KEYFRAME);
  421. }
  422. }
  423. }
  424. if (atag != T_NONE) {
  425. #ifndef DISABLE_AUDIO
  426. st = avformat_new_stream(s, NULL);
  427. if (!st)
  428. goto fail;
  429. st->id = NSV_ST_AUDIO;
  430. nst = av_mallocz(sizeof(NSVStream));
  431. if (!nst)
  432. goto fail;
  433. st->priv_data = nst;
  434. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  435. st->codec->codec_tag = atag;
  436. st->codec->codec_id = ff_codec_get_id(nsv_codec_audio_tags, atag);
  437. st->need_parsing = AVSTREAM_PARSE_FULL; /* for PCM we will read a chunk later and put correct info */
  438. /* set timebase to common denominator of ms and framerate */
  439. avpriv_set_pts_info(st, 64, 1, framerate.num*1000);
  440. st->start_time = 0;
  441. st->duration = (int64_t)nsv->duration * framerate.num;
  442. #endif
  443. }
  444. #ifdef CHECK_SUBSEQUENT_NSVS
  445. } else {
  446. if (nsv->vtag != vtag || nsv->atag != atag || nsv->vwidth != vwidth || nsv->vheight != vwidth) {
  447. av_dlog(s, "NSV NSVs header values differ from the first one!!!\n");
  448. //return -1;
  449. }
  450. #endif /* CHECK_SUBSEQUENT_NSVS */
  451. }
  452. nsv->state = NSV_HAS_READ_NSVS;
  453. return 0;
  454. fail:
  455. /* XXX */
  456. nsv->state = NSV_UNSYNC;
  457. return -1;
  458. }
  459. static int nsv_read_header(AVFormatContext *s)
  460. {
  461. NSVContext *nsv = s->priv_data;
  462. int i, err;
  463. av_dlog(s, "%s()\n", __FUNCTION__);
  464. av_dlog(s, "filename '%s'\n", s->filename);
  465. nsv->state = NSV_UNSYNC;
  466. nsv->ahead[0].data = nsv->ahead[1].data = NULL;
  467. for (i = 0; i < NSV_MAX_RESYNC_TRIES; i++) {
  468. if (nsv_resync(s) < 0)
  469. return -1;
  470. if (nsv->state == NSV_FOUND_NSVF) {
  471. err = nsv_parse_NSVf_header(s);
  472. if (err < 0)
  473. return err;
  474. }
  475. /* we need the first NSVs also... */
  476. if (nsv->state == NSV_FOUND_NSVS) {
  477. err = nsv_parse_NSVs_header(s);
  478. if (err < 0)
  479. return err;
  480. break; /* we just want the first one */
  481. }
  482. }
  483. if (s->nb_streams < 1) /* no luck so far */
  484. return -1;
  485. /* now read the first chunk, so we can attempt to decode more info */
  486. err = nsv_read_chunk(s, 1);
  487. av_dlog(s, "parsed header\n");
  488. return err;
  489. }
  490. static int nsv_read_chunk(AVFormatContext *s, int fill_header)
  491. {
  492. NSVContext *nsv = s->priv_data;
  493. AVIOContext *pb = s->pb;
  494. AVStream *st[2] = {NULL, NULL};
  495. NSVStream *nst;
  496. AVPacket *pkt;
  497. int i, err = 0;
  498. uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */
  499. uint32_t vsize;
  500. uint16_t asize;
  501. uint16_t auxsize;
  502. av_dlog(s, "%s(%d)\n", __FUNCTION__, fill_header);
  503. if (nsv->ahead[0].data || nsv->ahead[1].data)
  504. return 0; //-1; /* hey! eat what you've in your plate first! */
  505. null_chunk_retry:
  506. if (pb->eof_reached)
  507. return -1;
  508. for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++)
  509. err = nsv_resync(s);
  510. if (err < 0)
  511. return err;
  512. if (nsv->state == NSV_FOUND_NSVS)
  513. err = nsv_parse_NSVs_header(s);
  514. if (err < 0)
  515. return err;
  516. if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF)
  517. return -1;
  518. auxcount = avio_r8(pb);
  519. vsize = avio_rl16(pb);
  520. asize = avio_rl16(pb);
  521. vsize = (vsize << 4) | (auxcount >> 4);
  522. auxcount &= 0x0f;
  523. av_dlog(s, "NSV CHUNK %d aux, %u bytes video, %d bytes audio\n", auxcount, vsize, asize);
  524. /* skip aux stuff */
  525. for (i = 0; i < auxcount; i++) {
  526. uint32_t av_unused auxtag;
  527. auxsize = avio_rl16(pb);
  528. auxtag = avio_rl32(pb);
  529. av_dlog(s, "NSV aux data: '%c%c%c%c', %d bytes\n",
  530. (auxtag & 0x0ff),
  531. ((auxtag >> 8) & 0x0ff),
  532. ((auxtag >> 16) & 0x0ff),
  533. ((auxtag >> 24) & 0x0ff),
  534. auxsize);
  535. avio_skip(pb, auxsize);
  536. vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming braindead */
  537. }
  538. if (pb->eof_reached)
  539. return -1;
  540. if (!vsize && !asize) {
  541. nsv->state = NSV_UNSYNC;
  542. goto null_chunk_retry;
  543. }
  544. /* map back streams to v,a */
  545. if (s->nb_streams > 0)
  546. st[s->streams[0]->id] = s->streams[0];
  547. if (s->nb_streams > 1)
  548. st[s->streams[1]->id] = s->streams[1];
  549. if (vsize && st[NSV_ST_VIDEO]) {
  550. nst = st[NSV_ST_VIDEO]->priv_data;
  551. pkt = &nsv->ahead[NSV_ST_VIDEO];
  552. av_get_packet(pb, pkt, vsize);
  553. pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO;
  554. pkt->dts = nst->frame_offset;
  555. pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */
  556. for (i = 0; i < FFMIN(8, vsize); i++)
  557. av_dlog(s, "NSV video: [%d] = %02x\n", i, pkt->data[i]);
  558. }
  559. if(st[NSV_ST_VIDEO])
  560. ((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++;
  561. if (asize && st[NSV_ST_AUDIO]) {
  562. nst = st[NSV_ST_AUDIO]->priv_data;
  563. pkt = &nsv->ahead[NSV_ST_AUDIO];
  564. /* read raw audio specific header on the first audio chunk... */
  565. /* on ALL audio chunks ?? seems so! */
  566. if (asize && st[NSV_ST_AUDIO]->codec->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) {
  567. uint8_t bps;
  568. uint8_t channels;
  569. uint16_t samplerate;
  570. bps = avio_r8(pb);
  571. channels = avio_r8(pb);
  572. samplerate = avio_rl16(pb);
  573. asize-=4;
  574. av_dlog(s, "NSV RAWAUDIO: bps %d, nchan %d, srate %d\n", bps, channels, samplerate);
  575. if (fill_header) {
  576. st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */
  577. if (bps != 16) {
  578. av_dlog(s, "NSV AUDIO bit/sample != 16 (%d)!!!\n", bps);
  579. }
  580. bps /= channels; // ???
  581. if (bps == 8)
  582. st[NSV_ST_AUDIO]->codec->codec_id = CODEC_ID_PCM_U8;
  583. samplerate /= 4;/* UGH ??? XXX */
  584. channels = 1;
  585. st[NSV_ST_AUDIO]->codec->channels = channels;
  586. st[NSV_ST_AUDIO]->codec->sample_rate = samplerate;
  587. av_dlog(s, "NSV RAWAUDIO: bps %d, nchan %d, srate %d\n", bps, channels, samplerate);
  588. }
  589. }
  590. av_get_packet(pb, pkt, asize);
  591. pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO;
  592. pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */
  593. if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) {
  594. /* on a nsvs frame we have new information on a/v sync */
  595. pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1);
  596. pkt->dts *= (int64_t)1000 * nsv->framerate.den;
  597. pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num;
  598. av_dlog(s, "NSV AUDIO: sync:%d, dts:%"PRId64, nsv->avsync, pkt->dts);
  599. }
  600. nst->frame_offset++;
  601. }
  602. nsv->state = NSV_UNSYNC;
  603. return 0;
  604. }
  605. static int nsv_read_packet(AVFormatContext *s, AVPacket *pkt)
  606. {
  607. NSVContext *nsv = s->priv_data;
  608. int i, err = 0;
  609. av_dlog(s, "%s()\n", __FUNCTION__);
  610. /* in case we don't already have something to eat ... */
  611. if (nsv->ahead[0].data == NULL && nsv->ahead[1].data == NULL)
  612. err = nsv_read_chunk(s, 0);
  613. if (err < 0)
  614. return err;
  615. /* now pick one of the plates */
  616. for (i = 0; i < 2; i++) {
  617. if (nsv->ahead[i].data) {
  618. av_dlog(s, "%s: using cached packet[%d]\n", __FUNCTION__, i);
  619. /* avoid the cost of new_packet + memcpy(->data) */
  620. memcpy(pkt, &nsv->ahead[i], sizeof(AVPacket));
  621. nsv->ahead[i].data = NULL; /* we ate that one */
  622. return pkt->size;
  623. }
  624. }
  625. /* this restaurant is not approvisionned :^] */
  626. return -1;
  627. }
  628. static int nsv_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  629. {
  630. NSVContext *nsv = s->priv_data;
  631. AVStream *st = s->streams[stream_index];
  632. NSVStream *nst = st->priv_data;
  633. int index;
  634. index = av_index_search_timestamp(st, timestamp, flags);
  635. if(index < 0)
  636. return -1;
  637. if (avio_seek(s->pb, st->index_entries[index].pos, SEEK_SET) < 0)
  638. return -1;
  639. nst->frame_offset = st->index_entries[index].timestamp;
  640. nsv->state = NSV_UNSYNC;
  641. return 0;
  642. }
  643. static int nsv_read_close(AVFormatContext *s)
  644. {
  645. /* int i; */
  646. NSVContext *nsv = s->priv_data;
  647. av_freep(&nsv->nsvs_file_offset);
  648. av_freep(&nsv->nsvs_timestamps);
  649. if (nsv->ahead[0].data)
  650. av_free_packet(&nsv->ahead[0]);
  651. if (nsv->ahead[1].data)
  652. av_free_packet(&nsv->ahead[1]);
  653. #if 0
  654. for(i=0;i<s->nb_streams;i++) {
  655. AVStream *st = s->streams[i];
  656. NSVStream *ast = st->priv_data;
  657. if(ast){
  658. av_free(ast->index_entries);
  659. av_free(ast);
  660. }
  661. av_free(st->codec->palctrl);
  662. }
  663. #endif
  664. return 0;
  665. }
  666. static int nsv_probe(AVProbeData *p)
  667. {
  668. int i;
  669. int score;
  670. int vsize, asize, auxcount;
  671. score = 0;
  672. av_dlog(NULL, "nsv_probe(), buf_size %d\n", p->buf_size);
  673. /* check file header */
  674. /* streamed files might not have any header */
  675. if (p->buf[0] == 'N' && p->buf[1] == 'S' &&
  676. p->buf[2] == 'V' && (p->buf[3] == 'f' || p->buf[3] == 's'))
  677. return AVPROBE_SCORE_MAX;
  678. /* XXX: do streamed files always start at chunk boundary ?? */
  679. /* or do we need to search NSVs in the byte stream ? */
  680. /* seems the servers don't bother starting clean chunks... */
  681. /* sometimes even the first header is at 9KB or something :^) */
  682. for (i = 1; i < p->buf_size - 3; i++) {
  683. if (p->buf[i+0] == 'N' && p->buf[i+1] == 'S' &&
  684. p->buf[i+2] == 'V' && p->buf[i+3] == 's') {
  685. score = AVPROBE_SCORE_MAX/5;
  686. /* Get the chunk size and check if at the end we are getting 0xBEEF */
  687. auxcount = p->buf[i+19];
  688. vsize = p->buf[i+20] | p->buf[i+21] << 8;
  689. asize = p->buf[i+22] | p->buf[i+23] << 8;
  690. vsize = (vsize << 4) | (auxcount >> 4);
  691. if ((asize + vsize + i + 23) < p->buf_size - 2) {
  692. if (p->buf[i+23+asize+vsize+1] == 0xEF &&
  693. p->buf[i+23+asize+vsize+2] == 0xBE)
  694. return AVPROBE_SCORE_MAX-20;
  695. }
  696. }
  697. }
  698. /* so we'll have more luck on extension... */
  699. if (av_match_ext(p->filename, "nsv"))
  700. return AVPROBE_SCORE_MAX/2;
  701. /* FIXME: add mime-type check */
  702. return score;
  703. }
  704. AVInputFormat ff_nsv_demuxer = {
  705. .name = "nsv",
  706. .long_name = NULL_IF_CONFIG_SMALL("Nullsoft Streaming Video"),
  707. .priv_data_size = sizeof(NSVContext),
  708. .read_probe = nsv_probe,
  709. .read_header = nsv_read_header,
  710. .read_packet = nsv_read_packet,
  711. .read_close = nsv_read_close,
  712. .read_seek = nsv_read_seek,
  713. };