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