2 * "NUT" Container Format muxer and demuxer (DRAFT-200403??)
3 * Copyright (c) 2003 Alex Beregszaszi
4 * Copyright (c) 2004 Michael Niedermayer
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * NUT DRAFT can be found in MPlayer CVS at DOCS/tech/mpcf.txt
22 * AND http://people.fsn.hu/~alex/nut/ (TeX, pdf, ps, dvi, ..)
29 * - index packet reading support
36 #include "mpegaudio.h"
44 #define MAIN_STARTCODE (0x7A561F5F04ADULL + (((uint64_t)('N'<<8) + 'M')<<48))
45 #define STREAM_STARTCODE (0x11405BF2F9DBULL + (((uint64_t)('N'<<8) + 'S')<<48))
46 #define KEYFRAME_STARTCODE (0xE4ADEECA4569ULL + (((uint64_t)('N'<<8) + 'K')<<48))
47 #define INDEX_STARTCODE (0xDD672F23E64EULL + (((uint64_t)('N'<<8) + 'X')<<48))
48 #define INFO_STARTCODE (0xAB68B596BA78ULL + (((uint64_t)('N'<<8) + 'I')<<48))
50 #define MAX_TYPE1_DISTANCE (1024*16-1)
51 #define MAX_TYPE2_DISTANCE (1024*64-1)
53 #define MAX_SIZE_LRU 2
56 #define FLAG_FRAME_TYPE 1
57 #define FLAG_DATA_SIZE 2
59 #define FLAG_FULL_PTS 4
60 #define FLAG_KEY_FRAME 32
64 uint8_t stream_id_plus1;
71 int msb_timestamp_shift;
75 int64_t last_full_pts;
76 int lru_pts_delta[MAX_PTS_LRU];
77 int lru_size[MAX_SIZE_LRU];
78 int initial_pts_predictor[MAX_PTS_LRU];
79 int initial_size_predictor[MAX_SIZE_LRU];
80 int64_t last_sync_pos; ///<pos of last 1/2 type frame
86 int64_t last_packet_start;
87 int written_packet_size;
88 int64_t packet_size_pos;
89 int64_t last_frame_start[3];
90 FrameCode frame_code[256];
92 uint64_t next_startcode; ///< stores the next startcode if it has alraedy been parsed but the stream isnt seekable
93 StreamContext *stream;
96 static char *info_table[][2]={
97 {NULL , NULL }, // end
104 {"StartTimestamp" , "v"},
105 {"EndTimestamp" , "v"},
108 {"Description" , "UTF8"},
109 {"Copyright" , "UTF8"},
110 {"Encoder" , "UTF8"},
111 {"Keyword" , "UTF8"},
116 static void update_lru(int *lru, int current, int count){
119 for(i=0; i<count-1; i++){
120 if(lru[i] == current)
131 static void update(NUTContext *nut, int stream_index, int64_t frame_start, int frame_type, int frame_code, int key_frame, int size, int64_t pts){
132 StreamContext *stream= &nut->stream[stream_index];
133 const int flags=nut->frame_code[frame_code].flags;
135 stream->last_key_frame= key_frame;
136 nut->last_frame_start[ frame_type ]= frame_start;
138 update_lru(stream->lru_pts_delta, pts - stream->last_pts, 3);
139 update_lru(stream->lru_size, size, 2);
140 stream->last_pts= pts;
141 if((flags & FLAG_PTS) && (flags & FLAG_FULL_PTS))
142 stream->last_full_pts= pts;
145 static void reset(AVFormatContext *s/*, int frame_type*/){
146 NUTContext *nut = s->priv_data;
149 for(i=0; i<s->nb_streams; i++){
150 StreamContext *stream= &nut->stream[i];
152 stream->last_key_frame= 1;
153 memcpy(stream->lru_pts_delta, stream->initial_pts_predictor, sizeof(int)*MAX_PTS_LRU);
154 memcpy(stream->lru_size, stream->initial_size_predictor, sizeof(int)*MAX_SIZE_LRU);
158 static void build_frame_code(AVFormatContext *s){
159 NUTContext *nut = s->priv_data;
160 int key_frame, frame_type, full_pts, index, pred, stream_id;
163 int keyframe_0_esc= s->nb_streams > 2;
166 /* keyframe = 0 escapes, 3 codes */
167 for(frame_type=0; frame_type<2; frame_type++){
168 for(full_pts=frame_type; full_pts<2; full_pts++){
169 FrameCode *ft= &nut->frame_code[start];
170 ft->flags= FLAG_FRAME_TYPE*frame_type + FLAG_FULL_PTS*full_pts;
171 ft->flags|= FLAG_DATA_SIZE | FLAG_PTS;
172 ft->stream_id_plus1= 0;
179 for(stream_id= 0; stream_id<s->nb_streams; stream_id++){
180 int start2= start + (end-start)*stream_id / s->nb_streams;
181 int end2 = start + (end-start)*(stream_id+1) / s->nb_streams;
182 AVCodecContext *codec = &s->streams[stream_id]->codec;
183 int is_audio= codec->codec_type == CODEC_TYPE_AUDIO;
184 int intra_only= /*codec->intra_only || */is_audio;
187 for(key_frame=0; key_frame<2; key_frame++){
188 if(intra_only && keyframe_0_esc && key_frame==0)
191 for(frame_type=0; frame_type<2; frame_type++){
192 for(full_pts=frame_type; full_pts<2; full_pts++){
193 FrameCode *ft= &nut->frame_code[start2];
194 ft->flags= FLAG_FRAME_TYPE*frame_type + FLAG_FULL_PTS*full_pts + FLAG_KEY_FRAME*key_frame;
195 ft->flags|= FLAG_DATA_SIZE | FLAG_PTS;
196 ft->stream_id_plus1= stream_id + 1;
203 key_frame= intra_only;
206 int frame_bytes= codec->frame_size*(int64_t)codec->bit_rate / (8*codec->sample_rate);
207 for(pred=0; pred<MAX_SIZE_LRU; pred++){
208 for(frame_type=0; frame_type<1; frame_type++){
209 FrameCode *ft= &nut->frame_code[start2];
210 ft->flags= FLAG_KEY_FRAME*key_frame + (FLAG_FULL_PTS+FLAG_PTS+FLAG_FRAME_TYPE)*frame_type;
211 ft->stream_id_plus1= stream_id + 1;
213 ft->size_lsb=1 + pred;
216 nut->stream[stream_id].initial_size_predictor[pred]= frame_bytes + pred;
219 FrameCode *ft= &nut->frame_code[start2];
220 ft->flags= FLAG_KEY_FRAME | FLAG_DATA_SIZE;
221 ft->stream_id_plus1= stream_id + 1;
226 pred_count= 2 + codec->has_b_frames + (codec->codec_id == CODEC_ID_VORBIS);
227 for(pred=0; pred<pred_count; pred++){
228 int start3= start2 + (end2-start2)*pred / pred_count;
229 int end3 = start2 + (end2-start2)*(pred+1) / pred_count;
231 for(index=start3; index<end3; index++){
232 FrameCode *ft= &nut->frame_code[index];
233 ft->flags= FLAG_KEY_FRAME*key_frame + pred*4;
234 ft->flags|= FLAG_DATA_SIZE;
235 ft->stream_id_plus1= stream_id + 1;
236 //FIXME use single byte size and pred from last
237 ft->size_mul= end3-start3;
238 ft->size_lsb= index - start3;
240 nut->stream[stream_id].initial_pts_predictor[pred]= pred+1;
243 memmove(&nut->frame_code['N'+1], &nut->frame_code['N'], sizeof(FrameCode)*(255-'N'));
244 nut->frame_code['N'].flags= 1;
247 static uint64_t get_v(ByteIOContext *bc)
253 int tmp = get_byte(bc);
256 val= (val<<7) + tmp - 0x80;
258 return (val<<7) + tmp;
263 static int get_str(ByteIOContext *bc, char *string, int maxlen){
267 get_buffer(bc, string, FFMIN(len, maxlen));
274 string[FFMIN(len, maxlen-1)]= 0;
282 static uint64_t get_vb(ByteIOContext *bc){
290 val = (val<<8) + get_byte(bc);
295 static int get_packetheader(NUTContext *nut, ByteIOContext *bc, int prefix_length, int calculate_checksum)
297 int64_t start, size, last_size;
298 start= url_ftell(bc) - prefix_length;
300 if(nut->written_packet_size >= 0 && start != nut->packet_start + nut->written_packet_size){
301 av_log(nut->avf, AV_LOG_ERROR, "get_packetheader called at weird position\n");
306 init_checksum(bc, calculate_checksum ? update_adler32 : NULL, 0);
309 last_size= get_v(bc);
310 if(nut->written_packet_size >= 0 && nut->written_packet_size != last_size){
311 av_log(nut->avf, AV_LOG_ERROR, "packet size missmatch %d != %lld at %lld\n", nut->written_packet_size, last_size, start);
316 nut->last_packet_start = nut->packet_start;
317 nut->packet_start = start;
318 nut->written_packet_size= size;
323 static int check_checksum(ByteIOContext *bc){
324 unsigned long checksum= get_checksum(bc);
325 return checksum != get_be32(bc);
331 static int get_length(uint64_t val){
334 for (i=7; val>>i; i+=7);
339 static uint64_t find_any_startcode(ByteIOContext *bc, int64_t pos){
343 url_fseek(bc, pos, SEEK_SET); //note, this may fail if the stream isnt seekable, but that shouldnt matter, as in this case we simply start where we are currently
345 while(!url_feof(bc)){
346 state= (state<<8) | get_byte(bc);
347 if((state>>56) != 'N')
351 case STREAM_STARTCODE:
352 case KEYFRAME_STARTCODE:
354 case INDEX_STARTCODE:
363 * find the given startcode.
364 * @param code the startcode
365 * @param pos the start position of the search, or -1 if the current position
366 * @returns the position of the startcode or -1 if not found
368 static int64_t find_startcode(ByteIOContext *bc, uint64_t code, int64_t pos){
370 uint64_t startcode= find_any_startcode(bc, pos);
371 if(startcode == code)
372 return url_ftell(bc) - 8;
373 else if(startcode == 0)
379 #ifdef CONFIG_ENCODERS
380 static void put_v(ByteIOContext *bc, uint64_t val)
384 val &= 0x7FFFFFFFFFFFFFFFULL; // FIXME can only encode upto 63 bits currently
387 for (i-=7; i>0; i-=7){
388 put_byte(bc, 0x80 | (val>>i));
391 put_byte(bc, val&0x7f);
395 * stores a string as vb.
397 static void put_str(ByteIOContext *bc, const char *string){
398 int len= strlen(string);
401 put_buffer(bc, string, len);
404 static void put_vb(ByteIOContext *bc, uint64_t val){
407 for (i=8; val>>i; i+=8);
410 for(i-=8; i>=0; i-=8)
411 put_byte(bc, (val>>i)&0xFF);
414 static int put_packetheader(NUTContext *nut, ByteIOContext *bc, int max_size, int calculate_checksum)
416 put_flush_packet(bc);
417 nut->last_packet_start= nut->packet_start;
418 nut->packet_start+= nut->written_packet_size;
419 nut->packet_size_pos = url_ftell(bc);
420 nut->written_packet_size = max_size;
422 if(calculate_checksum)
423 init_checksum(bc, update_adler32, 0);
426 put_v(bc, nut->written_packet_size); /* forward ptr */
427 put_v(bc, nut->packet_start - nut->last_packet_start); /* backward ptr */
432 static int update_packetheader(NUTContext *nut, ByteIOContext *bc, int additional_size, int calculate_checksum){
433 int64_t start= nut->packet_start;
434 int64_t cur= url_ftell(bc);
435 int size= cur - start + additional_size;
437 if(calculate_checksum)
440 if(size != nut->written_packet_size){
443 assert( size <= nut->written_packet_size );
445 url_fseek(bc, nut->packet_size_pos, SEEK_SET);
446 for(i=get_length(size); i < get_length(nut->written_packet_size); i+=7)
450 url_fseek(bc, cur, SEEK_SET);
451 nut->written_packet_size= size; //FIXME may fail if multiple updates with differing sizes, as get_length may differ
453 if(calculate_checksum)
454 put_be32(bc, get_checksum(bc));
460 static int nut_write_header(AVFormatContext *s)
462 NUTContext *nut = s->priv_data;
463 ByteIOContext *bc = &s->pb;
464 AVCodecContext *codec;
470 av_mallocz(sizeof(StreamContext)*s->nb_streams);
472 av_set_pts_info(s, 60, 1, AV_TIME_BASE);
475 put_be64(bc, MAIN_STARTCODE);
476 put_packetheader(nut, bc, 120+5*256, 1);
477 put_v(bc, 1); /* version */
478 put_v(bc, s->nb_streams);
481 assert(nut->frame_code['N'].flags == 1);
483 int tmp_flags = nut->frame_code[i].flags;
484 int tmp_stream= nut->frame_code[i].stream_id_plus1;
485 int tmp_mul = nut->frame_code[i].size_mul;
486 int tmp_size = nut->frame_code[i].size_lsb;
487 put_v(bc, tmp_flags);
488 put_v(bc, tmp_stream);
492 for(j=0; i<256; j++,i++){
493 if(nut->frame_code[i].flags != tmp_flags ) break;
494 if(nut->frame_code[i].stream_id_plus1 != tmp_stream) break;
495 if(nut->frame_code[i].size_mul != tmp_mul ) break;
496 if(nut->frame_code[i].size_lsb != tmp_size ) break;
497 if(++tmp_size >= tmp_mul){
505 update_packetheader(nut, bc, 0, 1);
508 for (i = 0; i < s->nb_streams; i++)
512 codec = &s->streams[i]->codec;
514 put_be64(bc, STREAM_STARTCODE);
515 put_packetheader(nut, bc, 120 + codec->extradata_size, 1);
516 put_v(bc, i /*s->streams[i]->index*/);
517 put_v(bc, (codec->codec_type == CODEC_TYPE_AUDIO) ? 32 : 0);
518 if (codec->codec_tag)
519 put_vb(bc, codec->codec_tag);
520 else if (codec->codec_type == CODEC_TYPE_VIDEO)
522 put_vb(bc, codec_get_bmp_tag(codec->codec_id));
524 else if (codec->codec_type == CODEC_TYPE_AUDIO)
526 put_vb(bc, codec_get_wav_tag(codec->codec_id));
531 if (codec->codec_type == CODEC_TYPE_VIDEO)
533 nom = codec->frame_rate;
534 denom = codec->frame_rate_base;
538 nom = codec->sample_rate;
539 if(codec->frame_size>0)
540 denom= codec->frame_size;
544 gcd= ff_gcd(nom, denom);
547 nut->stream[i].rate_num= nom;
548 nut->stream[i].rate_den= denom;
550 put_v(bc, codec->bit_rate);
551 put_vb(bc, 0); /* no language code */
554 if(nom / denom < 1000)
555 nut->stream[i].msb_timestamp_shift = 7;
557 nut->stream[i].msb_timestamp_shift = 14;
558 put_v(bc, nut->stream[i].msb_timestamp_shift);
560 put_v(bc, nut->stream[i].initial_pts_predictor[j]);
562 put_v(bc, nut->stream[i].initial_size_predictor[j]);
563 put_byte(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
565 if(codec->extradata_size){
567 put_v(bc, codec->extradata_size);
568 put_buffer(bc, codec->extradata, codec->extradata_size);
570 put_v(bc, 0); /* end of codec specific headers */
572 switch(codec->codec_type)
574 case CODEC_TYPE_AUDIO:
575 put_v(bc, (codec->sample_rate * denom) / nom);
576 put_v(bc, codec->channels);
578 case CODEC_TYPE_VIDEO:
579 put_v(bc, codec->width);
580 put_v(bc, codec->height);
581 put_v(bc, codec->sample_aspect_ratio.num);
582 put_v(bc, codec->sample_aspect_ratio.den);
583 put_v(bc, 0); /* csp type -- unknown */
588 update_packetheader(nut, bc, 0, 1);
592 put_be64(bc, INFO_STARTCODE);
593 put_packetheader(nut, bc, 30+strlen(s->author)+strlen(s->title)+
594 strlen(s->comment)+strlen(s->copyright)+strlen(LIBAVFORMAT_IDENT), 1);
597 put_v(bc, 9); /* type */
598 put_str(bc, s->author);
602 put_v(bc, 10); /* type */
603 put_str(bc, s->title);
607 put_v(bc, 11); /* type */
608 put_str(bc, s->comment);
612 put_v(bc, 12); /* type */
613 put_str(bc, s->copyright);
616 put_v(bc, 13); /* type */
617 put_str(bc, LIBAVFORMAT_IDENT);
619 put_v(bc, 0); /* eof info */
620 update_packetheader(nut, bc, 0, 1);
622 put_flush_packet(bc);
627 static int nut_write_packet(AVFormatContext *s, int stream_index,
628 const uint8_t *buf, int size, int64_t pts)
630 NUTContext *nut = s->priv_data;
631 StreamContext *stream= &nut->stream[stream_index];
632 ByteIOContext *bc = &s->pb;
633 int key_frame = 0, full_pts=0;
635 int64_t lsb_pts, delta_pts;
636 int frame_type, best_length, frame_code, flags, i, size_mul, size_lsb;
637 const int64_t frame_start= url_ftell(bc);
639 if (stream_index > s->nb_streams)
642 pts= (av_rescale(pts, stream->rate_num, stream->rate_den) + AV_TIME_BASE/2) / AV_TIME_BASE;
644 enc = &s->streams[stream_index]->codec;
645 key_frame = enc->coded_frame->key_frame;
646 delta_pts= pts - stream->last_pts;
649 if(frame_start + size + 20 - FFMAX(nut->last_frame_start[1], nut->last_frame_start[2]) > MAX_TYPE1_DISTANCE)
652 if(frame_type==1 && frame_start + size - nut->last_frame_start[2] > MAX_TYPE2_DISTANCE)
654 if(!stream->last_key_frame)
659 update_packetheader(nut, bc, 0, 0);
663 //FIXME ensure that the timestamp can be represented by either delta or lsb or full_pts=1
665 lsb_pts = pts & ((1 << stream->msb_timestamp_shift)-1);
669 for(i=0; i<256; i++){
670 int stream_id_plus1= nut->frame_code[i].stream_id_plus1;
673 size_mul= nut->frame_code[i].size_mul;
674 size_lsb= nut->frame_code[i].size_lsb;
675 flags= nut->frame_code[i].flags;
677 if(stream_id_plus1 == 0) length+= get_length(stream_index);
678 else if(stream_id_plus1 - 1 != stream_index)
680 fc_key_frame= !!(flags & FLAG_KEY_FRAME);
682 assert(key_frame==0 || key_frame==1);
683 if(fc_key_frame != key_frame)
686 if((!!(flags & FLAG_FRAME_TYPE)) != (frame_type > 0))
689 if(size_mul <= size_lsb){
690 int p= stream->lru_size[size_lsb - size_mul];
694 if(size % size_mul != size_lsb)
696 if(flags & FLAG_DATA_SIZE)
697 length += get_length(size / size_mul);
698 else if(size/size_mul)
702 if(full_pts != ((flags & FLAG_PTS) && (flags & FLAG_FULL_PTS)))
706 if(flags&FLAG_FULL_PTS){
707 length += get_length(pts);
709 length += get_length(lsb_pts);
712 int delta= stream->lru_pts_delta[(flags & 12)>>2];
713 if(delta != pts - stream->last_pts)
715 assert(frame_type == 0);
718 if(length < best_length){
722 // av_log(s, AV_LOG_DEBUG, "%d %d %d %d %d %d %d %d %d %d\n", key_frame, frame_type, full_pts, size, stream_index, flags, size_mul, size_lsb, stream_id_plus1, length);
725 assert(frame_code != -1);
726 flags= nut->frame_code[frame_code].flags;
727 size_mul= nut->frame_code[frame_code].size_mul;
728 size_lsb= nut->frame_code[frame_code].size_lsb;
731 best_length ++; //frame_code
733 best_length += 4; //packet header
735 best_length += 8; // startcode
737 av_log(s, AV_LOG_DEBUG, "kf:%d ft:%d pt:%d fc:%2X len:%2d size:%d stream:%d flag:%d mul:%d lsb:%d s+1:%d pts_delta:%d\n", key_frame, frame_type, full_pts ? 2 : ((flags & FLAG_PTS) ? 1 : 0), frame_code, best_length, size, stream_index, flags, size_mul, size_lsb, nut->frame_code[frame_code].stream_id_plus1,(int)(pts - stream->last_pts));
741 put_be64(bc, KEYFRAME_STARTCODE);
742 put_byte(bc, frame_code);
745 put_packetheader(nut, bc, FFMAX(size+20, MAX_TYPE1_DISTANCE), 0);
746 if(nut->frame_code[frame_code].stream_id_plus1 == 0)
747 put_v(bc, stream_index);
748 if (flags & FLAG_PTS){
749 if (flags & FLAG_FULL_PTS)
754 if(flags & FLAG_DATA_SIZE)
755 put_v(bc, size / size_mul);
756 if(size > MAX_TYPE1_DISTANCE){
757 assert(frame_type > 0);
758 update_packetheader(nut, bc, size, 0);
761 put_buffer(bc, buf, size);
763 update(nut, stream_index, frame_start, frame_type, frame_code, key_frame, size, pts);
768 static int nut_write_trailer(AVFormatContext *s)
770 NUTContext *nut = s->priv_data;
771 ByteIOContext *bc = &s->pb;
773 update_packetheader(nut, bc, 0, 0);
780 for (i = 0; s->nb_streams; i++)
782 put_be64(bc, INDEX_STARTCODE);
783 put_packetheader(nut, bc, 64, 1);
784 put_v(bc, s->streams[i]->id);
786 update_packetheader(nut, bc, 0, 1);
790 put_flush_packet(bc);
792 av_freep(&nut->stream);
796 #endif //CONFIG_ENCODERS
798 static int nut_probe(AVProbeData *p)
804 for (i = 0; i < p->buf_size; i++) {
806 code = (code << 8) | c;
807 if (code == MAIN_STARTCODE)
808 return AVPROBE_SCORE_MAX;
813 static int decode_main_header(NUTContext *nut){
814 AVFormatContext *s= nut->avf;
815 ByteIOContext *bc = &s->pb;
819 get_packetheader(nut, bc, 8, 1);
823 av_log(s, AV_LOG_ERROR, "bad version (%Ld)\n", tmp);
827 nut->stream_count = get_v(bc);
830 int tmp_flags = get_v(bc);
831 int tmp_stream= get_v(bc);
832 int tmp_mul = get_v(bc);
833 int tmp_size = get_v(bc);
834 int count = get_v(bc);
836 if(count == 0 || i+count > 256){
837 av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
841 if((tmp_flags & FLAG_FRAME_TYPE) && tmp_flags != 1){
842 if(!(tmp_flags & FLAG_PTS) || !(tmp_flags & FLAG_FULL_PTS) ){
843 av_log(s, AV_LOG_ERROR, "no full pts in non 0 frame type\n");
848 for(j=0; j<count; j++,i++){
849 if(tmp_stream > nut->stream_count + 1){
850 av_log(s, AV_LOG_ERROR, "illegal stream number\n");
854 nut->frame_code[i].flags = tmp_flags ;
855 nut->frame_code[i].stream_id_plus1 = tmp_stream;
856 nut->frame_code[i].size_mul = tmp_mul ;
857 nut->frame_code[i].size_lsb = tmp_size ;
858 if(++tmp_size >= tmp_mul){
864 if(nut->frame_code['N'].flags != 1){
865 av_log(s, AV_LOG_ERROR, "illegal frame_code table\n");
869 if(check_checksum(bc)){
870 av_log(s, AV_LOG_ERROR, "Main header checksum missmatch\n");
877 static int decode_stream_header(NUTContext *nut){
878 AVFormatContext *s= nut->avf;
879 ByteIOContext *bc = &s->pb;
880 int class, nom, denom, stream_id, i;
884 get_packetheader(nut, bc, 8, 1);
885 stream_id= get_v(bc);
886 if(stream_id >= nut->stream_count || s->streams[stream_id])
889 st = av_new_stream(s, stream_id);
891 return AVERROR_NOMEM;
897 st->codec.codec_type = CODEC_TYPE_VIDEO;
898 st->codec.codec_id = codec_get_bmp_id(tmp);
899 if (st->codec.codec_id == CODEC_ID_NONE)
900 av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");
903 st->codec.codec_type = CODEC_TYPE_AUDIO;
904 st->codec.codec_id = codec_get_wav_id(tmp);
905 if (st->codec.codec_id == CODEC_ID_NONE)
906 av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");
909 av_log(s, AV_LOG_ERROR, "Unknown stream class (%d)\n", class);
912 s->bit_rate += get_v(bc);
913 get_vb(bc); /* language code */
916 nut->stream[stream_id].msb_timestamp_shift = get_v(bc);
918 nut->stream[stream_id].initial_pts_predictor[i]= get_v(bc);
920 nut->stream[stream_id].initial_size_predictor[i]= get_v(bc);
921 get_byte(bc); /* flags */
923 /* codec specific data headers */
924 while(get_v(bc) != 0){
925 st->codec.extradata_size= get_v(bc);
926 st->codec.extradata= av_mallocz(st->codec.extradata_size);
927 get_buffer(bc, st->codec.extradata, st->codec.extradata_size);
928 // url_fskip(bc, get_v(bc));
931 if (class == 0) /* VIDEO */
933 st->codec.width = get_v(bc);
934 st->codec.height = get_v(bc);
935 st->codec.sample_aspect_ratio.num= get_v(bc);
936 st->codec.sample_aspect_ratio.den= get_v(bc);
937 get_v(bc); /* csp type */
939 st->codec.frame_rate = nom;
940 st->codec.frame_rate_base = denom;
942 if (class == 32) /* AUDIO */
944 st->codec.sample_rate = (get_v(bc) * nom) / denom;
945 st->codec.channels = get_v(bc);
947 if(check_checksum(bc)){
948 av_log(s, AV_LOG_ERROR, "Stream header %d checksum missmatch\n", stream_id);
951 nut->stream[stream_id].rate_num= nom;
952 nut->stream[stream_id].rate_den= denom;
956 static int decode_info_header(NUTContext *nut){
957 AVFormatContext *s= nut->avf;
958 ByteIOContext *bc = &s->pb;
960 get_packetheader(nut, bc, 8, 1);
964 char *name, *type, custom_name[256], custom_type[256];
968 else if(id >= sizeof(info_table)/sizeof(info_table[0])){
969 av_log(s, AV_LOG_ERROR, "info id is too large %d %d\n", id, sizeof(info_table)/sizeof(info_table[0]));
973 type= info_table[id][1];
974 name= info_table[id][0];
975 //av_log(s, AV_LOG_DEBUG, "%d %s %s\n", id, type, name);
978 get_str(bc, custom_type, sizeof(custom_type));
982 get_str(bc, custom_name, sizeof(custom_name));
986 if(!strcmp(type, "v")){
987 int value= get_v(bc);
989 if(!strcmp(name, "Author"))
990 get_str(bc, s->author, sizeof(s->author));
991 else if(!strcmp(name, "Title"))
992 get_str(bc, s->title, sizeof(s->title));
993 else if(!strcmp(name, "Copyright"))
994 get_str(bc, s->copyright, sizeof(s->copyright));
995 else if(!strcmp(name, "Description"))
996 get_str(bc, s->comment, sizeof(s->comment));
998 get_str(bc, NULL, 0);
1001 if(check_checksum(bc)){
1002 av_log(s, AV_LOG_ERROR, "Info header checksum missmatch\n");
1008 static int nut_read_header(AVFormatContext *s, AVFormatParameters *ap)
1010 NUTContext *nut = s->priv_data;
1011 ByteIOContext *bc = &s->pb;
1013 int inited_stream_count;
1017 av_set_pts_info(s, 60, 1, AV_TIME_BASE);
1022 pos= find_startcode(bc, MAIN_STARTCODE, pos)+1;
1024 av_log(s, AV_LOG_ERROR, "no main startcode found\n");
1027 if(decode_main_header(nut) >= 0)
1034 nut->stream = av_malloc(sizeof(StreamContext)*nut->stream_count);
1036 /* stream headers */
1038 for(inited_stream_count=0; inited_stream_count < nut->stream_count;){
1039 pos= find_startcode(bc, STREAM_STARTCODE, pos)+1;
1041 av_log(s, AV_LOG_ERROR, "not all stream headers found\n");
1044 if(decode_stream_header(nut) >= 0)
1045 inited_stream_count++;
1051 uint64_t startcode= find_any_startcode(bc, pos);
1055 av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
1057 }else if(startcode == KEYFRAME_STARTCODE){
1058 nut->next_startcode= startcode;
1060 }else if(startcode != INFO_STARTCODE){
1064 decode_info_header(nut);
1070 static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code, int frame_type){
1071 AVFormatContext *s= nut->avf;
1072 StreamContext *stream;
1073 ByteIOContext *bc = &s->pb;
1074 int size, flags, size_mul, size_lsb, stream_id;
1077 const int prefix_len= frame_type == 2 ? 8+1 : 1;
1078 const int64_t frame_start= url_ftell(bc) - prefix_len;
1080 flags= nut->frame_code[frame_code].flags;
1081 size_mul= nut->frame_code[frame_code].size_mul;
1082 size_lsb= nut->frame_code[frame_code].size_lsb;
1083 stream_id= nut->frame_code[frame_code].stream_id_plus1 - 1;
1085 if(flags & FLAG_FRAME_TYPE){
1087 if(get_packetheader(nut, bc, prefix_len, 0) < 0)
1094 stream_id= get_v(bc);
1095 if(stream_id >= s->nb_streams){
1096 av_log(s, AV_LOG_ERROR, "illegal stream_id\n");
1099 stream= &nut->stream[stream_id];
1101 // av_log(s, AV_LOG_DEBUG, "ft:%d ppts:%d %d %d\n", frame_type, stream->lru_pts_delta[0], stream->lru_pts_delta[1], stream->lru_pts_delta[2]);
1103 key_frame= !!(flags & FLAG_KEY_FRAME);
1105 if(flags & FLAG_PTS){
1106 if(flags & FLAG_FULL_PTS){
1108 if(frame_type && key_frame){
1110 s->streams[stream_id],
1113 frame_start - nut->stream[stream_id].last_sync_pos,
1115 nut->stream[stream_id].last_sync_pos= frame_start;
1116 assert(nut->packet_start == frame_start);
1119 int64_t mask = (1<<stream->msb_timestamp_shift)-1;
1120 int64_t delta= stream->last_pts - mask/2;
1121 pts= ((get_v(bc) - delta)&mask) + delta;
1124 pts= stream->last_pts + stream->lru_pts_delta[(flags&12)>>2];
1127 if(size_mul <= size_lsb){
1128 size= stream->lru_size[size_lsb - size_mul];
1130 if(flags & FLAG_DATA_SIZE)
1131 size= size_mul*get_v(bc) + size_lsb;
1136 //av_log(s, AV_LOG_DEBUG, "fs:%lld fc:%d ft:%d kf:%d pts:%lld size:%d\n", frame_start, frame_code, frame_type, key_frame, pts, size);
1138 if(url_ftell(bc) - nut->packet_start + size > nut->written_packet_size){
1139 av_log(s, AV_LOG_ERROR, "frame size too large\n");
1143 av_new_packet(pkt, size);
1144 get_buffer(bc, pkt->data, size);
1145 pkt->stream_index = stream_id;
1147 pkt->flags |= PKT_FLAG_KEY;
1148 pkt->pts = pts * AV_TIME_BASE * stream->rate_den / stream->rate_num;
1150 update(nut, stream_id, frame_start, frame_type, frame_code, key_frame, size, pts);
1155 static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
1157 NUTContext *nut = s->priv_data;
1158 ByteIOContext *bc = &s->pb;
1159 int size, i, frame_code=0;
1164 uint64_t tmp= nut->next_startcode;
1165 nut->next_startcode=0;
1171 frame_code = get_byte(bc);
1172 if(frame_code == 'N'){
1175 tmp = (tmp<<8) + get_byte(bc);
1179 case MAIN_STARTCODE:
1180 case STREAM_STARTCODE:
1181 case INDEX_STARTCODE:
1182 get_packetheader(nut, bc, 8, 0);
1183 url_fseek(bc, nut->written_packet_size + nut->packet_start, SEEK_SET);
1185 case INFO_STARTCODE:
1186 if(decode_info_header(nut)<0)
1189 case KEYFRAME_STARTCODE:
1191 frame_code = get_byte(bc);
1193 if(decode_frame(nut, pkt, frame_code, frame_type)>=0)
1197 av_log(s, AV_LOG_DEBUG, "syncing from %lld\n", nut->packet_start+1);
1198 tmp= find_any_startcode(bc, nut->packet_start+1);
1201 av_log(s, AV_LOG_DEBUG, "sync\n");
1202 if(url_is_streamed(bc)){
1203 nut->next_startcode= tmp;
1207 pos= url_ftell(bc) - 8;
1208 av_log(s, AV_LOG_DEBUG, "at %lld code=%llX\n", pos, tmp);
1209 if(tmp==KEYFRAME_STARTCODE){
1215 while(size > 2 && size < 100000 && nut->packet_start < pos - size){
1216 url_fseek(bc, pos - size, SEEK_SET);
1217 frame_code= get_byte(bc);
1218 if(!(nut->frame_code[ frame_code ].flags & FLAG_FRAME_TYPE))
1220 if(get_v(bc) != size)
1224 av_log(s, AV_LOG_DEBUG, "steping back to %lld next %d\n", pos, size);
1226 url_fseek(bc, pos, SEEK_SET);
1228 nut->written_packet_size= -1;
1233 static int64_t read_timestamp(AVFormatContext *s, int stream_index, int64_t *pos_arg, int64_t pos_limit){
1234 NUTContext *nut = s->priv_data;
1235 ByteIOContext *bc = &s->pb;
1238 int frame_code,step, flags, stream_id, i;
1239 av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%lld,%lld)\n", stream_index, *pos_arg, pos_limit);
1242 return AV_NOPTS_VALUE;
1244 // find a previous startcode, FIXME use forward search and follow backward pointers if undamaged stream
1246 step= FFMIN(16*1024, pos);
1249 code= find_any_startcode(bc, pos);
1251 if(code && url_ftell(bc) - 8 < *pos_arg)
1253 step= FFMIN(2*step, pos);
1256 if(!code) //nothing found, not even after pos_arg
1257 return AV_NOPTS_VALUE;
1259 url_fseek(bc, -8, SEEK_CUR);
1260 for(i=0; i<s->nb_streams; i++)
1261 nut->stream[i].last_sync_pos= url_ftell(bc);
1264 int64_t pos= url_ftell(bc);
1269 return AV_NOPTS_VALUE;
1271 frame_code = get_byte(bc);
1272 if(frame_code == 'N'){
1275 tmp = (tmp<<8) + get_byte(bc);
1277 //av_log(s, AV_LOG_DEBUG, "before switch %llX at=%lld\n", tmp, pos);
1280 case MAIN_STARTCODE:
1281 case STREAM_STARTCODE:
1282 case INDEX_STARTCODE:
1283 case INFO_STARTCODE:
1284 nut->written_packet_size= -1;
1285 get_packetheader(nut, bc, 8, 0);
1286 url_fseek(bc, nut->written_packet_size + nut->packet_start, SEEK_SET);
1288 case KEYFRAME_STARTCODE:
1289 nut->written_packet_size= -1;
1291 frame_code = get_byte(bc);
1293 flags= nut->frame_code[frame_code].flags;
1294 stream_id= nut->frame_code[frame_code].stream_id_plus1 - 1;
1296 if(get_packetheader(nut, bc, prefix_len, 0) < 0)
1299 if(!(flags & FLAG_FRAME_TYPE) || !(flags & FLAG_PTS) || !(flags & FLAG_FULL_PTS))
1303 stream_id= get_v(bc);
1304 if(stream_id >= s->nb_streams)
1309 if(flags & FLAG_KEY_FRAME){
1311 s->streams[stream_id],
1314 pos - nut->stream[stream_id].last_sync_pos,
1316 nut->stream[stream_id].last_sync_pos= pos;
1318 if(stream_id != stream_index || !(flags & FLAG_KEY_FRAME) || nut->packet_start < *pos_arg){
1319 url_fseek(bc, nut->written_packet_size + nut->packet_start, SEEK_SET);
1323 *pos_arg= nut->packet_start;
1324 assert(nut->packet_start == pos);
1328 av_log(s, AV_LOG_DEBUG, "syncing from %lld\n", nut->packet_start+1);
1329 if(!find_any_startcode(bc, nut->packet_start+1))
1330 return AV_NOPTS_VALUE;
1332 url_fseek(bc, -8, SEEK_CUR);
1335 return AV_NOPTS_VALUE;
1339 static int nut_read_seek(AVFormatContext *s, int stream_index, int64_t target_ts){
1340 NUTContext *nut = s->priv_data;
1341 StreamContext *stream;
1342 int64_t pos_min, pos_max, pos, pos_limit;
1343 int64_t ts_min, ts_max, ts;
1345 int index, no_change,i;
1348 if (stream_index < 0) {
1349 stream_index = av_find_default_stream_index(s);
1350 if (stream_index < 0)
1353 stream= &nut->stream[stream_index];
1354 target_ts= (av_rescale(target_ts, stream->rate_num, stream->rate_den) + AV_TIME_BASE/2) / AV_TIME_BASE;
1357 av_log(s, AV_LOG_DEBUG, "read_seek: %d %lld\n", stream_index, target_ts);
1361 ts_min= AV_NOPTS_VALUE;
1362 pos_limit= -1; //gcc falsely says it may be uninitalized
1364 st= s->streams[stream_index];
1365 if(st->index_entries){
1368 index= av_index_search_timestamp(st, target_ts);
1369 e= &st->index_entries[index];
1371 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1373 ts_min= e->timestamp;
1375 av_log(s, AV_LOG_DEBUG, "unsing cached pos_min=0x%llx dts_min=%lld\n",
1382 if(index < st->nb_index_entries){
1383 e= &st->index_entries[index];
1384 assert(e->timestamp >= target_ts);
1386 ts_max= e->timestamp;
1387 pos_limit= pos_max - e->min_distance;
1389 av_log(s, AV_LOG_DEBUG, "unsing cached pos_max=0x%llx pos_limit=0x%llx dts_max=%lld\n",
1390 pos_max,pos_limit, ts_max);
1395 if(ts_min == AV_NOPTS_VALUE){
1397 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1398 if (ts_min == AV_NOPTS_VALUE)
1402 if(ts_max == AV_NOPTS_VALUE){
1404 pos_max = url_filesize(url_fileno(&s->pb)) - 1;
1407 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1409 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1410 if (ts_max == AV_NOPTS_VALUE)
1414 int64_t tmp_pos= pos_max + 1;
1415 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1416 if(tmp_ts == AV_NOPTS_VALUE)
1425 while (pos_min < pos_limit) {
1427 av_log(s, AV_LOG_DEBUG, "pos_min=0x%llx pos_max=0x%llx dts_min=%lld dts_max=%lld\n",
1431 assert(pos_limit <= pos_max);
1434 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1435 // interpolate position (better than dichotomy)
1436 pos = (int64_t)((double)(pos_max - pos_min) *
1437 (double)(target_ts - ts_min) /
1438 (double)(ts_max - ts_min)) + pos_min - approximate_keyframe_distance;
1439 }else if(no_change==1){
1440 // bisection, if interpolation failed to change min or max pos last time
1441 pos = (pos_min + pos_limit)>>1;
1443 // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
1448 else if(pos > pos_limit)
1452 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1458 av_log(s, AV_LOG_DEBUG, "%Ld %Ld %Ld / %Ld %Ld %Ld target:%Ld limit:%Ld start:%Ld noc:%d\n", pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, start_pos, no_change);
1460 assert(ts != AV_NOPTS_VALUE);
1461 if (target_ts < ts) {
1462 pos_limit = start_pos - 1;
1468 /* check if we are lucky */
1469 if (target_ts == ts)
1477 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1479 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1480 av_log(s, AV_LOG_DEBUG, "pos=0x%llx %lld<=%lld<=%lld\n",
1481 pos, ts_min, target_ts, ts_max);
1484 url_fseek(&s->pb, pos, SEEK_SET);
1486 nut->written_packet_size= -1;
1487 for(i=0; i<s->nb_streams; i++)
1488 nut->stream[i].last_sync_pos= pos;
1493 static int nut_read_close(AVFormatContext *s)
1495 NUTContext *nut = s->priv_data;
1498 for(i=0;i<s->nb_streams;i++) {
1499 av_freep(&s->streams[i]->codec.extradata);
1501 av_freep(&nut->stream);
1506 static AVInputFormat nut_iformat = {
1515 .extensions = "nut",
1518 #ifdef CONFIG_ENCODERS
1519 static AVOutputFormat nut_oformat = {
1525 #ifdef CONFIG_VORBIS
1527 #elif defined(CONFIG_MP3LAME)
1530 CODEC_ID_MP2, /* AC3 needs liba52 decoder */
1537 #endif //CONFIG_ENCODERS
1541 av_register_input_format(&nut_iformat);
1542 #ifdef CONFIG_ENCODERS
1543 av_register_output_format(&nut_oformat);
1544 #endif //CONFIG_ENCODERS