changing AVCodecContext codec -> *codec in AVStream so additions to AVCodecContext...
[libav.git] / libavformat / nut.c
CommitLineData
3aa180b8 1/*
a5247e3d 2 * "NUT" Container Format muxer and demuxer (DRAFT-200403??)
3aa180b8 3 * Copyright (c) 2003 Alex Beregszaszi
a5247e3d 4 * Copyright (c) 2004 Michael Niedermayer
3aa180b8
AB
5 *
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.
10 *
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.
15 *
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
19 *
3aa180b8 20 *
fc565b22 21 * Visit the official site at http://www.nut.hu/
3aa180b8
AB
22 *
23 */
24
25/*
26 * TODO:
3aa180b8 27 * - index writing
e52788d0 28 * - index packet reading support
3aa180b8
AB
29*/
30
31//#define DEBUG 1
32
a5247e3d 33#include <limits.h>
3aa180b8
AB
34#include "avformat.h"
35#include "mpegaudio.h"
a182f5da 36#include "avi.h"
3aa180b8 37
a5247e3d
MN
38#undef NDEBUG
39#include <assert.h>
40
84ad6130
MN
41//#define TRACE
42
3ac8749b
MN
43//from /dev/random
44
a5247e3d
MN
45#define MAIN_STARTCODE (0x7A561F5F04ADULL + (((uint64_t)('N'<<8) + 'M')<<48))
46#define STREAM_STARTCODE (0x11405BF2F9DBULL + (((uint64_t)('N'<<8) + 'S')<<48))
47#define KEYFRAME_STARTCODE (0xE4ADEECA4569ULL + (((uint64_t)('N'<<8) + 'K')<<48))
48#define INDEX_STARTCODE (0xDD672F23E64EULL + (((uint64_t)('N'<<8) + 'X')<<48))
49#define INFO_STARTCODE (0xAB68B596BA78ULL + (((uint64_t)('N'<<8) + 'I')<<48))
50
ca6ecf50
MN
51#define ID_STRING "nut/multimedia container\0"
52
0b43db14
MN
53#define MAX_DISTANCE (1024*16-1)
54#define MAX_SHORT_DISTANCE (1024*4-1)
a5247e3d 55
84ad6130
MN
56#define FLAG_DATA_SIZE 1
57#define FLAG_KEY_FRAME 2
58#define FLAG_INVALID 4
a5247e3d
MN
59
60typedef struct {
61 uint8_t flags;
62 uint8_t stream_id_plus1;
0b43db14
MN
63 uint16_t size_mul;
64 uint16_t size_lsb;
84ad6130
MN
65 int16_t timestamp_delta;
66 uint8_t reserved_count;
a5247e3d
MN
67} FrameCode;
68
69typedef struct {
70 int last_key_frame;
71 int msb_timestamp_shift;
72 int rate_num;
73 int rate_den;
74 int64_t last_pts;
7dddf251 75 int64_t last_sync_pos; ///<pos of last 1/2 type frame
0b43db14 76 int decode_delay;
a5247e3d 77} StreamContext;
3ac8749b 78
3aa180b8 79typedef struct {
a5247e3d 80 AVFormatContext *avf;
a5247e3d 81 int written_packet_size;
0b43db14 82 int64_t packet_start[3]; //0-> startcode less, 1-> short startcode 2-> long startcodes
a5247e3d 83 FrameCode frame_code[256];
568e18b1 84 unsigned int stream_count;
465e1dad 85 uint64_t next_startcode; ///< stores the next startcode if it has alraedy been parsed but the stream isnt seekable
a5247e3d 86 StreamContext *stream;
0b43db14 87 int max_distance;
ca6ecf50 88 int max_short_distance;
84ad6130
MN
89 int rate_num;
90 int rate_den;
91 int short_startcode;
3aa180b8
AB
92} NUTContext;
93
e52788d0
MN
94static char *info_table[][2]={
95 {NULL , NULL }, // end
96 {NULL , NULL },
97 {NULL , "UTF8"},
98 {NULL , "v"},
99 {NULL , "s"},
100 {"StreamId" , "v"},
101 {"SegmentId" , "v"},
102 {"StartTimestamp" , "v"},
103 {"EndTimestamp" , "v"},
104 {"Author" , "UTF8"},
5a757507 105 {"Title" , "UTF8"},
e52788d0
MN
106 {"Description" , "UTF8"},
107 {"Copyright" , "UTF8"},
108 {"Encoder" , "UTF8"},
109 {"Keyword" , "UTF8"},
110 {"Cover" , "JPEG"},
111 {"Cover" , "PNG"},
112};
113
01bd1ed2
MN
114void ff_parse_specific_params(AVCodecContext *stream, int *au_rate, int *au_ssize, int *au_scale);
115
a5247e3d
MN
116static 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){
117 StreamContext *stream= &nut->stream[stream_index];
118
119 stream->last_key_frame= key_frame;
0b43db14 120 nut->packet_start[ frame_type ]= frame_start;
a5247e3d 121 stream->last_pts= pts;
a5247e3d
MN
122}
123
84ad6130 124static void reset(AVFormatContext *s, int64_t global_ts){
a5247e3d
MN
125 NUTContext *nut = s->priv_data;
126 int i;
127
128 for(i=0; i<s->nb_streams; i++){
129 StreamContext *stream= &nut->stream[i];
130
131 stream->last_key_frame= 1;
84ad6130
MN
132
133 stream->last_pts= av_rescale(global_ts, stream->rate_num*(int64_t)nut->rate_den, stream->rate_den*(int64_t)nut->rate_num);
a5247e3d
MN
134 }
135}
136
137static void build_frame_code(AVFormatContext *s){
138 NUTContext *nut = s->priv_data;
84ad6130 139 int key_frame, index, pred, stream_id;
a5247e3d
MN
140 int start=0;
141 int end= 255;
142 int keyframe_0_esc= s->nb_streams > 2;
84ad6130 143 int pred_table[10];
a5247e3d
MN
144
145 if(keyframe_0_esc){
0b43db14
MN
146 /* keyframe = 0 escape */
147 FrameCode *ft= &nut->frame_code[start];
84ad6130 148 ft->flags= FLAG_DATA_SIZE;
0b43db14
MN
149 ft->stream_id_plus1= 0;
150 ft->size_mul=1;
84ad6130 151 ft->timestamp_delta=0;
0b43db14 152 start++;
a5247e3d
MN
153 }
154
155 for(stream_id= 0; stream_id<s->nb_streams; stream_id++){
156 int start2= start + (end-start)*stream_id / s->nb_streams;
157 int end2 = start + (end-start)*(stream_id+1) / s->nb_streams;
01f4895c 158 AVCodecContext *codec = s->streams[stream_id]->codec;
a5247e3d
MN
159 int is_audio= codec->codec_type == CODEC_TYPE_AUDIO;
160 int intra_only= /*codec->intra_only || */is_audio;
161 int pred_count;
162
163 for(key_frame=0; key_frame<2; key_frame++){
164 if(intra_only && keyframe_0_esc && key_frame==0)
165 continue;
166
0b43db14
MN
167 {
168 FrameCode *ft= &nut->frame_code[start2];
169 ft->flags= FLAG_KEY_FRAME*key_frame;
84ad6130 170 ft->flags|= FLAG_DATA_SIZE;
0b43db14
MN
171 ft->stream_id_plus1= stream_id + 1;
172 ft->size_mul=1;
84ad6130 173 ft->timestamp_delta=0;
0b43db14 174 start2++;
a5247e3d
MN
175 }
176 }
177
178 key_frame= intra_only;
179#if 1
180 if(is_audio){
181 int frame_bytes= codec->frame_size*(int64_t)codec->bit_rate / (8*codec->sample_rate);
84ad6130
MN
182 int pts;
183 for(pts=0; pts<2; pts++){
0b43db14 184 for(pred=0; pred<2; pred++){
a5247e3d 185 FrameCode *ft= &nut->frame_code[start2];
84ad6130 186 ft->flags= FLAG_KEY_FRAME*key_frame;
a5247e3d 187 ft->stream_id_plus1= stream_id + 1;
0b43db14
MN
188 ft->size_mul=frame_bytes + 2;
189 ft->size_lsb=frame_bytes + pred;
84ad6130 190 ft->timestamp_delta=pts;
a5247e3d
MN
191 start2++;
192 }
a5247e3d
MN
193 }
194 }else{
195 FrameCode *ft= &nut->frame_code[start2];
196 ft->flags= FLAG_KEY_FRAME | FLAG_DATA_SIZE;
197 ft->stream_id_plus1= stream_id + 1;
198 ft->size_mul=1;
84ad6130 199 ft->timestamp_delta=1;
a5247e3d
MN
200 start2++;
201 }
202#endif
84ad6130
MN
203
204 if(codec->has_b_frames){
205 pred_count=5;
206 pred_table[0]=-2;
207 pred_table[1]=-1;
208 pred_table[2]=1;
209 pred_table[3]=3;
210 pred_table[4]=4;
211 }else if(codec->codec_id == CODEC_ID_VORBIS){
212 pred_count=3;
213 pred_table[0]=2;
214 pred_table[1]=9;
215 pred_table[2]=16;
216 }else{
217 pred_count=1;
218 pred_table[0]=1;
219 }
220
a5247e3d
MN
221 for(pred=0; pred<pred_count; pred++){
222 int start3= start2 + (end2-start2)*pred / pred_count;
223 int end3 = start2 + (end2-start2)*(pred+1) / pred_count;
224
225 for(index=start3; index<end3; index++){
226 FrameCode *ft= &nut->frame_code[index];
84ad6130 227 ft->flags= FLAG_KEY_FRAME*key_frame;
a5247e3d
MN
228 ft->flags|= FLAG_DATA_SIZE;
229 ft->stream_id_plus1= stream_id + 1;
230//FIXME use single byte size and pred from last
231 ft->size_mul= end3-start3;
232 ft->size_lsb= index - start3;
84ad6130 233 ft->timestamp_delta= pred_table[pred];
a5247e3d 234 }
a5247e3d
MN
235 }
236 }
237 memmove(&nut->frame_code['N'+1], &nut->frame_code['N'], sizeof(FrameCode)*(255-'N'));
84ad6130 238 nut->frame_code['N'].flags= FLAG_INVALID;
a5247e3d
MN
239}
240
3aa180b8
AB
241static uint64_t get_v(ByteIOContext *bc)
242{
243 uint64_t val = 0;
244
465e1dad 245 for(;;)
3aa180b8
AB
246 {
247 int tmp = get_byte(bc);
248
249 if (tmp&0x80)
250 val= (val<<7) + tmp - 0x80;
0b43db14
MN
251 else{
252//av_log(NULL, AV_LOG_DEBUG, "get_v()= %lld\n", (val<<7) + tmp);
3aa180b8 253 return (val<<7) + tmp;
0b43db14 254 }
3aa180b8
AB
255 }
256 return -1;
257}
258
568e18b1
MN
259static int get_str(ByteIOContext *bc, char *string, unsigned int maxlen){
260 unsigned int len= get_v(bc);
3aa180b8 261
e52788d0
MN
262 if(len && maxlen)
263 get_buffer(bc, string, FFMIN(len, maxlen));
264 while(len > maxlen){
265 get_byte(bc);
266 len--;
267 }
8c653280 268
e52788d0
MN
269 if(maxlen)
270 string[FFMIN(len, maxlen-1)]= 0;
8c653280 271
e52788d0
MN
272 if(maxlen == len)
273 return -1;
274 else
275 return 0;
3aa180b8
AB
276}
277
84ad6130
MN
278static int64_t get_s(ByteIOContext *bc){
279 int64_t v = get_v(bc) + 1;
280
281 if (v&1) return -(v>>1);
282 else return (v>>1);
283}
284
7dddf251
MN
285static uint64_t get_vb(ByteIOContext *bc){
286 uint64_t val=0;
568e18b1 287 unsigned int i= get_v(bc);
7dddf251
MN
288
289 if(i>8)
290 return UINT64_MAX;
291
292 while(i--)
293 val = (val<<8) + get_byte(bc);
294
0b43db14 295//av_log(NULL, AV_LOG_DEBUG, "get_vb()= %lld\n", val);
7dddf251
MN
296 return val;
297}
298
84ad6130
MN
299#ifdef TRACE
300static inline uint64_t get_v_trace(ByteIOContext *bc, char *file, char *func, int line){
301 uint64_t v= get_v(bc);
302
303 printf("get_v %5lld / %llX in %s %s:%d\n", v, v, file, func, line);
304 return v;
305}
306
307static inline int64_t get_s_trace(ByteIOContext *bc, char *file, char *func, int line){
308 int64_t v= get_s(bc);
309
310 printf("get_s %5lld / %llX in %s %s:%d\n", v, v, file, func, line);
311 return v;
312}
313
314static inline uint64_t get_vb_trace(ByteIOContext *bc, char *file, char *func, int line){
315 uint64_t v= get_vb(bc);
316
317 printf("get_vb %5lld / %llX in %s %s:%d\n", v, v, file, func, line);
318 return v;
319}
320#define get_v(bc) get_v_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
321#define get_s(bc) get_s_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
322#define get_vb(bc) get_vb_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
323#endif
324
325
0b43db14 326static int get_packetheader(NUTContext *nut, ByteIOContext *bc, int calculate_checksum)
3aa180b8 327{
0b43db14
MN
328 int64_t start, size;
329 start= url_ftell(bc) - 8;
a5247e3d 330
465e1dad 331 init_checksum(bc, calculate_checksum ? update_adler32 : NULL, 0);
a5247e3d
MN
332
333 size= get_v(bc);
a5247e3d 334
0b43db14 335 nut->packet_start[2] = start;
a5247e3d
MN
336 nut->written_packet_size= size;
337
338 return size;
3aa180b8
AB
339}
340
ee9f36a8
MN
341static int check_checksum(ByteIOContext *bc){
342 unsigned long checksum= get_checksum(bc);
343 return checksum != get_be32(bc);
344}
345
203504d9
MN
346/**
347 *
348 */
349static int get_length(uint64_t val){
350 int i;
3aa180b8 351
7dddf251 352 for (i=7; val>>i; i+=7);
3aa180b8 353
7dddf251 354 return i;
3aa180b8
AB
355}
356
7c5934ed
MN
357static uint64_t find_any_startcode(ByteIOContext *bc, int64_t pos){
358 uint64_t state=0;
359
360 if(pos >= 0)
361 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
362
465e1dad 363 while(!url_feof(bc)){
7c5934ed
MN
364 state= (state<<8) | get_byte(bc);
365 if((state>>56) != 'N')
366 continue;
367 switch(state){
368 case MAIN_STARTCODE:
369 case STREAM_STARTCODE:
370 case KEYFRAME_STARTCODE:
371 case INFO_STARTCODE:
372 case INDEX_STARTCODE:
373 return state;
374 }
375 }
7dddf251 376
7c5934ed
MN
377 return 0;
378}
379
7dddf251
MN
380/**
381 * find the given startcode.
382 * @param code the startcode
383 * @param pos the start position of the search, or -1 if the current position
384 * @returns the position of the startcode or -1 if not found
385 */
386static int64_t find_startcode(ByteIOContext *bc, uint64_t code, int64_t pos){
7c5934ed
MN
387 for(;;){
388 uint64_t startcode= find_any_startcode(bc, pos);
389 if(startcode == code)
7dddf251 390 return url_ftell(bc) - 8;
7c5934ed
MN
391 else if(startcode == 0)
392 return -1;
393 pos=-1;
394 }
395}
396
764ef400 397#ifdef CONFIG_ENCODERS
84ad6130 398
7dddf251 399static void put_v(ByteIOContext *bc, uint64_t val)
3aa180b8
AB
400{
401 int i;
3aa180b8 402
0b43db14 403//av_log(NULL, AV_LOG_DEBUG, "put_v()= %lld\n", val);
3aa180b8 404 val &= 0x7FFFFFFFFFFFFFFFULL; // FIXME can only encode upto 63 bits currently
203504d9 405 i= get_length(val);
3aa180b8 406
3ac8749b 407 for (i-=7; i>0; i-=7){
3aa180b8 408 put_byte(bc, 0x80 | (val>>i));
3ac8749b 409 }
3aa180b8
AB
410
411 put_byte(bc, val&0x7f);
3aa180b8
AB
412}
413
7dddf251
MN
414/**
415 * stores a string as vb.
416 */
417static void put_str(ByteIOContext *bc, const char *string){
e52788d0 418 int len= strlen(string);
3aa180b8
AB
419
420 put_v(bc, len);
e52788d0 421 put_buffer(bc, string, len);
7dddf251
MN
422}
423
7071e567 424static void put_s(ByteIOContext *bc, int64_t val){
84ad6130
MN
425 if (val<=0) put_v(bc, -2*val );
426 else put_v(bc, 2*val-1);
427}
428
7dddf251
MN
429static void put_vb(ByteIOContext *bc, uint64_t val){
430 int i;
e52788d0 431
7dddf251
MN
432 for (i=8; val>>i; i+=8);
433
434 put_v(bc, i>>3);
435 for(i-=8; i>=0; i-=8)
436 put_byte(bc, (val>>i)&0xFF);
a182f5da
FB
437}
438
84ad6130
MN
439#ifdef TRACE
440static inline void put_v_trace(ByteIOContext *bc, uint64_t v, char *file, char *func, int line){
441 printf("get_v %5lld / %llX in %s %s:%d\n", v, v, file, func, line);
442
443 put_v(bc, v);
444}
445
446static inline void put_s_trace(ByteIOContext *bc, int64_t v, char *file, char *func, int line){
447 printf("get_s %5lld / %llX in %s %s:%d\n", v, v, file, func, line);
448
449 put_s(bc, v);
450}
451
452static inline void put_vb_trace(ByteIOContext *bc, uint64_t v, char *file, char *func, int line){
453 printf("get_vb %5lld / %llX in %s %s:%d\n", v, v, file, func, line);
454
455 put_vb(bc, v);
456}
457#define put_v(bc, v) put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
458#define put_s(bc, v) put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
459#define put_vb(bc, v) put_vb_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
460#endif
461
ee9f36a8 462static int put_packetheader(NUTContext *nut, ByteIOContext *bc, int max_size, int calculate_checksum)
3aa180b8
AB
463{
464 put_flush_packet(bc);
0b43db14
MN
465 nut->packet_start[2]+= nut->written_packet_size;
466 assert(url_ftell(bc) - 8 == nut->packet_start[2]);
a5247e3d 467 nut->written_packet_size = max_size;
ee9f36a8
MN
468
469 if(calculate_checksum)
470 init_checksum(bc, update_adler32, 0);
a5247e3d 471
3aa180b8 472 /* packet header */
a5247e3d 473 put_v(bc, nut->written_packet_size); /* forward ptr */
3aa180b8 474
3aa180b8
AB
475 return 0;
476}
477
ee9f36a8 478static int update_packetheader(NUTContext *nut, ByteIOContext *bc, int additional_size, int calculate_checksum){
0b43db14 479 int64_t start= nut->packet_start[2];
a5247e3d 480 int64_t cur= url_ftell(bc);
203504d9
MN
481 int size= cur - start + additional_size;
482
ee9f36a8
MN
483 if(calculate_checksum)
484 size += 4;
485
a5247e3d
MN
486 if(size != nut->written_packet_size){
487 int i;
488
489 assert( size <= nut->written_packet_size );
203504d9 490
0b43db14 491 url_fseek(bc, start + 8, SEEK_SET);
a5247e3d
MN
492 for(i=get_length(size); i < get_length(nut->written_packet_size); i+=7)
493 put_byte(bc, 0x80);
494 put_v(bc, size);
495
496 url_fseek(bc, cur, SEEK_SET);
497 nut->written_packet_size= size; //FIXME may fail if multiple updates with differing sizes, as get_length may differ
ee9f36a8
MN
498
499 if(calculate_checksum)
500 put_be32(bc, get_checksum(bc));
a5247e3d 501 }
3aa180b8 502
3aa180b8
AB
503 return 0;
504}
505
506static int nut_write_header(AVFormatContext *s)
507{
508 NUTContext *nut = s->priv_data;
509 ByteIOContext *bc = &s->pb;
510 AVCodecContext *codec;
84ad6130 511 int i, j, tmp_time, tmp_flags,tmp_stream, tmp_mul, tmp_size, tmp_fields;
3aa180b8 512
a5247e3d
MN
513 nut->avf= s;
514
515 nut->stream =
516 av_mallocz(sizeof(StreamContext)*s->nb_streams);
ca6ecf50
MN
517
518
519 put_buffer(bc, ID_STRING, strlen(ID_STRING));
520 put_byte(bc, 0);
521 nut->packet_start[2]= url_ftell(bc);
a5247e3d 522
3aa180b8 523 /* main header */
3ac8749b 524 put_be64(bc, MAIN_STARTCODE);
ee9f36a8 525 put_packetheader(nut, bc, 120+5*256, 1);
0b43db14 526 put_v(bc, 2); /* version */
3aa180b8 527 put_v(bc, s->nb_streams);
0b43db14 528 put_v(bc, MAX_DISTANCE);
ca6ecf50 529 put_v(bc, MAX_SHORT_DISTANCE);
a5247e3d 530
84ad6130
MN
531 put_v(bc, nut->rate_num=1);
532 put_v(bc, nut->rate_den=2);
533 put_v(bc, nut->short_startcode=0x4EFE79);
534
a5247e3d 535 build_frame_code(s);
84ad6130
MN
536 assert(nut->frame_code['N'].flags == FLAG_INVALID);
537
538 tmp_time= tmp_flags= tmp_stream= tmp_mul= tmp_size= /*tmp_res=*/ INT_MAX;
a5247e3d 539 for(i=0; i<256;){
84ad6130
MN
540 tmp_fields=0;
541 tmp_size= 0;
542 if(tmp_time != nut->frame_code[i].timestamp_delta) tmp_fields=1;
543 if(tmp_mul != nut->frame_code[i].size_mul ) tmp_fields=2;
544 if(tmp_stream != nut->frame_code[i].stream_id_plus1) tmp_fields=3;
545 if(tmp_size != nut->frame_code[i].size_lsb ) tmp_fields=4;
546// if(tmp_res != nut->frame_code[i].res ) tmp_fields=5;
547
548 tmp_time = nut->frame_code[i].timestamp_delta;
549 tmp_flags = nut->frame_code[i].flags;
550 tmp_stream= nut->frame_code[i].stream_id_plus1;
551 tmp_mul = nut->frame_code[i].size_mul;
552 tmp_size = nut->frame_code[i].size_lsb;
553// tmp_res = nut->frame_code[i].res;
554
a5247e3d 555 for(j=0; i<256; j++,i++){
84ad6130 556 if(nut->frame_code[i].timestamp_delta != tmp_time ) break;
a5247e3d
MN
557 if(nut->frame_code[i].flags != tmp_flags ) break;
558 if(nut->frame_code[i].stream_id_plus1 != tmp_stream) break;
559 if(nut->frame_code[i].size_mul != tmp_mul ) break;
84ad6130
MN
560 if(nut->frame_code[i].size_lsb != tmp_size+j) break;
561// if(nut->frame_code[i].res != tmp_res ) break;
a5247e3d 562 }
84ad6130
MN
563 if(j != tmp_mul - tmp_size) tmp_fields=6;
564
565 put_v(bc, tmp_flags);
566 put_v(bc, tmp_fields);
567 if(tmp_fields>0) put_s(bc, tmp_time);
568 if(tmp_fields>1) put_v(bc, tmp_mul);
569 if(tmp_fields>2) put_v(bc, tmp_stream);
570 if(tmp_fields>3) put_v(bc, tmp_size);
571 if(tmp_fields>4) put_v(bc, 0 /*tmp_res*/);
572 if(tmp_fields>5) put_v(bc, j);
a5247e3d
MN
573 }
574
ee9f36a8 575 update_packetheader(nut, bc, 0, 1);
203504d9 576
3aa180b8
AB
577 /* stream headers */
578 for (i = 0; i < s->nb_streams; i++)
579 {
01bd1ed2 580 int nom, denom, ssize;
cf246283 581
01f4895c 582 codec = s->streams[i]->codec;
3aa180b8 583
3ac8749b 584 put_be64(bc, STREAM_STARTCODE);
ee9f36a8 585 put_packetheader(nut, bc, 120 + codec->extradata_size, 1);
99b17f25 586 put_v(bc, i /*s->streams[i]->index*/);
01bd1ed2
MN
587 switch(codec->codec_type){
588 case CODEC_TYPE_VIDEO: put_v(bc, 0); break;
589 case CODEC_TYPE_AUDIO: put_v(bc, 1); break;
590// case CODEC_TYPE_TEXT : put_v(bc, 2); break;
591 case CODEC_TYPE_DATA : put_v(bc, 3); break;
592 default: return -1;
593 }
3aa180b8 594 if (codec->codec_tag)
7dddf251 595 put_vb(bc, codec->codec_tag);
3aa180b8
AB
596 else if (codec->codec_type == CODEC_TYPE_VIDEO)
597 {
7dddf251 598 put_vb(bc, codec_get_bmp_tag(codec->codec_id));
3aa180b8
AB
599 }
600 else if (codec->codec_type == CODEC_TYPE_AUDIO)
601 {
7dddf251 602 put_vb(bc, codec_get_wav_tag(codec->codec_id));
4b684105 603 }
e52788d0 604 else
7dddf251 605 put_vb(bc, 0);
01bd1ed2
MN
606
607 ff_parse_specific_params(codec, &nom, &ssize, &denom);
4b684105 608
a5247e3d
MN
609 nut->stream[i].rate_num= nom;
610 nut->stream[i].rate_den= denom;
cdd5034f 611 av_set_pts_info(s->streams[i], 60, denom, nom);
a5247e3d 612
3aa180b8 613 put_v(bc, codec->bit_rate);
7dddf251 614 put_vb(bc, 0); /* no language code */
cf246283
AB
615 put_v(bc, nom);
616 put_v(bc, denom);
a5247e3d
MN
617 if(nom / denom < 1000)
618 nut->stream[i].msb_timestamp_shift = 7;
619 else
620 nut->stream[i].msb_timestamp_shift = 14;
621 put_v(bc, nut->stream[i].msb_timestamp_shift);
0b43db14 622 put_v(bc, codec->has_b_frames);
3aa180b8
AB
623 put_byte(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
624
a5247e3d
MN
625 if(codec->extradata_size){
626 put_v(bc, 1);
627 put_v(bc, codec->extradata_size);
628 put_buffer(bc, codec->extradata, codec->extradata_size);
629 }
630 put_v(bc, 0); /* end of codec specific headers */
3aa180b8
AB
631
632 switch(codec->codec_type)
633 {
634 case CODEC_TYPE_AUDIO:
0b43db14
MN
635 put_v(bc, codec->sample_rate);
636 put_v(bc, 1);
3aa180b8 637 put_v(bc, codec->channels);
3aa180b8
AB
638 break;
639 case CODEC_TYPE_VIDEO:
640 put_v(bc, codec->width);
641 put_v(bc, codec->height);
a5247e3d
MN
642 put_v(bc, codec->sample_aspect_ratio.num);
643 put_v(bc, codec->sample_aspect_ratio.den);
3aa180b8 644 put_v(bc, 0); /* csp type -- unknown */
3aa180b8 645 break;
a182f5da
FB
646 default:
647 break;
3aa180b8 648 }
ee9f36a8 649 update_packetheader(nut, bc, 0, 1);
3aa180b8
AB
650 }
651
3aa180b8 652 /* info header */
ed0bb7be 653 put_be64(bc, INFO_STARTCODE);
e52788d0 654 put_packetheader(nut, bc, 30+strlen(s->author)+strlen(s->title)+
ee9f36a8 655 strlen(s->comment)+strlen(s->copyright)+strlen(LIBAVFORMAT_IDENT), 1);
3aa180b8
AB
656 if (s->author[0])
657 {
e52788d0
MN
658 put_v(bc, 9); /* type */
659 put_str(bc, s->author);
3aa180b8
AB
660 }
661 if (s->title[0])
662 {
e52788d0
MN
663 put_v(bc, 10); /* type */
664 put_str(bc, s->title);
3aa180b8
AB
665 }
666 if (s->comment[0])
667 {
e52788d0
MN
668 put_v(bc, 11); /* type */
669 put_str(bc, s->comment);
3aa180b8
AB
670 }
671 if (s->copyright[0])
672 {
e52788d0
MN
673 put_v(bc, 12); /* type */
674 put_str(bc, s->copyright);
3aa180b8
AB
675 }
676 /* encoder */
01f4895c 677 if(!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)){
75553f82
MN
678 put_v(bc, 13); /* type */
679 put_str(bc, LIBAVFORMAT_IDENT);
680 }
99b17f25
AB
681
682 put_v(bc, 0); /* eof info */
ee9f36a8 683 update_packetheader(nut, bc, 0, 1);
3aa180b8
AB
684
685 put_flush_packet(bc);
686
687 return 0;
688}
689
0b43db14
MN
690static int64_t lsb2full(StreamContext *stream, int64_t lsb){
691 int64_t mask = (1<<stream->msb_timestamp_shift)-1;
692 int64_t delta= stream->last_pts - mask/2;
693 return ((lsb - delta)&mask) + delta;
694}
695
e928649b 696static int nut_write_packet(AVFormatContext *s, AVPacket *pkt)
3aa180b8
AB
697{
698 NUTContext *nut = s->priv_data;
e928649b 699 StreamContext *stream= &nut->stream[pkt->stream_index];
3aa180b8 700 ByteIOContext *bc = &s->pb;
a5247e3d 701 int key_frame = 0, full_pts=0;
3aa180b8 702 AVCodecContext *enc;
0b43db14 703 int64_t coded_pts;
84ad6130 704 int frame_type, best_length, frame_code, flags, i, size_mul, size_lsb, time_delta;
a5247e3d 705 const int64_t frame_start= url_ftell(bc);
e928649b
MN
706 int64_t pts= pkt->pts;
707 int size= pkt->size;
708 int stream_index= pkt->stream_index;
3aa180b8 709
01f4895c 710 enc = s->streams[stream_index]->codec;
e928649b 711 key_frame = !!(pkt->flags & PKT_FLAG_KEY);
a5247e3d
MN
712
713 frame_type=0;
0b43db14
MN
714 if(frame_start + size + 20 - FFMAX(nut->packet_start[1], nut->packet_start[2]) > MAX_DISTANCE)
715 frame_type=2;
716 if(key_frame && !stream->last_key_frame)
717 frame_type=2;
3aa180b8 718
84ad6130
MN
719 if(frame_type>1){
720 int64_t global_ts= av_rescale(pts, stream->rate_den*(int64_t)nut->rate_num, stream->rate_num*(int64_t)nut->rate_den);
721 reset(s, global_ts);
722 put_be64(bc, KEYFRAME_STARTCODE);
723 put_v(bc, global_ts);
a5247e3d 724 }
84ad6130
MN
725 assert(stream->last_pts != AV_NOPTS_VALUE);
726 coded_pts = pts & ((1<<stream->msb_timestamp_shift)-1);
727 if(lsb2full(stream, coded_pts) != pts)
728 full_pts=1;
a5247e3d 729
0b43db14
MN
730 if(full_pts)
731 coded_pts= pts + (1<<stream->msb_timestamp_shift);
a5247e3d
MN
732
733 best_length=INT_MAX;
734 frame_code= -1;
735 for(i=0; i<256; i++){
736 int stream_id_plus1= nut->frame_code[i].stream_id_plus1;
aec8f88a 737 int fc_key_frame;
a5247e3d
MN
738 int length=0;
739 size_mul= nut->frame_code[i].size_mul;
740 size_lsb= nut->frame_code[i].size_lsb;
84ad6130 741 time_delta= nut->frame_code[i].timestamp_delta;
a5247e3d
MN
742 flags= nut->frame_code[i].flags;
743
0b43db14
MN
744 assert(size_mul > size_lsb);
745
a5247e3d
MN
746 if(stream_id_plus1 == 0) length+= get_length(stream_index);
747 else if(stream_id_plus1 - 1 != stream_index)
748 continue;
aec8f88a
MN
749 fc_key_frame= !!(flags & FLAG_KEY_FRAME);
750
a5247e3d
MN
751 assert(key_frame==0 || key_frame==1);
752 if(fc_key_frame != key_frame)
753 continue;
754
0b43db14 755 if(flags & FLAG_DATA_SIZE){
a5247e3d
MN
756 if(size % size_mul != size_lsb)
757 continue;
0b43db14
MN
758 length += get_length(size / size_mul);
759 }else if(size != size_lsb)
760 continue;
a5247e3d 761
84ad6130 762 if(full_pts && time_delta)
a5247e3d
MN
763 continue;
764
84ad6130 765 if(!time_delta){
0b43db14 766 length += get_length(coded_pts);
a5247e3d 767 }else{
84ad6130 768 if(time_delta != pts - stream->last_pts)
a5247e3d 769 continue;
a5247e3d
MN
770 }
771
772 if(length < best_length){
773 best_length= length;
774 frame_code=i;
775 }
776// 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);
777 }
3ac8749b 778
a5247e3d
MN
779 assert(frame_code != -1);
780 flags= nut->frame_code[frame_code].flags;
781 size_mul= nut->frame_code[frame_code].size_mul;
782 size_lsb= nut->frame_code[frame_code].size_lsb;
84ad6130
MN
783 time_delta= nut->frame_code[frame_code].timestamp_delta;
784#ifdef TRACE
a5247e3d
MN
785 best_length /= 7;
786 best_length ++; //frame_code
0b43db14
MN
787 if(frame_type==2){
788 best_length += 8; // startcode
a5247e3d 789 }
84ad6130 790 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 pts:%lld fs:%lld\n", key_frame, frame_type, full_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), pts, frame_start);
0b43db14 791// av_log(s, AV_LOG_DEBUG, "%d %d %d\n", stream->lru_pts_delta[0], stream->lru_pts_delta[1], stream->lru_pts_delta[2]);
a5247e3d
MN
792#endif
793
0b43db14 794 assert(frame_type != 1); //short startcode not implemented yet
a5247e3d
MN
795 put_byte(bc, frame_code);
796
a5247e3d
MN
797 if(nut->frame_code[frame_code].stream_id_plus1 == 0)
798 put_v(bc, stream_index);
84ad6130 799 if (!time_delta){
0b43db14 800 put_v(bc, coded_pts);
a5247e3d
MN
801 }
802 if(flags & FLAG_DATA_SIZE)
803 put_v(bc, size / size_mul);
84ad6130
MN
804 else
805 assert(size == size_lsb);
0b43db14
MN
806 if(size > MAX_DISTANCE){
807 assert(frame_type > 1);
a5247e3d 808 }
3aa180b8 809
e928649b 810 put_buffer(bc, pkt->data, size);
3aa180b8 811
a5247e3d
MN
812 update(nut, stream_index, frame_start, frame_type, frame_code, key_frame, size, pts);
813
3aa180b8
AB
814 return 0;
815}
816
817static int nut_write_trailer(AVFormatContext *s)
818{
f0a93eb0 819 NUTContext *nut = s->priv_data;
3aa180b8 820 ByteIOContext *bc = &s->pb;
a5247e3d 821
3aa180b8
AB
822#if 0
823 int i;
824
825 /* WRITE INDEX */
826
827 for (i = 0; s->nb_streams; i++)
828 {
3ac8749b 829 put_be64(bc, INDEX_STARTCODE);
ee9f36a8 830 put_packetheader(nut, bc, 64, 1);
3aa180b8
AB
831 put_v(bc, s->streams[i]->id);
832 put_v(bc, ...);
ee9f36a8 833 update_packetheader(nut, bc, 0, 1);
3aa180b8
AB
834 }
835#endif
836
837 put_flush_packet(bc);
f0a93eb0 838
a5247e3d 839 av_freep(&nut->stream);
3aa180b8
AB
840
841 return 0;
842}
764ef400 843#endif //CONFIG_ENCODERS
3aa180b8
AB
844
845static int nut_probe(AVProbeData *p)
846{
3ac8749b 847 int i;
0b43db14 848 uint64_t code= 0xff;
3ac8749b 849
3ac8749b 850 for (i = 0; i < p->buf_size; i++) {
0b43db14 851 code = (code << 8) | p->buf[i];
3ac8749b
MN
852 if (code == MAIN_STARTCODE)
853 return AVPROBE_SCORE_MAX;
854 }
855 return 0;
3aa180b8
AB
856}
857
7c5934ed
MN
858static int decode_main_header(NUTContext *nut){
859 AVFormatContext *s= nut->avf;
3aa180b8 860 ByteIOContext *bc = &s->pb;
3ac8749b 861 uint64_t tmp;
84ad6130 862 int i, j, tmp_stream, tmp_mul, tmp_time, tmp_size, count, tmp_res;
3aa180b8 863
0b43db14 864 get_packetheader(nut, bc, 1);
7c5934ed 865
3aa180b8 866 tmp = get_v(bc);
0b43db14 867 if (tmp != 2){
bc874dae 868 av_log(s, AV_LOG_ERROR, "bad version (%Ld)\n", tmp);
7c5934ed
MN
869 return -1;
870 }
3aa180b8 871
7c5934ed 872 nut->stream_count = get_v(bc);
568e18b1
MN
873 if(nut->stream_count > MAX_STREAMS){
874 av_log(s, AV_LOG_ERROR, "too many streams\n");
875 return -1;
876 }
0b43db14 877 nut->max_distance = get_v(bc);
ca6ecf50 878 nut->max_short_distance = get_v(bc);
84ad6130
MN
879 nut->rate_num= get_v(bc);
880 nut->rate_den= get_v(bc);
881 nut->short_startcode= get_v(bc);
882 if(nut->short_startcode>>16 != 'N'){
883 av_log(s, AV_LOG_ERROR, "invalid short startcode %X\n", nut->short_startcode);
884 return -1;
885 }
0b43db14 886
a5247e3d
MN
887 for(i=0; i<256;){
888 int tmp_flags = get_v(bc);
84ad6130
MN
889 int tmp_fields= get_v(bc);
890 if(tmp_fields>0) tmp_time = get_s(bc);
891 if(tmp_fields>1) tmp_mul = get_v(bc);
892 if(tmp_fields>2) tmp_stream= get_v(bc);
893 if(tmp_fields>3) tmp_size = get_v(bc);
894 else tmp_size = 0;
895 if(tmp_fields>4) tmp_res = get_v(bc);
896 else tmp_res = 0;
897 if(tmp_fields>5) count = get_v(bc);
898 else count = tmp_mul - tmp_size;
899
900 while(tmp_fields-- > 6)
901 get_v(bc);
902
a5247e3d
MN
903 if(count == 0 || i+count > 256){
904 av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
905 return -1;
906 }
84ad6130
MN
907 if(tmp_stream > nut->stream_count + 1){
908 av_log(s, AV_LOG_ERROR, "illegal stream number\n");
909 return -1;
910 }
a5247e3d 911
a5247e3d 912 for(j=0; j<count; j++,i++){
a5247e3d 913 nut->frame_code[i].flags = tmp_flags ;
84ad6130 914 nut->frame_code[i].timestamp_delta = tmp_time ;
a5247e3d
MN
915 nut->frame_code[i].stream_id_plus1 = tmp_stream;
916 nut->frame_code[i].size_mul = tmp_mul ;
84ad6130
MN
917 nut->frame_code[i].size_lsb = tmp_size+j;
918 nut->frame_code[i].reserved_count = tmp_res ;
a5247e3d
MN
919 }
920 }
84ad6130 921 if(nut->frame_code['N'].flags != FLAG_INVALID){
a5247e3d
MN
922 av_log(s, AV_LOG_ERROR, "illegal frame_code table\n");
923 return -1;
924 }
7c5934ed 925
ee9f36a8 926 if(check_checksum(bc)){
160d679c 927 av_log(s, AV_LOG_ERROR, "Main header checksum mismatch\n");
ee9f36a8
MN
928 return -1;
929 }
f0a93eb0 930
7c5934ed
MN
931 return 0;
932}
933
934static int decode_stream_header(NUTContext *nut){
935 AVFormatContext *s= nut->avf;
936 ByteIOContext *bc = &s->pb;
84ad6130 937 int class, nom, denom, stream_id;
7c5934ed
MN
938 uint64_t tmp;
939 AVStream *st;
940
0b43db14 941 get_packetheader(nut, bc, 1);
7c5934ed
MN
942 stream_id= get_v(bc);
943 if(stream_id >= nut->stream_count || s->streams[stream_id])
944 return -1;
3aa180b8 945
7c5934ed
MN
946 st = av_new_stream(s, stream_id);
947 if (!st)
948 return AVERROR_NOMEM;
9ee91c2f 949
7c5934ed 950 class = get_v(bc);
7dddf251 951 tmp = get_vb(bc);
01f4895c 952 st->codec->codec_tag= tmp;
7c5934ed 953 switch(class)
3aa180b8 954 {
7c5934ed 955 case 0:
01f4895c
MN
956 st->codec->codec_type = CODEC_TYPE_VIDEO;
957 st->codec->codec_id = codec_get_bmp_id(tmp);
958 if (st->codec->codec_id == CODEC_ID_NONE)
7c5934ed
MN
959 av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");
960 break;
01bd1ed2
MN
961 case 1:
962 case 32: //compatibility
01f4895c
MN
963 st->codec->codec_type = CODEC_TYPE_AUDIO;
964 st->codec->codec_id = codec_get_wav_id(tmp);
965 if (st->codec->codec_id == CODEC_ID_NONE)
7c5934ed
MN
966 av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");
967 break;
01bd1ed2 968 case 2:
01f4895c 969// st->codec->codec_type = CODEC_TYPE_TEXT;
01bd1ed2
MN
970// break;
971 case 3:
01f4895c 972 st->codec->codec_type = CODEC_TYPE_DATA;
01bd1ed2 973 break;
7c5934ed
MN
974 default:
975 av_log(s, AV_LOG_ERROR, "Unknown stream class (%d)\n", class);
ee9f36a8 976 return -1;
e52788d0 977 }
7c5934ed 978 s->bit_rate += get_v(bc);
7dddf251 979 get_vb(bc); /* language code */
7c5934ed
MN
980 nom = get_v(bc);
981 denom = get_v(bc);
982 nut->stream[stream_id].msb_timestamp_shift = get_v(bc);
01f4895c 983 st->codec->has_b_frames=
0b43db14 984 nut->stream[stream_id].decode_delay= get_v(bc);
7c5934ed
MN
985 get_byte(bc); /* flags */
986
987 /* codec specific data headers */
988 while(get_v(bc) != 0){
01f4895c
MN
989 st->codec->extradata_size= get_v(bc);
990 if((unsigned)st->codec->extradata_size > (1<<30))
568e18b1 991 return -1;
01f4895c
MN
992 st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
993 get_buffer(bc, st->codec->extradata, st->codec->extradata_size);
7c5934ed
MN
994// url_fskip(bc, get_v(bc));
995 }
e52788d0 996
01f4895c 997 if (st->codec->codec_type == CODEC_TYPE_VIDEO) /* VIDEO */
7c5934ed 998 {
01f4895c
MN
999 st->codec->width = get_v(bc);
1000 st->codec->height = get_v(bc);
1001 st->codec->sample_aspect_ratio.num= get_v(bc);
1002 st->codec->sample_aspect_ratio.den= get_v(bc);
7c5934ed 1003 get_v(bc); /* csp type */
7c5934ed 1004 }
01f4895c 1005 if (st->codec->codec_type == CODEC_TYPE_AUDIO) /* AUDIO */
7c5934ed 1006 {
01f4895c 1007 st->codec->sample_rate = get_v(bc);
0b43db14 1008 get_v(bc); // samplerate_den
01f4895c 1009 st->codec->channels = get_v(bc);
7c5934ed
MN
1010 }
1011 if(check_checksum(bc)){
160d679c 1012 av_log(s, AV_LOG_ERROR, "Stream header %d checksum mismatch\n", stream_id);
7c5934ed
MN
1013 return -1;
1014 }
cdd5034f 1015 av_set_pts_info(s->streams[stream_id], 60, denom, nom);
7c5934ed
MN
1016 nut->stream[stream_id].rate_num= nom;
1017 nut->stream[stream_id].rate_den= denom;
1018 return 0;
1019}
e52788d0 1020
7c5934ed
MN
1021static int decode_info_header(NUTContext *nut){
1022 AVFormatContext *s= nut->avf;
1023 ByteIOContext *bc = &s->pb;
1024
0b43db14 1025 get_packetheader(nut, bc, 1);
7c5934ed
MN
1026
1027 for(;;){
1028 int id= get_v(bc);
1029 char *name, *type, custom_name[256], custom_type[256];
1030
1031 if(!id)
1032 break;
1033 else if(id >= sizeof(info_table)/sizeof(info_table[0])){
1034 av_log(s, AV_LOG_ERROR, "info id is too large %d %d\n", id, sizeof(info_table)/sizeof(info_table[0]));
1035 return -1;
1036 }
e52788d0 1037
7c5934ed
MN
1038 type= info_table[id][1];
1039 name= info_table[id][0];
e52788d0
MN
1040//av_log(s, AV_LOG_DEBUG, "%d %s %s\n", id, type, name);
1041
7c5934ed
MN
1042 if(!type){
1043 get_str(bc, custom_type, sizeof(custom_type));
1044 type= custom_type;
1045 }
1046 if(!name){
1047 get_str(bc, custom_name, sizeof(custom_name));
1048 name= custom_name;
e52788d0 1049 }
7c5934ed
MN
1050
1051 if(!strcmp(type, "v")){
88730be6 1052 get_v(bc);
7c5934ed
MN
1053 }else{
1054 if(!strcmp(name, "Author"))
1055 get_str(bc, s->author, sizeof(s->author));
1056 else if(!strcmp(name, "Title"))
1057 get_str(bc, s->title, sizeof(s->title));
1058 else if(!strcmp(name, "Copyright"))
1059 get_str(bc, s->copyright, sizeof(s->copyright));
1060 else if(!strcmp(name, "Description"))
1061 get_str(bc, s->comment, sizeof(s->comment));
1062 else
1063 get_str(bc, NULL, 0);
ee9f36a8 1064 }
7c5934ed
MN
1065 }
1066 if(check_checksum(bc)){
160d679c 1067 av_log(s, AV_LOG_ERROR, "Info header checksum mismatch\n");
7c5934ed
MN
1068 return -1;
1069 }
1070 return 0;
1071}
1072
1073static int nut_read_header(AVFormatContext *s, AVFormatParameters *ap)
1074{
1075 NUTContext *nut = s->priv_data;
1076 ByteIOContext *bc = &s->pb;
1077 int64_t pos;
1078 int inited_stream_count;
1079
1080 nut->avf= s;
3aa180b8 1081
7c5934ed
MN
1082 /* main header */
1083 pos=0;
1084 for(;;){
7dddf251
MN
1085 pos= find_startcode(bc, MAIN_STARTCODE, pos)+1;
1086 if (pos<0){
7c5934ed
MN
1087 av_log(s, AV_LOG_ERROR, "no main startcode found\n");
1088 return -1;
1089 }
7c5934ed
MN
1090 if(decode_main_header(nut) >= 0)
1091 break;
1092 }
1093
1094
1095 s->bit_rate = 0;
1096
1097 nut->stream = av_malloc(sizeof(StreamContext)*nut->stream_count);
1098
1099 /* stream headers */
1100 pos=0;
1101 for(inited_stream_count=0; inited_stream_count < nut->stream_count;){
7dddf251 1102 pos= find_startcode(bc, STREAM_STARTCODE, pos)+1;
01bd1ed2 1103 if (pos<0+1){
7c5934ed
MN
1104 av_log(s, AV_LOG_ERROR, "not all stream headers found\n");
1105 return -1;
1106 }
7c5934ed
MN
1107 if(decode_stream_header(nut) >= 0)
1108 inited_stream_count++;
1109 }
1110
1111 /* info headers */
1112 pos=0;
1113 for(;;){
1114 uint64_t startcode= find_any_startcode(bc, pos);
1115 pos= url_ftell(bc);
1116
1117 if(startcode==0){
1118 av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
1119 return -1;
1120 }else if(startcode == KEYFRAME_STARTCODE){
465e1dad 1121 nut->next_startcode= startcode;
7c5934ed
MN
1122 break;
1123 }else if(startcode != INFO_STARTCODE){
1124 continue;
1125 }
1126
1127 decode_info_header(nut);
1128 }
1129
3aa180b8
AB
1130 return 0;
1131}
1132
84ad6130 1133static int decode_frame_header(NUTContext *nut, int *key_frame_ret, int64_t *pts_ret, int *stream_id_ret, int frame_code, int frame_type, int64_t frame_start){
465e1dad 1134 AVFormatContext *s= nut->avf;
a5247e3d 1135 StreamContext *stream;
3aa180b8 1136 ByteIOContext *bc = &s->pb;
84ad6130 1137 int size, flags, size_mul, size_lsb, stream_id, time_delta;
f0a93eb0 1138 int64_t pts = 0;
3aa180b8 1139
0b43db14
MN
1140 if(frame_type < 2 && frame_start - nut->packet_start[2] > nut->max_distance){
1141 av_log(s, AV_LOG_ERROR, "last frame must have been damaged\n");
1142 return -1;
1143 }
1144
1145 if(frame_type)
1146 nut->packet_start[ frame_type ]= frame_start; //otherwise 1 goto 1 may happen
1147
a5247e3d
MN
1148 flags= nut->frame_code[frame_code].flags;
1149 size_mul= nut->frame_code[frame_code].size_mul;
1150 size_lsb= nut->frame_code[frame_code].size_lsb;
1151 stream_id= nut->frame_code[frame_code].stream_id_plus1 - 1;
84ad6130
MN
1152 time_delta= nut->frame_code[frame_code].timestamp_delta;
1153
a5247e3d
MN
1154 if(stream_id==-1)
1155 stream_id= get_v(bc);
1156 if(stream_id >= s->nb_streams){
1157 av_log(s, AV_LOG_ERROR, "illegal stream_id\n");
1158 return -1;
1159 }
1160 stream= &nut->stream[stream_id];
465e1dad
MN
1161
1162// 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]);
0b43db14
MN
1163
1164 *key_frame_ret= !!(flags & FLAG_KEY_FRAME);
1165
84ad6130 1166 if(!time_delta){
0b43db14
MN
1167 int64_t mask = (1<<stream->msb_timestamp_shift)-1;
1168 pts= get_v(bc);
1169 if(pts > mask){
1170 pts -= mask+1;
a5247e3d 1171 }else{
0b43db14
MN
1172 if(stream->last_pts == AV_NOPTS_VALUE){
1173 av_log(s, AV_LOG_ERROR, "no reference pts available\n");
1174 return -1;
1175 }
1176 pts= lsb2full(stream, pts);
a5247e3d
MN
1177 }
1178 }else{
0b43db14
MN
1179 if(stream->last_pts == AV_NOPTS_VALUE){
1180 av_log(s, AV_LOG_ERROR, "no reference pts available\n");
1181 return -1;
1182 }
84ad6130 1183 pts= stream->last_pts + time_delta;
a5247e3d 1184 }
0b43db14
MN
1185
1186 if(*key_frame_ret){
0b43db14
MN
1187// av_log(s, AV_LOG_DEBUG, "stream:%d start:%lld pts:%lld length:%lld\n",stream_id, frame_start, av_pts, frame_start - nut->stream[stream_id].last_sync_pos);
1188 av_add_index_entry(
1189 s->streams[stream_id],
1190 frame_start,
cdd5034f 1191 pts,
0b43db14
MN
1192 frame_start - nut->stream[stream_id].last_sync_pos,
1193 AVINDEX_KEYFRAME);
1194 nut->stream[stream_id].last_sync_pos= frame_start;
1195// assert(nut->packet_start == frame_start);
a5247e3d 1196 }
0b43db14
MN
1197
1198 assert(size_mul > size_lsb);
1199 size= size_lsb;
1200 if(flags & FLAG_DATA_SIZE)
1201 size+= size_mul*get_v(bc);
a5247e3d 1202
84ad6130
MN
1203#ifdef TRACE
1204av_log(s, AV_LOG_DEBUG, "fs:%lld fc:%d ft:%d kf:%d pts:%lld size:%d mul:%d lsb:%d flags:%d delta:%d\n", frame_start, frame_code, frame_type, *key_frame_ret, pts, size, size_mul, size_lsb, flags, time_delta);
1205#endif
465e1dad 1206
0b43db14 1207 if(frame_type==0 && url_ftell(bc) - nut->packet_start[2] + size > nut->max_distance){
465e1dad
MN
1208 av_log(s, AV_LOG_ERROR, "frame size too large\n");
1209 return -1;
1210 }
a5247e3d 1211
0b43db14 1212 *stream_id_ret = stream_id;
cdd5034f 1213 *pts_ret = pts;
0b43db14
MN
1214
1215 update(nut, stream_id, frame_start, frame_type, frame_code, *key_frame_ret, size, pts);
1216
1217 return size;
1218}
1219
84ad6130 1220static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code, int frame_type, int64_t frame_start){
0b43db14
MN
1221 AVFormatContext *s= nut->avf;
1222 ByteIOContext *bc = &s->pb;
f3356e9c
MN
1223 int size, stream_id, key_frame, discard;
1224 int64_t pts, last_IP_pts;
0b43db14 1225
84ad6130 1226 size= decode_frame_header(nut, &key_frame, &pts, &stream_id, frame_code, frame_type, frame_start);
0b43db14
MN
1227 if(size < 0)
1228 return -1;
1229
f3356e9c
MN
1230 discard= s->streams[ stream_id ]->discard;
1231 last_IP_pts= s->streams[ stream_id ]->last_IP_pts;
1232 if( (discard >= AVDISCARD_NONKEY && !key_frame)
1233 ||(discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE && last_IP_pts > pts)
1234 || discard >= AVDISCARD_ALL){
b9866ebc
MN
1235 url_fskip(bc, size);
1236 return 1;
1237 }
1238
2692067a 1239 av_get_packet(bc, pkt, size);
a5247e3d 1240 pkt->stream_index = stream_id;
3aa180b8
AB
1241 if (key_frame)
1242 pkt->flags |= PKT_FLAG_KEY;
0b43db14 1243 pkt->pts = pts;
a5247e3d 1244
a5247e3d
MN
1245 return 0;
1246}
1247
465e1dad
MN
1248static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
1249{
1250 NUTContext *nut = s->priv_data;
1251 ByteIOContext *bc = &s->pb;
b9866ebc 1252 int i, frame_code=0, ret;
465e1dad
MN
1253
1254 for(;;){
84ad6130 1255 int64_t pos= url_ftell(bc);
7dddf251 1256 int frame_type= 0;
465e1dad
MN
1257 uint64_t tmp= nut->next_startcode;
1258 nut->next_startcode=0;
1259
1260 if (url_feof(bc))
1261 return -1;
1262
84ad6130
MN
1263 if(tmp){
1264 pos-=8;
1265 }else{
465e1dad
MN
1266 frame_code = get_byte(bc);
1267 if(frame_code == 'N'){
1268 tmp= frame_code;
7dddf251
MN
1269 for(i=1; i<8; i++)
1270 tmp = (tmp<<8) + get_byte(bc);
465e1dad
MN
1271 }
1272 }
1273 switch(tmp){
465e1dad
MN
1274 case MAIN_STARTCODE:
1275 case STREAM_STARTCODE:
1276 case INDEX_STARTCODE:
0b43db14 1277 get_packetheader(nut, bc, 0);
84ad6130 1278 assert(nut->packet_start[2] == pos);
0b43db14 1279 url_fseek(bc, nut->written_packet_size + nut->packet_start[2], SEEK_SET);
465e1dad
MN
1280 break;
1281 case INFO_STARTCODE:
1282 if(decode_info_header(nut)<0)
1283 goto resync;
1284 break;
7dddf251
MN
1285 case KEYFRAME_STARTCODE:
1286 frame_type = 2;
84ad6130 1287 reset(s, get_v(bc));
7dddf251 1288 frame_code = get_byte(bc);
465e1dad 1289 case 0:
b9866ebc
MN
1290 ret= decode_frame(nut, pkt, frame_code, frame_type, pos);
1291 if(ret==0)
465e1dad 1292 return 0;
b9866ebc
MN
1293 else if(ret==1) //ok but discard packet
1294 break;
465e1dad
MN
1295 default:
1296resync:
0b43db14
MN
1297av_log(s, AV_LOG_DEBUG, "syncing from %lld\n", nut->packet_start[2]+1);
1298 tmp= find_any_startcode(bc, nut->packet_start[2]+1);
465e1dad
MN
1299 if(tmp==0)
1300 return -1;
1301av_log(s, AV_LOG_DEBUG, "sync\n");
0b43db14 1302 nut->next_startcode= tmp;
7dddf251
MN
1303 }
1304 }
1305}
1306
8d14a25c 1307static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index, int64_t *pos_arg, int64_t pos_limit){
7dddf251 1308 NUTContext *nut = s->priv_data;
8d14a25c 1309 StreamContext *stream;
7dddf251
MN
1310 ByteIOContext *bc = &s->pb;
1311 int64_t pos, pts;
1312 uint64_t code;
0b43db14 1313 int frame_code,step, stream_id, i,size, key_frame;
7dddf251
MN
1314av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%lld,%lld)\n", stream_index, *pos_arg, pos_limit);
1315
1316 if(*pos_arg < 0)
1317 return AV_NOPTS_VALUE;
1318
7dddf251
MN
1319 pos= *pos_arg;
1320 step= FFMIN(16*1024, pos);
1321 do{
1322 pos-= step;
1323 code= find_any_startcode(bc, pos);
1324
0b43db14 1325 if(code && url_ftell(bc) - 8 <= *pos_arg)
7dddf251
MN
1326 break;
1327 step= FFMIN(2*step, pos);
1328 }while(step);
1329
1330 if(!code) //nothing found, not even after pos_arg
1331 return AV_NOPTS_VALUE;
1332
1333 url_fseek(bc, -8, SEEK_CUR);
1334 for(i=0; i<s->nb_streams; i++)
1335 nut->stream[i].last_sync_pos= url_ftell(bc);
1336
1337 for(;;){
0b43db14 1338 int frame_type=0;
7dddf251
MN
1339 int64_t pos= url_ftell(bc);
1340 uint64_t tmp=0;
7dddf251 1341
0b43db14 1342 if(pos > pos_limit || url_feof(bc))
7dddf251
MN
1343 return AV_NOPTS_VALUE;
1344
1345 frame_code = get_byte(bc);
1346 if(frame_code == 'N'){
1347 tmp= frame_code;
1348 for(i=1; i<8; i++)
1349 tmp = (tmp<<8) + get_byte(bc);
1350 }
1351//av_log(s, AV_LOG_DEBUG, "before switch %llX at=%lld\n", tmp, pos);
1352
1353 switch(tmp){
1354 case MAIN_STARTCODE:
1355 case STREAM_STARTCODE:
1356 case INDEX_STARTCODE:
1357 case INFO_STARTCODE:
0b43db14
MN
1358 get_packetheader(nut, bc, 0);
1359 assert(nut->packet_start[2]==pos);
1360 url_fseek(bc, nut->written_packet_size + pos, SEEK_SET);
7dddf251
MN
1361 break;
1362 case KEYFRAME_STARTCODE:
0b43db14 1363 frame_type=2;
84ad6130 1364 reset(s, get_v(bc));
7dddf251
MN
1365 frame_code = get_byte(bc);
1366 case 0:
84ad6130 1367 size= decode_frame_header(nut, &key_frame, &pts, &stream_id, frame_code, frame_type, pos);
0b43db14 1368 if(size < 0)
7dddf251
MN
1369 goto resync;
1370
8d14a25c 1371 stream= &nut->stream[stream_id];
0b43db14
MN
1372 if(stream_id != stream_index || !key_frame || pos < *pos_arg){
1373 url_fseek(bc, size, SEEK_CUR);
7dddf251
MN
1374 break;
1375 }
1376
0b43db14 1377 *pos_arg= pos;
7dddf251
MN
1378 return pts;
1379 default:
1380resync:
0b43db14
MN
1381av_log(s, AV_LOG_DEBUG, "syncing from %lld\n", nut->packet_start[2]+1);
1382 if(!find_any_startcode(bc, nut->packet_start[2]+1))
7dddf251
MN
1383 return AV_NOPTS_VALUE;
1384
1385 url_fseek(bc, -8, SEEK_CUR);
465e1dad
MN
1386 }
1387 }
7dddf251
MN
1388 return AV_NOPTS_VALUE;
1389}
1390
3ba1438d 1391static int nut_read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
0b43db14 1392// NUTContext *nut = s->priv_data;
8d14a25c 1393 int64_t pos;
7dddf251 1394
3ba1438d 1395 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
8d14a25c 1396 return -1;
7dddf251 1397
8d14a25c 1398 pos= url_ftell(&s->pb);
0b43db14 1399 nut_read_timestamp(s, stream_index, &pos, pos-1);
7dddf251
MN
1400
1401 return 0;
465e1dad
MN
1402}
1403
a5247e3d
MN
1404static int nut_read_close(AVFormatContext *s)
1405{
1406 NUTContext *nut = s->priv_data;
1407 int i;
1408
1409 for(i=0;i<s->nb_streams;i++) {
01f4895c 1410 av_freep(&s->streams[i]->codec->extradata);
a5247e3d
MN
1411 }
1412 av_freep(&nut->stream);
3aa180b8
AB
1413
1414 return 0;
1415}
1416
1417static AVInputFormat nut_iformat = {
1418 "nut",
1419 "nut format",
1420 sizeof(NUTContext),
1421 nut_probe,
1422 nut_read_header,
1423 nut_read_packet,
a5247e3d 1424 nut_read_close,
7dddf251 1425 nut_read_seek,
8d14a25c 1426 nut_read_timestamp,
3aa180b8
AB
1427 .extensions = "nut",
1428};
1429
764ef400 1430#ifdef CONFIG_ENCODERS
3aa180b8
AB
1431static AVOutputFormat nut_oformat = {
1432 "nut",
1433 "nut format",
1434 "video/x-nut",
1435 "nut",
1436 sizeof(NUTContext),
5c5dea3f 1437#ifdef CONFIG_LIBVORBIS
3aa180b8
AB
1438 CODEC_ID_VORBIS,
1439#elif defined(CONFIG_MP3LAME)
80783dc2 1440 CODEC_ID_MP3,
3aa180b8 1441#else
ed0bb7be 1442 CODEC_ID_MP2, /* AC3 needs liba52 decoder */
3aa180b8
AB
1443#endif
1444 CODEC_ID_MPEG4,
1445 nut_write_header,
1446 nut_write_packet,
1447 nut_write_trailer,
16423e17 1448 .flags = AVFMT_GLOBALHEADER,
3aa180b8 1449};
764ef400 1450#endif //CONFIG_ENCODERS
3aa180b8
AB
1451
1452int nut_init(void)
1453{
1454 av_register_input_format(&nut_iformat);
764ef400 1455#ifdef CONFIG_ENCODERS
3aa180b8 1456 av_register_output_format(&nut_oformat);
764ef400 1457#endif //CONFIG_ENCODERS
3aa180b8
AB
1458 return 0;
1459}