]> git.sesse.net Git - vlc/blob - modules/demux/nuv.c
0230ec20c371b17e7c3e38ed15106287783691d0
[vlc] / modules / demux / nuv.c
1 /*****************************************************************************
2  * nuv.c:
3  *****************************************************************************
4  * Copyright (C) 2005 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gertjan Van Droogenbroeck <gertjanvd _PLUS_ vlc _AT_ gmail _DOT_ com>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <assert.h>
33
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
36 #include <vlc_demux.h>
37 #include <vlc_memory.h>
38
39 /* TODO:
40  *  - test
41  */
42
43 /*****************************************************************************
44  * Module descriptor
45  *****************************************************************************/
46 static int  Open  ( vlc_object_t * );
47 static void Close ( vlc_object_t * );
48
49 vlc_module_begin ()
50     set_category( CAT_INPUT )
51     set_subcategory( SUBCAT_INPUT_DEMUX )
52     set_description( N_("Nuv demuxer") )
53     set_capability( "demux", 145 )
54     set_callbacks( Open, Close )
55     add_shortcut( "nuv" )
56 vlc_module_end ()
57
58 /*****************************************************************************
59  * Local prototypes
60  *****************************************************************************/
61 static int Demux  ( demux_t * );
62 static int Control( demux_t *, int, va_list );
63
64 /* */
65 typedef struct
66 {
67     int64_t i_time;
68     int64_t i_offset;
69
70 } demux_index_entry_t;
71
72 typedef struct
73 {
74     int i_idx;
75     int i_idx_max;
76
77     demux_index_entry_t *idx;
78 } demux_index_t;
79
80
81 static void demux_IndexInit( demux_index_t * );
82 static void demux_IndexClean( demux_index_t * );
83 static void demux_IndexAppend( demux_index_t *,
84                                int64_t i_time, int64_t i_offset );
85 /* Convert a time into offset */
86 static int64_t demux_IndexConvertTime( demux_index_t *, int64_t i_time );
87 /* Find the nearest offset in the index */
88 static int64_t demux_IndexFindOffset( demux_index_t *, int64_t i_offset );
89
90
91 /* */
92 typedef struct
93 {
94     char id[12];       /* "NuppelVideo\0" or "MythTVVideo\0" */
95     char version[5];    /* "x.xx\0" */
96
97     int  i_width;
98     int  i_height;
99     int  i_width_desired;
100     int  i_height_desired;
101
102     char i_mode;            /* P progressive, I interlaced */
103
104     double  d_aspect;       /* 1.0 squared pixel */
105     double  d_fps;
106
107     int     i_video_blocks; /* 0 no video, -1 unknown */
108     int     i_audio_blocks;
109     int     i_text_blocks;
110
111     int     i_keyframe_distance;
112
113 } header_t;
114
115 #define NUV_FH_SIZE 12
116 typedef struct
117 {
118     char i_type;        /* A: audio, V: video, S: sync; T: test
119                            R: Seekpoint (string:RTjjjjjjjj)
120                            D: Extra data for codec
121                            X: extended data Q: seektable */
122     char i_compression; /* V: 0 uncompressed
123                               1 RTJpeg
124                               2 RTJpeg+lzo
125                               N black frame
126                               L copy last
127                            A: 0 uncompressed (44100 1-bits, 2ch)
128                               1 lzo
129                               2 layer 2
130                               3 layer 3
131                               F flac
132                               S shorten
133                               N null frame loudless
134                               L copy last
135                             S: B audio and vdeo sync point
136                                A audio sync info (timecode == effective
137                                     dsp frequency*100)
138                                V next video sync (timecode == next video
139                                     frame num)
140                                S audio,video,text correlation */
141     char i_keyframe;    /* 0 keyframe, else no no key frame */
142     uint8_t i_filters;  /* 0x01: gauss 5 pixel (8,2,2,2,2)/16
143                            0x02: gauss 5 pixel (8,1,1,1,1)/12
144                            0x04: cartoon filter */
145
146     int i_timecode;     /* ms */
147
148     int i_length;       /* V,A,T: length of following data
149                            S: length of packet correl */
150 } frame_header_t;
151
152 typedef struct
153 {
154     int             i_version;
155     vlc_fourcc_t    i_video_fcc;
156
157     vlc_fourcc_t    i_audio_fcc;
158     int             i_audio_sample_rate;
159     int             i_audio_bits_per_sample;
160     int             i_audio_channels;
161     int             i_audio_compression_ratio;
162     int             i_audio_quality;
163     int             i_rtjpeg_quality;
164     int             i_rtjpeg_luma_filter;
165     int             i_rtjpeg_chroma_filter;
166     int             i_lavc_bitrate;
167     int             i_lavc_qmin;
168     int             i_lavc_qmax;
169     int             i_lavc_maxqdiff;
170     int64_t         i_seektable_offset;
171     int64_t         i_keyframe_adjust_offset;
172
173 } extended_header_t;
174
175 struct demux_sys_t
176 {
177     header_t          hdr;
178     extended_header_t exh;
179
180     int64_t     i_pcr;
181     es_out_id_t *p_es_video;
182     int         i_extra_f;
183     uint8_t     *p_extra_f;
184
185     es_out_id_t *p_es_audio;
186
187     /* index */
188     demux_index_t idx;
189     bool b_index;
190     bool b_seekable;
191     /* frameheader buffer */
192     uint8_t fh_buffer[NUV_FH_SIZE];
193     int64_t i_total_frames;
194     int64_t i_total_length;
195     /* first frame position (used for calculating size without seektable) */
196     int i_first_frame_offset;
197 };
198
199 static int HeaderLoad( demux_t *, header_t *h );
200 static int FrameHeaderLoad( demux_t *, frame_header_t *h );
201 static int ExtendedHeaderLoad( demux_t *, extended_header_t *h );
202 static int SeekTableLoad( demux_t *, demux_sys_t * );
203 static int ControlSetPosition( demux_t *p_demux, int64_t i_pos, bool b_guess );
204
205 /*****************************************************************************
206  * Open: initializes ES structures
207  *****************************************************************************/
208 static int Open( vlc_object_t * p_this )
209 {
210     demux_t     *p_demux = (demux_t*)p_this;
211     demux_sys_t *p_sys;
212     const uint8_t *p_peek;
213     frame_header_t fh;
214     bool  b_extended;
215
216     /* Check id */
217     if( stream_Peek( p_demux->s, &p_peek, 12 ) != 12 ||
218         ( strncmp( (char *)p_peek, "MythTVVideo", 11 ) &&
219           strncmp( (char *)p_peek, "NuppelVideo", 11 ) ) )
220         return VLC_EGENERIC;
221
222     p_sys = malloc( sizeof( demux_sys_t ) );
223     if( p_sys == NULL )
224         return VLC_ENOMEM;
225     memset( p_sys, 0, sizeof( demux_sys_t ) );
226     p_sys->p_es_video = NULL;
227     p_sys->p_es_audio = NULL;
228     p_sys->p_extra_f = NULL;
229     p_sys->i_pcr = -1;
230     p_sys->b_index = false;
231     p_sys->i_total_frames = -1;
232     p_sys->i_total_length = -1;
233     demux_IndexInit( &p_sys->idx );
234
235     p_demux->p_sys = p_sys;
236
237     /* Info about the stream */
238     stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
239 #if 0
240     if( p_sys->b_seekable )
241         msg_Dbg( p_demux, "stream is seekable" );
242     else
243         msg_Dbg( p_demux, "stream is NOT seekable" );
244 #endif
245
246     if( HeaderLoad( p_demux, &p_sys->hdr ) )
247         goto error;
248
249     /* Load 'D' */
250     if( FrameHeaderLoad( p_demux, &fh ) || fh.i_type != 'D' )
251         goto error;
252     if( fh.i_length > 0 )
253     {
254         if( fh.i_compression == 'F' || fh.i_compression == 'R' )
255         {
256             /* ffmpeg extra data */
257             p_sys->i_extra_f = fh.i_length;
258             p_sys->p_extra_f = malloc( fh.i_length );
259             if( p_sys->p_extra_f == NULL || stream_Read( p_demux->s,
260                              p_sys->p_extra_f, fh.i_length ) != fh.i_length )
261                 goto error;
262         }
263         else
264         {
265             msg_Warn( p_demux, "unsupported 'D' frame (c=%c)", fh.i_compression );
266             if( stream_Read( p_demux->s, NULL, fh.i_length ) != fh.i_length )
267                 goto error;
268         }
269     }
270
271     /* Check and load extented */
272     if( stream_Peek( p_demux->s, &p_peek, 1 ) != 1 )
273         goto error;
274     if( p_peek[0] == 'X' )
275     {
276         b_extended = true;
277
278         if( FrameHeaderLoad( p_demux, &fh ) )
279             goto error;
280         if( fh.i_length != 512 )
281             goto error;
282
283         if( ExtendedHeaderLoad( p_demux, &p_sys->exh ) )
284             goto error;
285
286         if( !p_sys->b_seekable )
287             msg_Warn( p_demux, "stream is not seekable, skipping seektable" );
288         else if( SeekTableLoad( p_demux, p_sys ) )
289             goto error;
290
291     }
292     else
293     {
294         b_extended = false;
295
296         /* XXX: for now only file with extended chunk are supported
297          * why: because else we need to have support for rtjpeg+stupid nuv shit */
298         msg_Err( p_demux, "incomplete NUV support (upload samples)" );
299         goto error;
300     }
301
302     /* Create audio/video (will work only with extended header and audio=mp3 */
303     if( p_sys->hdr.i_video_blocks != 0 )
304     {
305         es_format_t fmt;
306
307         es_format_Init( &fmt, VIDEO_ES, p_sys->exh.i_video_fcc );
308         fmt.video.i_width = p_sys->hdr.i_width;
309         fmt.video.i_height = p_sys->hdr.i_height;
310         fmt.i_extra = p_sys->i_extra_f;
311         fmt.p_extra = p_sys->p_extra_f;
312         fmt.video.i_aspect = VOUT_ASPECT_FACTOR * p_sys->hdr.d_aspect;
313
314         p_sys->p_es_video = es_out_Add( p_demux->out, &fmt );
315     }
316     if( p_sys->hdr.i_audio_blocks != 0 )
317     {
318         es_format_t fmt;
319
320         es_format_Init( &fmt, AUDIO_ES, VLC_CODEC_MPGA );
321         fmt.audio.i_rate = p_sys->exh.i_audio_sample_rate;
322         fmt.audio.i_bitspersample = p_sys->exh.i_audio_bits_per_sample;
323
324         p_sys->p_es_audio = es_out_Add( p_demux->out, &fmt );
325     }
326     if( p_sys->hdr.i_text_blocks != 0 )
327     {
328         msg_Warn( p_demux, "text not yet supported (upload samples)" );
329     }
330
331     p_sys->i_first_frame_offset = stream_Tell( p_demux->s );
332
333     /* Fill p_demux fields */
334     p_demux->pf_demux = Demux;
335     p_demux->pf_control = Control;
336
337     return VLC_SUCCESS;
338
339 error:
340     msg_Warn( p_demux, "cannot load Nuv file" );
341     p_demux->p_sys = NULL;
342     free( p_sys );
343     return VLC_EGENERIC;
344 }
345
346 /*****************************************************************************
347  * Close: frees unused data
348  *****************************************************************************/
349 static void Close( vlc_object_t * p_this )
350 {
351     demux_t        *p_demux = (demux_t*)p_this;
352     demux_sys_t    *p_sys = p_demux->p_sys;
353
354     free( p_sys->p_extra_f );
355     demux_IndexClean( &p_sys->idx );
356     free( p_sys );
357 }
358
359 /*****************************************************************************
360  * Demux: reads and demuxes data packets
361  *****************************************************************************
362  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
363  *****************************************************************************/
364 static int Demux( demux_t *p_demux )
365 {
366     demux_sys_t *p_sys = p_demux->p_sys;
367     frame_header_t fh;
368     block_t *p_data;
369
370     for( ;; )
371     {
372         if( !vlc_object_alive (p_demux) )
373             return -1;
374
375         if( FrameHeaderLoad( p_demux, &fh ) )
376             return 0;
377
378         if( fh.i_type == 'A' || fh.i_type == 'V' )
379             break;
380
381         /* TODO add support for some block type */
382
383         if( fh.i_type != 'R' && fh.i_length > 0 )
384         {
385             if( stream_Read( p_demux->s, NULL, fh.i_length ) != fh.i_length )
386                 return -1;
387         }
388     }
389
390     /* */
391     if( ( p_data = stream_Block( p_demux->s, fh.i_length ) ) == NULL )
392         return 0;
393
394     p_data->i_dts = (int64_t)fh.i_timecode * 1000;
395     p_data->i_pts = (fh.i_type == 'V') ? 0 : p_data->i_dts;
396
397     /* only add keyframes to index */
398     if( !fh.i_keyframe && !p_sys->b_index )
399         demux_IndexAppend( &p_sys->idx, p_data->i_dts, stream_Tell(p_demux->s) - NUV_FH_SIZE );
400
401     /* */
402     if( p_data->i_dts > p_sys->i_pcr )
403     {
404         p_sys->i_pcr = p_data->i_dts;
405         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr );
406     }
407
408     if( fh.i_type == 'A' && p_sys->p_es_audio )
409     {
410         if( fh.i_compression == '3' )
411             es_out_Send( p_demux->out, p_sys->p_es_audio, p_data );
412         else
413         {
414             msg_Dbg( p_demux, "unsupported compression %c for audio (upload samples)", fh.i_compression );
415             block_Release( p_data );
416         }
417     }
418     else if( fh.i_type == 'V' && p_sys->p_es_video )
419     {
420         if( fh.i_compression >='0' && fh.i_compression <='3' )
421         {
422             /* for rtjpeg data, the header is also needed */
423             p_data = block_Realloc( p_data, NUV_FH_SIZE, fh.i_length );
424             memcpy( p_data->p_buffer, p_sys->fh_buffer, NUV_FH_SIZE );
425         }
426         /* 0,1,2,3 -> rtjpeg, >=4 mpeg4 */
427         if( fh.i_compression >= '0' )
428             es_out_Send( p_demux->out, p_sys->p_es_video, p_data );
429         else
430         {
431             msg_Dbg( p_demux, "unsupported compression %c for video (upload samples)", fh.i_compression );
432             block_Release( p_data );
433         }
434     }
435     else
436     {
437         block_Release( p_data );
438     }
439
440     return 1;
441 }
442
443 /*****************************************************************************
444  * Control:
445  *****************************************************************************/
446 static int Control( demux_t *p_demux, int i_query, va_list args )
447 {
448     demux_sys_t *p_sys  = p_demux->p_sys;
449
450     double   f, *pf;
451     int64_t i64, *pi64;
452
453     switch( i_query )
454     {
455
456         case DEMUX_GET_POSITION:
457             pf = (double*)va_arg( args, double * );
458
459             if( p_sys->i_total_length > 0 && p_sys->i_pcr >= 0 )
460             {
461                 *pf = (double)p_sys->i_pcr / (double)p_sys->i_total_length;
462             }
463             else
464             {
465                 i64 = stream_Size( p_demux->s );
466                 if( i64 > 0 )
467                 {
468                     const double f_current = stream_Tell( p_demux->s );
469                     *pf = f_current / (double)i64;
470                 }
471                 else
472                 {
473                     *pf = 0.0;
474                 }
475             }
476             return VLC_SUCCESS;
477
478         case DEMUX_SET_POSITION:
479         {
480             int64_t i_pos;
481
482             f = (double)va_arg( args, double );
483
484             p_sys->i_pcr = -1;
485
486             /* first try to see if we can seek based on time (== GET_LENGTH works) */
487             if( p_sys->i_total_length > 0 && ( i_pos = demux_IndexConvertTime( &p_sys->idx, p_sys->i_total_length * f ) ) > 0 )
488                 return ControlSetPosition( p_demux, i_pos, false );
489
490             /* if not search based on total stream size */
491             else if( ( i_pos = demux_IndexFindOffset( &p_sys->idx, stream_Size( p_demux->s ) * f ) ) >= 0 )
492                 return ControlSetPosition( p_demux, i_pos, false );
493
494             else if( ( i_pos =  p_sys->i_first_frame_offset + ( stream_Size( p_demux->s ) - p_sys->i_first_frame_offset ) * f ) >= 0 )
495                 return ControlSetPosition( p_demux, i_pos, true );
496
497             else
498                 return VLC_EGENERIC;
499         }
500
501         case DEMUX_GET_TIME:
502             pi64 = (int64_t*)va_arg( args, int64_t * );
503             *pi64 = p_sys->i_pcr >= 0 ? p_sys->i_pcr : 0;
504             return VLC_SUCCESS;
505
506         case DEMUX_SET_TIME:
507         {
508             int64_t i_pos;
509             i64 = (int64_t)va_arg( args, int64_t );
510
511             p_sys->i_pcr = -1;
512
513             i_pos = demux_IndexConvertTime( &p_sys->idx, i64 );
514             if( i_pos < 0 )
515                 return VLC_EGENERIC;
516             else
517                 return ControlSetPosition( p_demux, i_pos, false );
518         }
519
520         case DEMUX_GET_LENGTH:
521             pi64 = (int64_t*)va_arg( args, int64_t * );
522             if( p_sys->i_total_length >= 0 )
523             {
524                 *pi64 = p_sys->i_total_length;
525                 return VLC_SUCCESS;
526             }
527             else if( stream_Tell( p_demux->s ) > p_sys->i_first_frame_offset )
528             {
529                 /* This should give an approximation of the total duration */
530                 *pi64 = (double)( stream_Size( p_demux->s ) - p_sys->i_first_frame_offset ) /
531                         (double)( stream_Tell( p_demux->s ) - p_sys->i_first_frame_offset )
532                         * (double)( p_sys->i_pcr >= 0 ? p_sys->i_pcr : 0 );
533                 return VLC_SUCCESS;
534             }
535             else
536                 return VLC_EGENERIC;
537
538         case DEMUX_GET_FPS:
539             pf = (double*)va_arg( args, double * );
540             *pf = p_sys->hdr.d_fps;
541             return VLC_SUCCESS;
542
543         case DEMUX_GET_META:
544         default:
545             return VLC_EGENERIC;
546
547     }
548 }
549 static int ControlSetPosition( demux_t *p_demux, int64_t i_pos, bool b_guess )
550 {
551     demux_sys_t *p_sys  = p_demux->p_sys;
552
553     if( i_pos < 0 )
554         return VLC_EGENERIC;
555
556     /* if we can seek in the stream */
557     if( p_sys->b_seekable && !b_guess )
558     {
559         if( stream_Seek( p_demux->s, i_pos ) )
560             return VLC_EGENERIC;
561     }
562     else
563     {
564         /* forward seek */
565         if( i_pos > stream_Tell( p_demux->s ) )
566         {
567             msg_Dbg( p_demux, "unable to seek, skipping frames (slow)" );
568         }
569         else
570         {
571             msg_Warn( p_demux, "unable to seek, only forward seeking is possible" );
572
573             return VLC_EGENERIC;
574         }
575     }
576
577     while( vlc_object_alive (p_demux) )
578     {
579         frame_header_t fh;
580         int64_t i_tell;
581
582         if( ( i_tell = stream_Tell( p_demux->s ) ) >= i_pos )
583             break;
584
585         if( FrameHeaderLoad( p_demux, &fh ) )
586             return VLC_EGENERIC;
587
588         if( fh.i_type == 'A' || fh.i_type == 'V' )
589         {
590             if( !fh.i_keyframe && !p_sys->b_index )
591                 demux_IndexAppend( &p_sys->idx,(int64_t)fh.i_timecode*1000, i_tell );
592         }
593
594         if( fh.i_type != 'R' && fh.i_length > 0 )
595         {
596             if( stream_Read( p_demux->s, NULL, fh.i_length ) != fh.i_length )
597                 return VLC_EGENERIC;
598         }
599     }
600
601     return VLC_SUCCESS;
602 }
603
604 /*****************************************************************************
605  *
606  *****************************************************************************/
607 static inline void GetDoubleLE( double *pd, void *src )
608 {
609     /* FIXME works only if sizeof(double) == 8 */
610 #ifdef WORDS_BIGENDIAN
611     uint8_t *p = (uint8_t*)pd, *q = (uint8_t*)src;
612     int i;
613     for( i = 0; i < 8; i++ )
614         p[i] = q[7-i];
615 #else
616     memcpy( pd, src, 8 );
617 #endif
618 }
619
620 /* HeaderLoad:
621  */
622 static int HeaderLoad( demux_t *p_demux, header_t *h )
623 {
624     uint8_t buffer[72];
625
626     if( stream_Read( p_demux->s, buffer, 72 ) != 72 )
627         return VLC_EGENERIC;
628
629     /* XXX: they are alignment to take care of (another broken format) */
630     memcpy( h->id,      &buffer[ 0], 12 );
631     memcpy( h->version, &buffer[12], 5 );
632     h->i_width = GetDWLE( &buffer[20] );
633     h->i_height = GetDWLE( &buffer[24] );
634     h->i_width_desired = GetDWLE( &buffer[28] );
635     h->i_height_desired = GetDWLE( &buffer[32] );
636     h->i_mode = buffer[36];
637     GetDoubleLE( &h->d_aspect, &buffer[40] );
638     GetDoubleLE( &h->d_fps, &buffer[48] );
639     h->i_video_blocks = GetDWLE( &buffer[56] );
640     h->i_audio_blocks = GetDWLE( &buffer[60] );
641     h->i_text_blocks = GetDWLE( &buffer[64] );
642     h->i_keyframe_distance = GetDWLE( &buffer[68] );
643 #if 0
644     msg_Dbg( p_demux, "nuv: h=%s v=%s %dx%d a=%f fps=%f v=%d a=%d t=%d kfd=%d",
645              h->id, h->version, h->i_width, h->i_height, h->d_aspect,
646              h->d_fps, h->i_video_blocks, h->i_audio_blocks, h->i_text_blocks,
647              h->i_keyframe_distance );
648 #endif
649     return VLC_SUCCESS;
650 }
651
652 /* FrameHeaderLoad:
653  */
654 static int FrameHeaderLoad( demux_t *p_demux, frame_header_t *h )
655 {
656     uint8_t* buffer = p_demux->p_sys->fh_buffer;
657
658     if( stream_Read( p_demux->s, buffer, 12 ) != 12 )
659         return VLC_EGENERIC;
660
661     h->i_type = buffer[0];
662     h->i_compression = buffer[1];
663     h->i_keyframe = buffer[2];
664     h->i_filters = buffer[3];
665
666     h->i_timecode = GetDWLE( &buffer[4] );
667     h->i_length = GetDWLE( &buffer[8] );
668 #if 0
669     msg_Dbg( p_demux, "frame hdr: t=%c c=%c k=%d f=0x%x timecode=%d l=%d",
670              h->i_type,
671              h->i_compression ? h->i_compression : ' ',
672              h->i_keyframe ? h->i_keyframe : ' ',
673              h->i_filters,
674              h->i_timecode, h->i_length );
675 #endif
676     return VLC_SUCCESS;
677 }
678
679 static int ExtendedHeaderLoad( demux_t *p_demux, extended_header_t *h )
680 {
681     uint8_t buffer[512];
682
683     if( stream_Read( p_demux->s, buffer, 512 ) != 512 )
684         return VLC_EGENERIC;
685
686     h->i_version = GetDWLE( &buffer[0] );
687     h->i_video_fcc = VLC_FOURCC( buffer[4], buffer[5], buffer[6], buffer[7] );
688     h->i_audio_fcc = VLC_FOURCC( buffer[8], buffer[9], buffer[10], buffer[11] );
689     h->i_audio_sample_rate = GetDWLE( &buffer[12] );
690     h->i_audio_bits_per_sample = GetDWLE( &buffer[16] );
691     h->i_audio_channels = GetDWLE( &buffer[20] );
692     h->i_audio_compression_ratio = GetDWLE( &buffer[24] );
693     h->i_audio_quality = GetDWLE( &buffer[28] );
694     h->i_rtjpeg_quality = GetDWLE( &buffer[32] );
695     h->i_rtjpeg_luma_filter = GetDWLE( &buffer[36] );
696     h->i_rtjpeg_chroma_filter = GetDWLE( &buffer[40] );
697     h->i_lavc_bitrate = GetDWLE( &buffer[44] );
698     h->i_lavc_qmin = GetDWLE( &buffer[48] );
699     h->i_lavc_qmin = GetDWLE( &buffer[52] );
700     h->i_lavc_maxqdiff = GetDWLE( &buffer[56] );
701     h->i_seektable_offset = GetQWLE( &buffer[60] );
702     h->i_keyframe_adjust_offset= GetQWLE( &buffer[68] );
703 #if 0
704     msg_Dbg( p_demux, "ex hdr: v=%d vffc=%4.4s afcc=%4.4s %dHz %dbits ach=%d acr=%d aq=%d"
705                       "rtjpeg q=%d lf=%d lc=%d lavc br=%d qmin=%d qmax=%d maxqdiff=%d seekableoff=%"PRIi64" keyfao=%"PRIi64,
706              h->i_version,
707              (char*)&h->i_video_fcc,
708              (char*)&h->i_audio_fcc, h->i_audio_sample_rate, h->i_audio_bits_per_sample, h->i_audio_channels,
709              h->i_audio_compression_ratio, h->i_audio_quality,
710              h->i_rtjpeg_quality, h->i_rtjpeg_luma_filter, h->i_rtjpeg_chroma_filter,
711              h->i_lavc_bitrate, h->i_lavc_qmin, h->i_lavc_qmax, h->i_lavc_maxqdiff,
712              h->i_seektable_offset, h->i_keyframe_adjust_offset );
713 #endif
714     return VLC_SUCCESS;
715 }
716
717 /*
718     typedef struct
719     {
720       int64_t i_file_offset;
721       int32_t i_keyframe_number;
722     } seektable_entry_t;
723     typedef struct
724     {
725        int32_t i_adjust;
726        int32_t i_keyframe_number;
727     } kfatable_entry_t;
728 */
729
730 static int SeekTableLoad( demux_t *p_demux, demux_sys_t *p_sys )
731 {
732     frame_header_t fh;
733     int64_t i_original_pos;
734     int64_t i_time, i_offset;
735     int keyframe, last_keyframe = 0, frame = 0, kfa_entry_id = 0;
736
737     if( p_sys->exh.i_seektable_offset <= 0 )
738         return VLC_SUCCESS;
739
740     /* Save current position */
741     i_original_pos = stream_Tell( p_demux->s );
742 #if 0
743     msg_Dbg( p_demux, "current offset %"PRIi64, i_original_pos );
744
745     msg_Dbg( p_demux, "seeking in stream to %"PRIi64, p_sys->exh.i_seektable_offset );
746 #endif
747     if( stream_Seek( p_demux->s, p_sys->exh.i_seektable_offset ) )
748         return VLC_EGENERIC;
749
750     if( FrameHeaderLoad( p_demux, &fh ) )
751         return VLC_EGENERIC;
752
753     if( fh.i_type != 'Q' )
754     {
755         msg_Warn( p_demux, "invalid seektable, frame type=%c", fh.i_type );
756         stream_Seek( p_demux->s, i_original_pos );
757         return VLC_EGENERIC;
758     }
759
760     /* */
761     uint8_t *p_seek_table = malloc( fh.i_length );
762     if( p_seek_table == NULL )
763         return VLC_ENOMEM;
764
765     if( stream_Read( p_demux->s, p_seek_table, fh.i_length ) != fh.i_length )
766     {
767         free( p_seek_table );
768         return VLC_EGENERIC;
769     }
770     const int32_t i_seek_elements = fh.i_length / 12;
771
772     /* Get keyframe adjust offsets */
773     int32_t i_kfa_elements;
774     uint8_t *p_kfa_table;
775
776     if( p_sys->exh.i_keyframe_adjust_offset > 0 )
777     {
778         msg_Dbg( p_demux, "seeking in stream to %"PRIi64, p_sys->exh.i_keyframe_adjust_offset );
779         if( stream_Seek( p_demux->s, p_sys->exh.i_keyframe_adjust_offset ) )
780         {
781             free( p_seek_table );
782             return VLC_EGENERIC;
783         }
784
785         if( FrameHeaderLoad( p_demux, &fh ) )
786         {
787             free( p_seek_table );
788             return VLC_EGENERIC;
789         }
790
791         if( fh.i_type == 'K' && fh.i_length >= 8 )
792         {
793             p_kfa_table = malloc( fh.i_length );
794
795             if( p_kfa_table == NULL )
796             {
797                 free( p_seek_table );
798                 return VLC_ENOMEM;
799             }
800
801             if( stream_Read( p_demux->s, p_kfa_table, fh.i_length ) != fh.i_length )
802             {
803                 free( p_seek_table );
804                 free( p_kfa_table );
805                 return VLC_EGENERIC;
806             }
807
808             i_kfa_elements = fh.i_length / 8;
809         }
810     }
811     else
812     {
813         i_kfa_elements = 0;
814     }
815
816
817     if( i_kfa_elements > 0 )
818         msg_Warn( p_demux, "untested keyframe adjust support, upload samples" );
819
820     for( int32_t j = 0; j < i_seek_elements; j++)
821     {
822 #if 0
823         uint8_t* p = p_seek_table + j * 12;
824         msg_Dbg( p_demux, "%x %x %x %x %x %x %x %x %x %x %x %x",
825         p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[11]);
826 #endif
827         keyframe = GetDWLE( p_seek_table + j * 12 + 8 );
828
829         frame += (keyframe - last_keyframe) * p_sys->hdr.i_keyframe_distance;
830
831         if( kfa_entry_id < i_kfa_elements && *(int32_t*)(p_kfa_table + kfa_entry_id * 12 + 4) == j )
832         {
833             frame -= *(int32_t*)(p_kfa_table + kfa_entry_id * 12);
834             msg_Dbg( p_demux, "corrected keyframe %d with current frame number %d (corrected with %d)",
835                         keyframe, frame, *(int32_t*)(p_kfa_table + kfa_entry_id * 12) );
836             kfa_entry_id++;
837         }
838
839         i_time = (double)( (int64_t)frame * 1000000 ) / p_sys->hdr.d_fps;
840         i_offset = GetQWLE( p_seek_table + j * 12 );
841
842         if( i_offset == 0 && i_time != 0 )
843             msg_Dbg( p_demux, "invalid file offset %d %"PRIi64, keyframe, i_offset );
844         else
845         {
846             demux_IndexAppend( &p_sys->idx, i_time , i_offset );
847 #if 0
848             msg_Dbg( p_demux, "adding entry position %d %"PRIi64 " file offset %"PRIi64, keyframe, i_time, i_offset );
849 #endif
850         }
851
852         last_keyframe = keyframe;
853     }
854
855     p_sys->i_total_frames = (int64_t)frame;
856
857     p_sys->b_index = true;
858
859     p_sys->i_total_length = p_sys->i_total_frames * 1000000 / p_sys->hdr.d_fps;
860
861     msg_Dbg( p_demux, "index table loaded (%d elements)", i_seek_elements );
862
863     if( i_kfa_elements )
864         free ( p_kfa_table );
865
866     free ( p_seek_table );
867
868     /* Restore stream position */
869     if( stream_Seek( p_demux->s, i_original_pos ) )
870         return VLC_EGENERIC;
871
872     return VLC_SUCCESS;
873
874 }
875
876 /*****************************************************************************/
877 #define DEMUX_INDEX_SIZE_MAX (100000)
878 static void demux_IndexInit( demux_index_t *p_idx )
879 {
880     p_idx->i_idx = 0;
881     p_idx->i_idx_max = 0;
882     p_idx->idx = NULL;
883 }
884 static void demux_IndexClean( demux_index_t *p_idx )
885 {
886     free( p_idx->idx );
887     p_idx->idx = NULL;
888 }
889 static void demux_IndexAppend( demux_index_t *p_idx,
890                                int64_t i_time, int64_t i_offset )
891 {
892     /* Be sure to append new entry (we don't insert point) */
893     if( p_idx->i_idx > 0 && p_idx->idx[p_idx->i_idx-1].i_time >= i_time )
894         return;
895
896     /* */
897     if( p_idx->i_idx >= p_idx->i_idx_max )
898     {
899         if( p_idx->i_idx >= DEMUX_INDEX_SIZE_MAX )
900         {
901             /* Avoid too big index */
902             const int64_t i_length = p_idx->idx[p_idx->i_idx-1].i_time -
903                                                         p_idx->idx[0].i_time;
904             const int i_count = DEMUX_INDEX_SIZE_MAX/2;
905             int i, j;
906
907             /* We try to reduce the resolution of the index by a factor 2 */
908             for( i = 1, j = 1; i < p_idx->i_idx; i++ )
909             {
910                 if( p_idx->idx[i].i_time < j * i_length / i_count )
911                     continue;
912
913                 p_idx->idx[j++] = p_idx->idx[i];
914             }
915             p_idx->i_idx = j;
916
917             if( p_idx->i_idx > 3 * DEMUX_INDEX_SIZE_MAX / 4 )
918             {
919                 /* We haven't created enough space
920                  * (This method won't create a good index but work for sure) */
921                 for( i = 0; i < p_idx->i_idx/2; i++ )
922                     p_idx->idx[i] = p_idx->idx[2*i];
923                 p_idx->i_idx /= 2;
924             }
925         }
926         else
927         {
928             p_idx->i_idx_max += 1000;
929             p_idx->idx = realloc_or_free( p_idx->idx,
930                                 p_idx->i_idx_max*sizeof(demux_index_entry_t));
931             assert( p_idx->idx );
932         }
933     }
934
935     /* */
936     p_idx->idx[p_idx->i_idx].i_time = i_time;
937     p_idx->idx[p_idx->i_idx].i_offset = i_offset;
938
939     p_idx->i_idx++;
940 }
941 static int64_t demux_IndexConvertTime( demux_index_t *p_idx, int64_t i_time )
942 {
943     int i_min = 0;
944     int i_max = p_idx->i_idx-1;
945
946     /* Empty index */
947     if( p_idx->i_idx <= 0 )
948         return -1;
949
950     /* Special border case */
951     if( i_time <= p_idx->idx[0].i_time )
952         return p_idx->idx[0].i_offset;
953     if( i_time >= p_idx->idx[i_max].i_time )
954         return p_idx->idx[i_max].i_offset;
955
956     /* Dicho */
957     for( ;; )
958     {
959         int i_med;
960
961         if( i_max - i_min <= 1 )
962             break;
963
964         i_med = (i_min+i_max)/2;
965         if( p_idx->idx[i_med].i_time < i_time )
966             i_min = i_med;
967         else if( p_idx->idx[i_med].i_time > i_time )
968             i_max = i_med;
969         else
970             return p_idx->idx[i_med].i_offset;
971     }
972
973     /* return nearest in time */
974     if( i_time - p_idx->idx[i_min].i_time < p_idx->idx[i_max].i_time - i_time )
975         return p_idx->idx[i_min].i_offset;
976     else
977         return p_idx->idx[i_max].i_offset;
978 }
979
980
981 static int64_t demux_IndexFindOffset( demux_index_t *p_idx, int64_t i_offset )
982 {
983     int i_min = 0;
984     int i_max = p_idx->i_idx-1;
985
986     /* Empty index */
987     if( p_idx->i_idx <= 0 )
988         return -1;
989
990     /* Special border case */
991     if( i_offset <= p_idx->idx[0].i_offset )
992         return p_idx->idx[0].i_offset;
993     if( i_offset == p_idx->idx[i_max].i_offset )
994         return p_idx->idx[i_max].i_offset;
995     if( i_offset > p_idx->idx[i_max].i_offset )
996         return -1;
997
998     /* Dicho */
999     for( ;; )
1000     {
1001         int i_med;
1002
1003         if( i_max - i_min <= 1 )
1004             break;
1005
1006         i_med = (i_min+i_max)/2;
1007         if( p_idx->idx[i_med].i_offset < i_offset )
1008             i_min = i_med;
1009         else if( p_idx->idx[i_med].i_offset > i_offset )
1010             i_max = i_med;
1011         else
1012             return p_idx->idx[i_med].i_offset;
1013     }
1014
1015     /* return nearest */
1016     if( i_offset - p_idx->idx[i_min].i_offset < p_idx->idx[i_max].i_offset - i_offset )
1017         return p_idx->idx[i_min].i_offset;
1018     else
1019         return p_idx->idx[i_max].i_offset;
1020 }
1021