Libav 0.7.1
libavformat/nsvdec.c
Go to the documentation of this file.
00001 /*
00002  * NSV demuxer
00003  * Copyright (c) 2004 The Libav Project
00004  *
00005  * This file is part of Libav.
00006  *
00007  * Libav is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * Libav is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with Libav; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 #include "avformat.h"
00022 #include "riff.h"
00023 #include "libavutil/dict.h"
00024 
00025 //#define DEBUG_DUMP_INDEX // XXX dumbdriving-271.nsv breaks with it commented!!
00026 #define CHECK_SUBSEQUENT_NSVS
00027 //#define DISABLE_AUDIO
00028 
00029 /* max bytes to crawl for trying to resync
00030  * stupid streaming servers don't start at chunk boundaries...
00031  */
00032 #define NSV_MAX_RESYNC (500*1024)
00033 #define NSV_MAX_RESYNC_TRIES 300
00034 
00035 /*
00036  * First version by Francois Revol - revol@free.fr
00037  * References:
00038  * (1) http://www.multimedia.cx/nsv-format.txt
00039  * seems someone came to the same conclusions as me, and updated it:
00040  * (2) http://www.stud.ktu.lt/~vitslav/nsv/nsv-format.txt
00041  *     http://www.stud.ktu.lt/~vitslav/nsv/
00042  * official docs
00043  * (3) http://ultravox.aol.com/NSVFormat.rtf
00044  * Sample files:
00045  * (S1) http://www.nullsoft.com/nsv/samples/
00046  * http://www.nullsoft.com/nsv/samples/faster.nsv
00047  * http://streamripper.sourceforge.net/openbb/read.php?TID=492&page=4
00048  */
00049 
00050 /*
00051  * notes on the header (Francois Revol):
00052  *
00053  * It is followed by strings, then a table, but nothing tells
00054  * where the table begins according to (1). After checking faster.nsv,
00055  * I believe NVSf[16-19] gives the size of the strings data
00056  * (that is the offset of the data table after the header).
00057  * After checking all samples from (S1) all confirms this.
00058  *
00059  * Then, about NSVf[12-15], faster.nsf has 179700. When veiwing it in VLC,
00060  * I noticed there was about 1 NVSs chunk/s, so I ran
00061  * strings faster.nsv | grep NSVs | wc -l
00062  * which gave me 180. That leads me to think that NSVf[12-15] might be the
00063  * file length in milliseconds.
00064  * Let's try that:
00065  * 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
00066  * except for nstrailer (which doesn't have an NSVf header), it repports correct time.
00067  *
00068  * nsvtrailer.nsv (S1) does not have any NSVf header, only NSVs chunks,
00069  * so the header seems to not be mandatory. (for streaming).
00070  *
00071  * index slice duration check (excepts nsvtrailer.nsv):
00072  * for f in [^n]*.nsv; do DUR="$(ffmpeg -i "$f" 2>/dev/null | grep 'NSVf duration' | cut -d ' ' -f 4)"; IC="$(ffmpeg -i "$f" 2>/dev/null | grep 'INDEX ENTRIES' | cut -d ' ' -f 2)"; echo "duration $DUR, slite time $(($DUR/$IC))"; done
00073  */
00074 
00075 /*
00076  * TODO:
00077  * - handle timestamps !!!
00078  * - use index
00079  * - mime-type in probe()
00080  * - seek
00081  */
00082 
00083 #if 0
00084 struct NSVf_header {
00085     uint32_t chunk_tag; /* 'NSVf' */
00086     uint32_t chunk_size;
00087     uint32_t file_size; /* max 4GB ??? no one learns anything it seems :^) */
00088     uint32_t file_length; //unknown1;  /* what about MSB of file_size ? */
00089     uint32_t info_strings_size; /* size of the info strings */ //unknown2;
00090     uint32_t table_entries;
00091     uint32_t table_entries_used; /* the left ones should be -1 */
00092 };
00093 
00094 struct NSVs_header {
00095     uint32_t chunk_tag; /* 'NSVs' */
00096     uint32_t v4cc;      /* or 'NONE' */
00097     uint32_t a4cc;      /* or 'NONE' */
00098     uint16_t vwidth;    /* assert(vwidth%16==0) */
00099     uint16_t vheight;   /* assert(vheight%16==0) */
00100     uint8_t framerate;  /* value = (framerate&0x80)?frtable[frameratex0x7f]:framerate */
00101     uint16_t unknown;
00102 };
00103 
00104 struct nsv_avchunk_header {
00105     uint8_t vchunk_size_lsb;
00106     uint16_t vchunk_size_msb; /* value = (vchunk_size_msb << 4) | (vchunk_size_lsb >> 4) */
00107     uint16_t achunk_size;
00108 };
00109 
00110 struct nsv_pcm_header {
00111     uint8_t bits_per_sample;
00112     uint8_t channel_count;
00113     uint16_t sample_rate;
00114 };
00115 #endif
00116 
00117 /* variation from avi.h */
00118 /*typedef struct CodecTag {
00119     int id;
00120     unsigned int tag;
00121 } CodecTag;*/
00122 
00123 /* tags */
00124 
00125 #define T_NSVF MKTAG('N', 'S', 'V', 'f') /* file header */
00126 #define T_NSVS MKTAG('N', 'S', 'V', 's') /* chunk header */
00127 #define T_TOC2 MKTAG('T', 'O', 'C', '2') /* extra index marker */
00128 #define T_NONE MKTAG('N', 'O', 'N', 'E') /* null a/v 4CC */
00129 #define T_SUBT MKTAG('S', 'U', 'B', 'T') /* subtitle aux data */
00130 #define T_ASYN MKTAG('A', 'S', 'Y', 'N') /* async a/v aux marker */
00131 #define T_KEYF MKTAG('K', 'E', 'Y', 'F') /* video keyframe aux marker (addition) */
00132 
00133 #define TB_NSVF MKBETAG('N', 'S', 'V', 'f')
00134 #define TB_NSVS MKBETAG('N', 'S', 'V', 's')
00135 
00136 /* hardcoded stream indexes */
00137 #define NSV_ST_VIDEO 0
00138 #define NSV_ST_AUDIO 1
00139 #define NSV_ST_SUBT 2
00140 
00141 enum NSVStatus {
00142     NSV_UNSYNC,
00143     NSV_FOUND_NSVF,
00144     NSV_HAS_READ_NSVF,
00145     NSV_FOUND_NSVS,
00146     NSV_HAS_READ_NSVS,
00147     NSV_FOUND_BEEF,
00148     NSV_GOT_VIDEO,
00149     NSV_GOT_AUDIO,
00150 };
00151 
00152 typedef struct NSVStream {
00153     int frame_offset; /* current frame (video) or byte (audio) counter
00154                          (used to compute the pts) */
00155     int scale;
00156     int rate;
00157     int sample_size; /* audio only data */
00158     int start;
00159 
00160     int new_frame_offset; /* temporary storage (used during seek) */
00161     int cum_len; /* temporary storage (used during seek) */
00162 } NSVStream;
00163 
00164 typedef struct {
00165     int  base_offset;
00166     int  NSVf_end;
00167     uint32_t *nsvs_file_offset;
00168     int index_entries;
00169     enum NSVStatus state;
00170     AVPacket ahead[2]; /* [v, a] if .data is !NULL there is something */
00171     /* cached */
00172     int64_t duration;
00173     uint32_t vtag, atag;
00174     uint16_t vwidth, vheight;
00175     int16_t avsync;
00176     AVRational framerate;
00177     uint32_t *nsvs_timestamps;
00178     //DVDemuxContext* dv_demux;
00179 } NSVContext;
00180 
00181 static const AVCodecTag nsv_codec_video_tags[] = {
00182     { CODEC_ID_VP3, MKTAG('V', 'P', '3', ' ') },
00183     { CODEC_ID_VP3, MKTAG('V', 'P', '3', '0') },
00184     { CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') },
00185     { CODEC_ID_VP5, MKTAG('V', 'P', '5', ' ') },
00186     { CODEC_ID_VP5, MKTAG('V', 'P', '5', '0') },
00187     { CODEC_ID_VP6, MKTAG('V', 'P', '6', ' ') },
00188     { CODEC_ID_VP6, MKTAG('V', 'P', '6', '0') },
00189     { CODEC_ID_VP6, MKTAG('V', 'P', '6', '1') },
00190     { CODEC_ID_VP6, MKTAG('V', 'P', '6', '2') },
00191 /*
00192     { CODEC_ID_VP4, MKTAG('V', 'P', '4', ' ') },
00193     { CODEC_ID_VP4, MKTAG('V', 'P', '4', '0') },
00194 */
00195     { CODEC_ID_MPEG4, MKTAG('X', 'V', 'I', 'D') }, /* cf sample xvid decoder from nsv_codec_sdk.zip */
00196     { CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B', '3') },
00197     { CODEC_ID_NONE, 0 },
00198 };
00199 
00200 static const AVCodecTag nsv_codec_audio_tags[] = {
00201     { CODEC_ID_MP3,       MKTAG('M', 'P', '3', ' ') },
00202     { CODEC_ID_AAC,       MKTAG('A', 'A', 'C', ' ') },
00203     { CODEC_ID_AAC,       MKTAG('A', 'A', 'C', 'P') },
00204     { CODEC_ID_SPEEX,     MKTAG('S', 'P', 'X', ' ') },
00205     { CODEC_ID_PCM_U16LE, MKTAG('P', 'C', 'M', ' ') },
00206     { CODEC_ID_NONE,      0 },
00207 };
00208 
00209 //static int nsv_load_index(AVFormatContext *s);
00210 static int nsv_read_chunk(AVFormatContext *s, int fill_header);
00211 
00212 #define print_tag(str, tag, size)       \
00213     av_dlog(NULL, "%s: tag=%c%c%c%c\n", \
00214             str, tag & 0xff,            \
00215             (tag >> 8) & 0xff,          \
00216             (tag >> 16) & 0xff,         \
00217             (tag >> 24) & 0xff);
00218 
00219 /* try to find something we recognize, and set the state accordingly */
00220 static int nsv_resync(AVFormatContext *s)
00221 {
00222     NSVContext *nsv = s->priv_data;
00223     AVIOContext *pb = s->pb;
00224     uint32_t v = 0;
00225     int i;
00226 
00227     av_dlog(s, "%s(), offset = %"PRId64", state = %d\n", __FUNCTION__, avio_tell(pb), nsv->state);
00228 
00229     //nsv->state = NSV_UNSYNC;
00230 
00231     for (i = 0; i < NSV_MAX_RESYNC; i++) {
00232         if (pb->eof_reached) {
00233             av_dlog(s, "NSV EOF\n");
00234             nsv->state = NSV_UNSYNC;
00235             return -1;
00236         }
00237         v <<= 8;
00238         v |= avio_r8(pb);
00239         if (i < 8) {
00240             av_dlog(s, "NSV resync: [%d] = %02x\n", i, v & 0x0FF);
00241         }
00242 
00243         if ((v & 0x0000ffff) == 0xefbe) { /* BEEF */
00244             av_dlog(s, "NSV resynced on BEEF after %d bytes\n", i+1);
00245             nsv->state = NSV_FOUND_BEEF;
00246             return 0;
00247         }
00248         /* we read as big endian, thus the MK*BE* */
00249         if (v == TB_NSVF) { /* NSVf */
00250             av_dlog(s, "NSV resynced on NSVf after %d bytes\n", i+1);
00251             nsv->state = NSV_FOUND_NSVF;
00252             return 0;
00253         }
00254         if (v == MKBETAG('N', 'S', 'V', 's')) { /* NSVs */
00255             av_dlog(s, "NSV resynced on NSVs after %d bytes\n", i+1);
00256             nsv->state = NSV_FOUND_NSVS;
00257             return 0;
00258         }
00259 
00260     }
00261     av_dlog(s, "NSV sync lost\n");
00262     return -1;
00263 }
00264 
00265 static int nsv_parse_NSVf_header(AVFormatContext *s, AVFormatParameters *ap)
00266 {
00267     NSVContext *nsv = s->priv_data;
00268     AVIOContext *pb = s->pb;
00269     unsigned int av_unused file_size;
00270     unsigned int size;
00271     int64_t duration;
00272     int strings_size;
00273     int table_entries;
00274     int table_entries_used;
00275 
00276     av_dlog(s, "%s()\n", __FUNCTION__);
00277 
00278     nsv->state = NSV_UNSYNC; /* in case we fail */
00279 
00280     size = avio_rl32(pb);
00281     if (size < 28)
00282         return -1;
00283     nsv->NSVf_end = size;
00284 
00285     //s->file_size = (uint32_t)avio_rl32(pb);
00286     file_size = (uint32_t)avio_rl32(pb);
00287     av_dlog(s, "NSV NSVf chunk_size %u\n", size);
00288     av_dlog(s, "NSV NSVf file_size %u\n", file_size);
00289 
00290     nsv->duration = duration = avio_rl32(pb); /* in ms */
00291     av_dlog(s, "NSV NSVf duration %"PRId64" ms\n", duration);
00292     // XXX: store it in AVStreams
00293 
00294     strings_size = avio_rl32(pb);
00295     table_entries = avio_rl32(pb);
00296     table_entries_used = avio_rl32(pb);
00297     av_dlog(s, "NSV NSVf info-strings size: %d, table entries: %d, bis %d\n",
00298             strings_size, table_entries, table_entries_used);
00299     if (pb->eof_reached)
00300         return -1;
00301 
00302     av_dlog(s, "NSV got header; filepos %"PRId64"\n", avio_tell(pb));
00303 
00304     if (strings_size > 0) {
00305         char *strings; /* last byte will be '\0' to play safe with str*() */
00306         char *p, *endp;
00307         char *token, *value;
00308         char quote;
00309 
00310         p = strings = av_mallocz((size_t)strings_size + 1);
00311         if (!p)
00312             return AVERROR(ENOMEM);
00313         endp = strings + strings_size;
00314         avio_read(pb, strings, strings_size);
00315         while (p < endp) {
00316             while (*p == ' ')
00317                 p++; /* strip out spaces */
00318             if (p >= endp-2)
00319                 break;
00320             token = p;
00321             p = strchr(p, '=');
00322             if (!p || p >= endp-2)
00323                 break;
00324             *p++ = '\0';
00325             quote = *p++;
00326             value = p;
00327             p = strchr(p, quote);
00328             if (!p || p >= endp)
00329                 break;
00330             *p++ = '\0';
00331             av_dlog(s, "NSV NSVf INFO: %s='%s'\n", token, value);
00332             av_dict_set(&s->metadata, token, value, 0);
00333         }
00334         av_free(strings);
00335     }
00336     if (pb->eof_reached)
00337         return -1;
00338 
00339     av_dlog(s, "NSV got infos; filepos %"PRId64"\n", avio_tell(pb));
00340 
00341     if (table_entries_used > 0) {
00342         int i;
00343         nsv->index_entries = table_entries_used;
00344         if((unsigned)table_entries_used >= UINT_MAX / sizeof(uint32_t))
00345             return -1;
00346         nsv->nsvs_file_offset = av_malloc((unsigned)table_entries_used * sizeof(uint32_t));
00347         if (!nsv->nsvs_file_offset)
00348             return AVERROR(ENOMEM);
00349 
00350         for(i=0;i<table_entries_used;i++)
00351             nsv->nsvs_file_offset[i] = avio_rl32(pb) + size;
00352 
00353         if(table_entries > table_entries_used &&
00354            avio_rl32(pb) == MKTAG('T','O','C','2')) {
00355             nsv->nsvs_timestamps = av_malloc((unsigned)table_entries_used*sizeof(uint32_t));
00356             if (!nsv->nsvs_timestamps)
00357                 return AVERROR(ENOMEM);
00358             for(i=0;i<table_entries_used;i++) {
00359                 nsv->nsvs_timestamps[i] = avio_rl32(pb);
00360             }
00361         }
00362     }
00363 
00364     av_dlog(s, "NSV got index; filepos %"PRId64"\n", avio_tell(pb));
00365 
00366 #ifdef DEBUG_DUMP_INDEX
00367 #define V(v) ((v<0x20 || v > 127)?'.':v)
00368     /* dump index */
00369     av_dlog(s, "NSV %d INDEX ENTRIES:\n", table_entries);
00370     av_dlog(s, "NSV [dataoffset][fileoffset]\n", table_entries);
00371     for (i = 0; i < table_entries; i++) {
00372         unsigned char b[8];
00373         avio_seek(pb, size + nsv->nsvs_file_offset[i], SEEK_SET);
00374         avio_read(pb, b, 8);
00375         av_dlog(s, "NSV [0x%08lx][0x%08lx]: %02x %02x %02x %02x %02x %02x %02x %02x"
00376            "%c%c%c%c%c%c%c%c\n",
00377            nsv->nsvs_file_offset[i], size + nsv->nsvs_file_offset[i],
00378            b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
00379            V(b[0]), V(b[1]), V(b[2]), V(b[3]), V(b[4]), V(b[5]), V(b[6]), V(b[7]) );
00380     }
00381     //avio_seek(pb, size, SEEK_SET); /* go back to end of header */
00382 #undef V
00383 #endif
00384 
00385     avio_seek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */
00386 
00387     if (pb->eof_reached)
00388         return -1;
00389     nsv->state = NSV_HAS_READ_NSVF;
00390     return 0;
00391 }
00392 
00393 static int nsv_parse_NSVs_header(AVFormatContext *s, AVFormatParameters *ap)
00394 {
00395     NSVContext *nsv = s->priv_data;
00396     AVIOContext *pb = s->pb;
00397     uint32_t vtag, atag;
00398     uint16_t vwidth, vheight;
00399     AVRational framerate;
00400     int i;
00401     AVStream *st;
00402     NSVStream *nst;
00403     av_dlog(s, "%s()\n", __FUNCTION__);
00404 
00405     vtag = avio_rl32(pb);
00406     atag = avio_rl32(pb);
00407     vwidth = avio_rl16(pb);
00408     vheight = avio_rl16(pb);
00409     i = avio_r8(pb);
00410 
00411     av_dlog(s, "NSV NSVs framerate code %2x\n", i);
00412     if(i&0x80) { /* odd way of giving native framerates from docs */
00413         int t=(i & 0x7F)>>2;
00414         if(t<16) framerate = (AVRational){1, t+1};
00415         else     framerate = (AVRational){t-15, 1};
00416 
00417         if(i&1){
00418             framerate.num *= 1000;
00419             framerate.den *= 1001;
00420         }
00421 
00422         if((i&3)==3)      framerate.num *= 24;
00423         else if((i&3)==2) framerate.num *= 25;
00424         else              framerate.num *= 30;
00425     }
00426     else
00427         framerate= (AVRational){i, 1};
00428 
00429     nsv->avsync = avio_rl16(pb);
00430     nsv->framerate = framerate;
00431 
00432     print_tag("NSV NSVs vtag", vtag, 0);
00433     print_tag("NSV NSVs atag", atag, 0);
00434     av_dlog(s, "NSV NSVs vsize %dx%d\n", vwidth, vheight);
00435 
00436     /* XXX change to ap != NULL ? */
00437     if (s->nb_streams == 0) { /* streams not yet published, let's do that */
00438         nsv->vtag = vtag;
00439         nsv->atag = atag;
00440         nsv->vwidth = vwidth;
00441         nsv->vheight = vwidth;
00442         if (vtag != T_NONE) {
00443             int i;
00444             st = av_new_stream(s, NSV_ST_VIDEO);
00445             if (!st)
00446                 goto fail;
00447 
00448             nst = av_mallocz(sizeof(NSVStream));
00449             if (!nst)
00450                 goto fail;
00451             st->priv_data = nst;
00452             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
00453             st->codec->codec_tag = vtag;
00454             st->codec->codec_id = ff_codec_get_id(nsv_codec_video_tags, vtag);
00455             st->codec->width = vwidth;
00456             st->codec->height = vheight;
00457             st->codec->bits_per_coded_sample = 24; /* depth XXX */
00458 
00459             av_set_pts_info(st, 64, framerate.den, framerate.num);
00460             st->start_time = 0;
00461             st->duration = av_rescale(nsv->duration, framerate.num, 1000*framerate.den);
00462 
00463             for(i=0;i<nsv->index_entries;i++) {
00464                 if(nsv->nsvs_timestamps) {
00465                     av_add_index_entry(st, nsv->nsvs_file_offset[i], nsv->nsvs_timestamps[i],
00466                                        0, 0, AVINDEX_KEYFRAME);
00467                 } else {
00468                     int64_t ts = av_rescale(i*nsv->duration/nsv->index_entries, framerate.num, 1000*framerate.den);
00469                     av_add_index_entry(st, nsv->nsvs_file_offset[i], ts, 0, 0, AVINDEX_KEYFRAME);
00470                 }
00471             }
00472         }
00473         if (atag != T_NONE) {
00474 #ifndef DISABLE_AUDIO
00475             st = av_new_stream(s, NSV_ST_AUDIO);
00476             if (!st)
00477                 goto fail;
00478 
00479             nst = av_mallocz(sizeof(NSVStream));
00480             if (!nst)
00481                 goto fail;
00482             st->priv_data = nst;
00483             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
00484             st->codec->codec_tag = atag;
00485             st->codec->codec_id = ff_codec_get_id(nsv_codec_audio_tags, atag);
00486 
00487             st->need_parsing = AVSTREAM_PARSE_FULL; /* for PCM we will read a chunk later and put correct info */
00488 
00489             /* set timebase to common denominator of ms and framerate */
00490             av_set_pts_info(st, 64, 1, framerate.num*1000);
00491             st->start_time = 0;
00492             st->duration = (int64_t)nsv->duration * framerate.num;
00493 #endif
00494         }
00495 #ifdef CHECK_SUBSEQUENT_NSVS
00496     } else {
00497         if (nsv->vtag != vtag || nsv->atag != atag || nsv->vwidth != vwidth || nsv->vheight != vwidth) {
00498             av_dlog(s, "NSV NSVs header values differ from the first one!!!\n");
00499             //return -1;
00500         }
00501 #endif /* CHECK_SUBSEQUENT_NSVS */
00502     }
00503 
00504     nsv->state = NSV_HAS_READ_NSVS;
00505     return 0;
00506 fail:
00507     /* XXX */
00508     nsv->state = NSV_UNSYNC;
00509     return -1;
00510 }
00511 
00512 static int nsv_read_header(AVFormatContext *s, AVFormatParameters *ap)
00513 {
00514     NSVContext *nsv = s->priv_data;
00515     int i, err;
00516 
00517     av_dlog(s, "%s()\n", __FUNCTION__);
00518     av_dlog(s, "filename '%s'\n", s->filename);
00519 
00520     nsv->state = NSV_UNSYNC;
00521     nsv->ahead[0].data = nsv->ahead[1].data = NULL;
00522 
00523     for (i = 0; i < NSV_MAX_RESYNC_TRIES; i++) {
00524         if (nsv_resync(s) < 0)
00525             return -1;
00526         if (nsv->state == NSV_FOUND_NSVF) {
00527             err = nsv_parse_NSVf_header(s, ap);
00528             if (err < 0)
00529                 return err;
00530         }
00531             /* we need the first NSVs also... */
00532         if (nsv->state == NSV_FOUND_NSVS) {
00533             err = nsv_parse_NSVs_header(s, ap);
00534             if (err < 0)
00535                 return err;
00536             break; /* we just want the first one */
00537         }
00538     }
00539     if (s->nb_streams < 1) /* no luck so far */
00540         return -1;
00541     /* now read the first chunk, so we can attempt to decode more info */
00542     err = nsv_read_chunk(s, 1);
00543 
00544     av_dlog(s, "parsed header\n");
00545     return err;
00546 }
00547 
00548 static int nsv_read_chunk(AVFormatContext *s, int fill_header)
00549 {
00550     NSVContext *nsv = s->priv_data;
00551     AVIOContext *pb = s->pb;
00552     AVStream *st[2] = {NULL, NULL};
00553     NSVStream *nst;
00554     AVPacket *pkt;
00555     int i, err = 0;
00556     uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */
00557     uint32_t vsize;
00558     uint16_t asize;
00559     uint16_t auxsize;
00560     uint32_t av_unused auxtag;
00561 
00562     av_dlog(s, "%s(%d)\n", __FUNCTION__, fill_header);
00563 
00564     if (nsv->ahead[0].data || nsv->ahead[1].data)
00565         return 0; //-1; /* hey! eat what you've in your plate first! */
00566 
00567 null_chunk_retry:
00568     if (pb->eof_reached)
00569         return -1;
00570 
00571     for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++)
00572         err = nsv_resync(s);
00573     if (err < 0)
00574         return err;
00575     if (nsv->state == NSV_FOUND_NSVS)
00576         err = nsv_parse_NSVs_header(s, NULL);
00577     if (err < 0)
00578         return err;
00579     if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF)
00580         return -1;
00581 
00582     auxcount = avio_r8(pb);
00583     vsize = avio_rl16(pb);
00584     asize = avio_rl16(pb);
00585     vsize = (vsize << 4) | (auxcount >> 4);
00586     auxcount &= 0x0f;
00587     av_dlog(s, "NSV CHUNK %d aux, %u bytes video, %d bytes audio\n", auxcount, vsize, asize);
00588     /* skip aux stuff */
00589     for (i = 0; i < auxcount; i++) {
00590         auxsize = avio_rl16(pb);
00591         auxtag = avio_rl32(pb);
00592         av_dlog(s, "NSV aux data: '%c%c%c%c', %d bytes\n",
00593               (auxtag & 0x0ff),
00594               ((auxtag >> 8) & 0x0ff),
00595               ((auxtag >> 16) & 0x0ff),
00596               ((auxtag >> 24) & 0x0ff),
00597               auxsize);
00598         avio_skip(pb, auxsize);
00599         vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming braindead */
00600     }
00601 
00602     if (pb->eof_reached)
00603         return -1;
00604     if (!vsize && !asize) {
00605         nsv->state = NSV_UNSYNC;
00606         goto null_chunk_retry;
00607     }
00608 
00609     /* map back streams to v,a */
00610     if (s->nb_streams > 0)
00611         st[s->streams[0]->id] = s->streams[0];
00612     if (s->nb_streams > 1)
00613         st[s->streams[1]->id] = s->streams[1];
00614 
00615     if (vsize && st[NSV_ST_VIDEO]) {
00616         nst = st[NSV_ST_VIDEO]->priv_data;
00617         pkt = &nsv->ahead[NSV_ST_VIDEO];
00618         av_get_packet(pb, pkt, vsize);
00619         pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO;
00620         pkt->dts = nst->frame_offset;
00621         pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */
00622         for (i = 0; i < FFMIN(8, vsize); i++)
00623             av_dlog(s, "NSV video: [%d] = %02x\n", i, pkt->data[i]);
00624     }
00625     if(st[NSV_ST_VIDEO])
00626         ((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++;
00627 
00628     if (asize && st[NSV_ST_AUDIO]) {
00629         nst = st[NSV_ST_AUDIO]->priv_data;
00630         pkt = &nsv->ahead[NSV_ST_AUDIO];
00631         /* read raw audio specific header on the first audio chunk... */
00632         /* on ALL audio chunks ?? seems so! */
00633         if (asize && st[NSV_ST_AUDIO]->codec->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) {
00634             uint8_t bps;
00635             uint8_t channels;
00636             uint16_t samplerate;
00637             bps = avio_r8(pb);
00638             channels = avio_r8(pb);
00639             samplerate = avio_rl16(pb);
00640             asize-=4;
00641             av_dlog(s, "NSV RAWAUDIO: bps %d, nchan %d, srate %d\n", bps, channels, samplerate);
00642             if (fill_header) {
00643                 st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */
00644                 if (bps != 16) {
00645                     av_dlog(s, "NSV AUDIO bit/sample != 16 (%d)!!!\n", bps);
00646                 }
00647                 bps /= channels; // ???
00648                 if (bps == 8)
00649                     st[NSV_ST_AUDIO]->codec->codec_id = CODEC_ID_PCM_U8;
00650                 samplerate /= 4;/* UGH ??? XXX */
00651                 channels = 1;
00652                 st[NSV_ST_AUDIO]->codec->channels = channels;
00653                 st[NSV_ST_AUDIO]->codec->sample_rate = samplerate;
00654                 av_dlog(s, "NSV RAWAUDIO: bps %d, nchan %d, srate %d\n", bps, channels, samplerate);
00655             }
00656         }
00657         av_get_packet(pb, pkt, asize);
00658         pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO;
00659         pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */
00660         if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) {
00661             /* on a nsvs frame we have new information on a/v sync */
00662             pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1);
00663             pkt->dts *= (int64_t)1000        * nsv->framerate.den;
00664             pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num;
00665             av_dlog(s, "NSV AUDIO: sync:%d, dts:%"PRId64, nsv->avsync, pkt->dts);
00666         }
00667         nst->frame_offset++;
00668     }
00669 
00670     nsv->state = NSV_UNSYNC;
00671     return 0;
00672 }
00673 
00674 
00675 static int nsv_read_packet(AVFormatContext *s, AVPacket *pkt)
00676 {
00677     NSVContext *nsv = s->priv_data;
00678     int i, err = 0;
00679 
00680     av_dlog(s, "%s()\n", __FUNCTION__);
00681 
00682     /* in case we don't already have something to eat ... */
00683     if (nsv->ahead[0].data == NULL && nsv->ahead[1].data == NULL)
00684         err = nsv_read_chunk(s, 0);
00685     if (err < 0)
00686         return err;
00687 
00688     /* now pick one of the plates */
00689     for (i = 0; i < 2; i++) {
00690         if (nsv->ahead[i].data) {
00691             av_dlog(s, "%s: using cached packet[%d]\n", __FUNCTION__, i);
00692             /* avoid the cost of new_packet + memcpy(->data) */
00693             memcpy(pkt, &nsv->ahead[i], sizeof(AVPacket));
00694             nsv->ahead[i].data = NULL; /* we ate that one */
00695             return pkt->size;
00696         }
00697     }
00698 
00699     /* this restaurant is not approvisionned :^] */
00700     return -1;
00701 }
00702 
00703 static int nsv_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
00704 {
00705     NSVContext *nsv = s->priv_data;
00706     AVStream *st = s->streams[stream_index];
00707     NSVStream *nst = st->priv_data;
00708     int index;
00709 
00710     index = av_index_search_timestamp(st, timestamp, flags);
00711     if(index < 0)
00712         return -1;
00713 
00714     avio_seek(s->pb, st->index_entries[index].pos, SEEK_SET);
00715     nst->frame_offset = st->index_entries[index].timestamp;
00716     nsv->state = NSV_UNSYNC;
00717     return 0;
00718 }
00719 
00720 static int nsv_read_close(AVFormatContext *s)
00721 {
00722 /*     int i; */
00723     NSVContext *nsv = s->priv_data;
00724 
00725     av_freep(&nsv->nsvs_file_offset);
00726     av_freep(&nsv->nsvs_timestamps);
00727     if (nsv->ahead[0].data)
00728         av_free_packet(&nsv->ahead[0]);
00729     if (nsv->ahead[1].data)
00730         av_free_packet(&nsv->ahead[1]);
00731 
00732 #if 0
00733 
00734     for(i=0;i<s->nb_streams;i++) {
00735         AVStream *st = s->streams[i];
00736         NSVStream *ast = st->priv_data;
00737         if(ast){
00738             av_free(ast->index_entries);
00739             av_free(ast);
00740         }
00741         av_free(st->codec->palctrl);
00742     }
00743 
00744 #endif
00745     return 0;
00746 }
00747 
00748 static int nsv_probe(AVProbeData *p)
00749 {
00750     int i;
00751     int score;
00752     int vsize, asize, auxcount;
00753     score = 0;
00754     av_dlog(NULL, "nsv_probe(), buf_size %d\n", p->buf_size);
00755     /* check file header */
00756     /* streamed files might not have any header */
00757     if (p->buf[0] == 'N' && p->buf[1] == 'S' &&
00758         p->buf[2] == 'V' && (p->buf[3] == 'f' || p->buf[3] == 's'))
00759         return AVPROBE_SCORE_MAX;
00760     /* XXX: do streamed files always start at chunk boundary ?? */
00761     /* or do we need to search NSVs in the byte stream ? */
00762     /* seems the servers don't bother starting clean chunks... */
00763     /* sometimes even the first header is at 9KB or something :^) */
00764     for (i = 1; i < p->buf_size - 3; i++) {
00765         if (p->buf[i+0] == 'N' && p->buf[i+1] == 'S' &&
00766             p->buf[i+2] == 'V' && p->buf[i+3] == 's') {
00767             score = AVPROBE_SCORE_MAX/5;
00768             /* Get the chunk size and check if at the end we are getting 0xBEEF */
00769             auxcount = p->buf[i+19];
00770             vsize = p->buf[i+20]  | p->buf[i+21] << 8;
00771             asize = p->buf[i+22]  | p->buf[i+23] << 8;
00772             vsize = (vsize << 4) | (auxcount >> 4);
00773             if ((asize + vsize + i + 23) <  p->buf_size - 2) {
00774                 if (p->buf[i+23+asize+vsize+1] == 0xEF &&
00775                     p->buf[i+23+asize+vsize+2] == 0xBE)
00776                     return AVPROBE_SCORE_MAX-20;
00777             }
00778         }
00779     }
00780     /* so we'll have more luck on extension... */
00781     if (av_match_ext(p->filename, "nsv"))
00782         return AVPROBE_SCORE_MAX/2;
00783     /* FIXME: add mime-type check */
00784     return score;
00785 }
00786 
00787 AVInputFormat ff_nsv_demuxer = {
00788     "nsv",
00789     NULL_IF_CONFIG_SMALL("Nullsoft Streaming Video"),
00790     sizeof(NSVContext),
00791     nsv_probe,
00792     nsv_read_header,
00793     nsv_read_packet,
00794     nsv_read_close,
00795     nsv_read_seek,
00796 };