]> git.sesse.net Git - vlc/blob - modules/demux/nuv.c
fingerprinter: don't hardcode acoustid module selection
[vlc] / modules / demux / nuv.c
1 /*****************************************************************************
2  * nuv.c:
3  *****************************************************************************
4  * Copyright (C) 2005 VLC authors and VideoLAN
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 it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * 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
212     /* Check id */
213     if( stream_Peek( p_demux->s, &p_peek, 12 ) != 12 ||
214         ( strncmp( (char *)p_peek, "MythTVVideo", 11 ) &&
215           strncmp( (char *)p_peek, "NuppelVideo", 11 ) ) )
216         return VLC_EGENERIC;
217
218     p_sys = malloc( sizeof( demux_sys_t ) );
219     if( p_sys == NULL )
220         return VLC_ENOMEM;
221     memset( p_sys, 0, sizeof( demux_sys_t ) );
222     p_sys->p_es_video = NULL;
223     p_sys->p_es_audio = NULL;
224     p_sys->p_extra_f = NULL;
225     p_sys->i_pcr = -1;
226     p_sys->b_index = false;
227     p_sys->i_total_frames = -1;
228     p_sys->i_total_length = -1;
229     demux_IndexInit( &p_sys->idx );
230
231     p_demux->p_sys = p_sys;
232
233     /* Info about the stream */
234     stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
235 #if 0
236     if( p_sys->b_seekable )
237         msg_Dbg( p_demux, "stream is seekable" );
238     else
239         msg_Dbg( p_demux, "stream is NOT seekable" );
240 #endif
241
242     if( HeaderLoad( p_demux, &p_sys->hdr ) )
243         goto error;
244
245     /* Load 'D' */
246     if( FrameHeaderLoad( p_demux, &fh ) || fh.i_type != 'D' )
247         goto error;
248     if( fh.i_length > 0 )
249     {
250         if( fh.i_compression == 'F' || fh.i_compression == 'R' )
251         {
252             /* ffmpeg extra data */
253             p_sys->i_extra_f = fh.i_length;
254             p_sys->p_extra_f = malloc( fh.i_length );
255             if( p_sys->p_extra_f == NULL || stream_Read( p_demux->s,
256                              p_sys->p_extra_f, fh.i_length ) != fh.i_length )
257                 goto error;
258         }
259         else
260         {
261             msg_Warn( p_demux, "unsupported 'D' frame (c=%c)", fh.i_compression );
262             if( stream_Read( p_demux->s, NULL, fh.i_length ) != fh.i_length )
263                 goto error;
264         }
265     }
266
267     /* Check and load extented */
268     if( stream_Peek( p_demux->s, &p_peek, 1 ) != 1 )
269         goto error;
270     if( p_peek[0] == 'X' )
271     {
272         if( FrameHeaderLoad( p_demux, &fh ) )
273             goto error;
274         if( fh.i_length != 512 )
275             goto error;
276
277         if( ExtendedHeaderLoad( p_demux, &p_sys->exh ) )
278             goto error;
279
280         if( !p_sys->b_seekable )
281             msg_Warn( p_demux, "stream is not seekable, skipping seektable" );
282         else if( SeekTableLoad( p_demux, p_sys ) )
283         {
284             p_sys->b_index = false;
285             msg_Warn( p_demux, "Seektable is broken, seek won't be accurate" );
286         }
287     }
288     else
289     {
290         /* XXX: for now only file with extended chunk are supported
291          * why: because else we need to have support for rtjpeg+stupid nuv shit */
292         msg_Err( p_demux, "VLC doesn't support NUV without extended chunks (please upload samples)" );
293         goto error;
294     }
295
296     /* Create audio/video (will work only with extended header and audio=mp3 */
297     if( p_sys->hdr.i_video_blocks != 0 )
298     {
299         es_format_t fmt;
300
301         es_format_Init( &fmt, VIDEO_ES, p_sys->exh.i_video_fcc );
302         fmt.video.i_width = p_sys->hdr.i_width;
303         fmt.video.i_height = p_sys->hdr.i_height;
304         fmt.i_extra = p_sys->i_extra_f;
305         fmt.p_extra = p_sys->p_extra_f;
306         fmt.video.i_sar_num = p_sys->hdr.d_aspect * fmt.video.i_height;
307         fmt.video.i_sar_den = fmt.video.i_width;
308
309         p_sys->p_es_video = es_out_Add( p_demux->out, &fmt );
310     }
311     if( p_sys->hdr.i_audio_blocks != 0 )
312     {
313         es_format_t fmt;
314
315         es_format_Init( &fmt, AUDIO_ES, VLC_CODEC_MPGA );
316         fmt.audio.i_rate = p_sys->exh.i_audio_sample_rate;
317         fmt.audio.i_bitspersample = p_sys->exh.i_audio_bits_per_sample;
318
319         p_sys->p_es_audio = es_out_Add( p_demux->out, &fmt );
320     }
321     if( p_sys->hdr.i_text_blocks != 0 )
322     {
323         msg_Warn( p_demux, "text not yet supported (upload samples)" );
324     }
325
326     p_sys->i_first_frame_offset = stream_Tell( p_demux->s );
327
328     /* Fill p_demux fields */
329     p_demux->pf_demux = Demux;
330     p_demux->pf_control = Control;
331
332     return VLC_SUCCESS;
333
334 error:
335     msg_Warn( p_demux, "cannot load Nuv file" );
336     p_demux->p_sys = NULL;
337     free( p_sys );
338     return VLC_EGENERIC;
339 }
340
341 /*****************************************************************************
342  * Close: frees unused data
343  *****************************************************************************/
344 static void Close( vlc_object_t * p_this )
345 {
346     demux_t        *p_demux = (demux_t*)p_this;
347     demux_sys_t    *p_sys = p_demux->p_sys;
348
349     free( p_sys->p_extra_f );
350     demux_IndexClean( &p_sys->idx );
351     free( p_sys );
352 }
353
354 /*****************************************************************************
355  * Demux: reads and demuxes data packets
356  *****************************************************************************
357  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
358  *****************************************************************************/
359 static int Demux( demux_t *p_demux )
360 {
361     demux_sys_t *p_sys = p_demux->p_sys;
362     frame_header_t fh;
363     block_t *p_data;
364
365     for( ;; )
366     {
367         if( !vlc_object_alive (p_demux) )
368             return -1;
369
370         if( FrameHeaderLoad( p_demux, &fh ) )
371             return 0;
372
373         if( fh.i_type == 'A' || fh.i_type == 'V' )
374             break;
375
376         /* TODO add support for some block type */
377
378         if( fh.i_type != 'R' && fh.i_length > 0 )
379         {
380             if( stream_Read( p_demux->s, NULL, fh.i_length ) != fh.i_length )
381                 return -1;
382         }
383     }
384
385     /* */
386     if( ( p_data = stream_Block( p_demux->s, fh.i_length ) ) == NULL )
387         return 0;
388
389     p_data->i_dts = VLC_TS_0 + (int64_t)fh.i_timecode * 1000;
390     p_data->i_pts = (fh.i_type == 'V') ? VLC_TS_INVALID : p_data->i_dts;
391
392     /* only add keyframes to index */
393     if( !fh.i_keyframe && !p_sys->b_index )
394         demux_IndexAppend( &p_sys->idx,
395                            p_data->i_dts - VLC_TS_0,
396                            stream_Tell(p_demux->s) - NUV_FH_SIZE );
397
398     /* */
399     if( p_sys->i_pcr < 0 || p_sys->i_pcr < p_data->i_dts - VLC_TS_0 )
400     {
401         p_sys->i_pcr = p_data->i_dts - VLC_TS_0;
402         es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + 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             if( unlikely(!p_data) )
422                 abort();
423             memcpy( p_data->p_buffer, p_sys->fh_buffer, NUV_FH_SIZE );
424         }
425         /* 0,1,2,3 -> rtjpeg, >=4 mpeg4 */
426         if( fh.i_compression >= '0' )
427             es_out_Send( p_demux->out, p_sys->p_es_video, p_data );
428         else
429         {
430             msg_Dbg( p_demux, "unsupported compression %c for video (upload samples)", fh.i_compression );
431             block_Release( p_data );
432         }
433     }
434     else
435     {
436         block_Release( p_data );
437     }
438
439     return 1;
440 }
441
442 /*****************************************************************************
443  * Control:
444  *****************************************************************************/
445 static int Control( demux_t *p_demux, int i_query, va_list args )
446 {
447     demux_sys_t *p_sys  = p_demux->p_sys;
448
449     double   f, *pf;
450     int64_t i64, *pi64;
451
452     switch( i_query )
453     {
454
455         case DEMUX_GET_POSITION:
456             pf = (double*)va_arg( args, double * );
457
458             if( p_sys->i_total_length > 0 && p_sys->i_pcr >= 0 )
459             {
460                 *pf = (double)p_sys->i_pcr / (double)p_sys->i_total_length;
461             }
462             else
463             {
464                 i64 = stream_Size( p_demux->s );
465                 if( i64 > 0 )
466                 {
467                     const double f_current = stream_Tell( p_demux->s );
468                     *pf = f_current / (double)i64;
469                 }
470                 else
471                 {
472                     *pf = 0.0;
473                 }
474             }
475             return VLC_SUCCESS;
476
477         case DEMUX_SET_POSITION:
478         {
479             int64_t i_pos;
480
481             f = (double)va_arg( args, double );
482
483             p_sys->i_pcr = -1;
484
485             /* first try to see if we can seek based on time (== GET_LENGTH works) */
486             if( p_sys->i_total_length > 0 && ( i_pos = demux_IndexConvertTime( &p_sys->idx, p_sys->i_total_length * f ) ) > 0 )
487                 return ControlSetPosition( p_demux, i_pos, false );
488
489             /* if not search based on total stream size */
490             else if( ( i_pos = demux_IndexFindOffset( &p_sys->idx, stream_Size( p_demux->s ) * f ) ) >= 0 )
491                 return ControlSetPosition( p_demux, i_pos, false );
492
493             else if( ( i_pos =  p_sys->i_first_frame_offset + ( stream_Size( p_demux->s ) - p_sys->i_first_frame_offset ) * f ) >= 0 )
494                 return ControlSetPosition( p_demux, i_pos, true );
495
496             else
497                 return VLC_EGENERIC;
498         }
499
500         case DEMUX_GET_TIME:
501             pi64 = (int64_t*)va_arg( args, int64_t * );
502             *pi64 = p_sys->i_pcr >= 0 ? p_sys->i_pcr : 0;
503             return VLC_SUCCESS;
504
505         case DEMUX_SET_TIME:
506         {
507             int64_t i_pos;
508             i64 = (int64_t)va_arg( args, int64_t );
509
510             p_sys->i_pcr = -1;
511
512             i_pos = demux_IndexConvertTime( &p_sys->idx, i64 );
513             if( i_pos < 0 )
514                 return VLC_EGENERIC;
515             else
516                 return ControlSetPosition( p_demux, i_pos, false );
517         }
518
519         case DEMUX_GET_LENGTH:
520             pi64 = (int64_t*)va_arg( args, int64_t * );
521             if( p_sys->i_total_length >= 0 )
522             {
523                 *pi64 = p_sys->i_total_length;
524                 return VLC_SUCCESS;
525             }
526             else if( stream_Tell( p_demux->s ) > p_sys->i_first_frame_offset )
527             {
528                 /* This should give an approximation of the total duration */
529                 *pi64 = (double)( stream_Size( p_demux->s ) - p_sys->i_first_frame_offset ) /
530                         (double)( stream_Tell( p_demux->s ) - p_sys->i_first_frame_offset )
531                         * (double)( p_sys->i_pcr >= 0 ? p_sys->i_pcr : 0 );
532                 return VLC_SUCCESS;
533             }
534             else
535                 return VLC_EGENERIC;
536
537         case DEMUX_GET_FPS:
538             pf = (double*)va_arg( args, double * );
539             *pf = p_sys->hdr.d_fps;
540             return VLC_SUCCESS;
541
542         case DEMUX_GET_META:
543         default:
544             return VLC_EGENERIC;
545
546     }
547 }
548 static int ControlSetPosition( demux_t *p_demux, int64_t i_pos, bool b_guess )
549 {
550     demux_sys_t *p_sys  = p_demux->p_sys;
551
552     if( i_pos < 0 )
553         return VLC_EGENERIC;
554
555     /* if we can seek in the stream */
556     if( p_sys->b_seekable && !b_guess )
557     {
558         if( stream_Seek( p_demux->s, i_pos ) )
559             return VLC_EGENERIC;
560     }
561     else
562     {
563         /* forward seek */
564         if( i_pos > stream_Tell( p_demux->s ) )
565         {
566             msg_Dbg( p_demux, "unable to seek, skipping frames (slow)" );
567         }
568         else
569         {
570             msg_Warn( p_demux, "unable to seek, only forward seeking is possible" );
571
572             return VLC_EGENERIC;
573         }
574     }
575
576     while( vlc_object_alive (p_demux) )
577     {
578         frame_header_t fh;
579         int64_t i_tell;
580
581         if( ( i_tell = stream_Tell( p_demux->s ) ) >= i_pos )
582             break;
583
584         if( FrameHeaderLoad( p_demux, &fh ) )
585             return VLC_EGENERIC;
586
587         if( fh.i_type == 'A' || fh.i_type == 'V' )
588         {
589             if( !fh.i_keyframe && !p_sys->b_index )
590                 demux_IndexAppend( &p_sys->idx,(int64_t)fh.i_timecode*1000, i_tell );
591         }
592
593         if( fh.i_type != 'R' && fh.i_length > 0 )
594         {
595             if( stream_Read( p_demux->s, NULL, fh.i_length ) != fh.i_length )
596                 return VLC_EGENERIC;
597         }
598     }
599
600     return VLC_SUCCESS;
601 }
602
603 /*****************************************************************************
604  *
605  *****************************************************************************/
606 static inline void GetDoubleLE( double *pd, void *src )
607 {
608     /* FIXME works only if sizeof(double) == 8 */
609 #ifdef WORDS_BIGENDIAN
610     uint8_t *p = (uint8_t*)pd, *q = (uint8_t*)src;
611     int i;
612     for( i = 0; i < 8; i++ )
613         p[i] = q[7-i];
614 #else
615     memcpy( pd, src, 8 );
616 #endif
617 }
618
619 /* HeaderLoad:
620  */
621 static int HeaderLoad( demux_t *p_demux, header_t *h )
622 {
623     uint8_t buffer[72];
624
625     if( stream_Read( p_demux->s, buffer, 72 ) != 72 )
626         return VLC_EGENERIC;
627
628     /* XXX: they are alignment to take care of (another broken format) */
629     memcpy( h->id,      &buffer[ 0], 12 );
630     memcpy( h->version, &buffer[12], 5 );
631     h->i_width = GetDWLE( &buffer[20] );
632     h->i_height = GetDWLE( &buffer[24] );
633     h->i_width_desired = GetDWLE( &buffer[28] );
634     h->i_height_desired = GetDWLE( &buffer[32] );
635     h->i_mode = buffer[36];
636     GetDoubleLE( &h->d_aspect, &buffer[40] );
637     GetDoubleLE( &h->d_fps, &buffer[48] );
638     h->i_video_blocks = GetDWLE( &buffer[56] );
639     h->i_audio_blocks = GetDWLE( &buffer[60] );
640     h->i_text_blocks = GetDWLE( &buffer[64] );
641     h->i_keyframe_distance = GetDWLE( &buffer[68] );
642 #if 0
643     msg_Dbg( p_demux, "nuv: h=%s v=%s %dx%d a=%f fps=%f v=%d a=%d t=%d kfd=%d",
644              h->id, h->version, h->i_width, h->i_height, h->d_aspect,
645              h->d_fps, h->i_video_blocks, h->i_audio_blocks, h->i_text_blocks,
646              h->i_keyframe_distance );
647 #endif
648     return VLC_SUCCESS;
649 }
650
651 /* FrameHeaderLoad:
652  */
653 static int FrameHeaderLoad( demux_t *p_demux, frame_header_t *h )
654 {
655     uint8_t* buffer = p_demux->p_sys->fh_buffer;
656
657     if( stream_Read( p_demux->s, buffer, 12 ) != 12 )
658         return VLC_EGENERIC;
659
660     h->i_type = buffer[0];
661     h->i_compression = buffer[1];
662     h->i_keyframe = buffer[2];
663     h->i_filters = buffer[3];
664
665     h->i_timecode = GetDWLE( &buffer[4] );
666     h->i_length = GetDWLE( &buffer[8] );
667 #if 0
668     msg_Dbg( p_demux, "frame hdr: t=%c c=%c k=%d f=0x%x timecode=%d l=%d",
669              h->i_type,
670              h->i_compression ? h->i_compression : ' ',
671              h->i_keyframe ? h->i_keyframe : ' ',
672              h->i_filters,
673              h->i_timecode, h->i_length );
674 #endif
675     return VLC_SUCCESS;
676 }
677
678 static int ExtendedHeaderLoad( demux_t *p_demux, extended_header_t *h )
679 {
680     uint8_t buffer[512];
681
682     if( stream_Read( p_demux->s, buffer, 512 ) != 512 )
683         return VLC_EGENERIC;
684
685     h->i_version = GetDWLE( &buffer[0] );
686     h->i_video_fcc = VLC_FOURCC( buffer[4], buffer[5], buffer[6], buffer[7] );
687     h->i_audio_fcc = VLC_FOURCC( buffer[8], buffer[9], buffer[10], buffer[11] );
688     h->i_audio_sample_rate = GetDWLE( &buffer[12] );
689     h->i_audio_bits_per_sample = GetDWLE( &buffer[16] );
690     h->i_audio_channels = GetDWLE( &buffer[20] );
691     h->i_audio_compression_ratio = GetDWLE( &buffer[24] );
692     h->i_audio_quality = GetDWLE( &buffer[28] );
693     h->i_rtjpeg_quality = GetDWLE( &buffer[32] );
694     h->i_rtjpeg_luma_filter = GetDWLE( &buffer[36] );
695     h->i_rtjpeg_chroma_filter = GetDWLE( &buffer[40] );
696     h->i_lavc_bitrate = GetDWLE( &buffer[44] );
697     h->i_lavc_qmin = GetDWLE( &buffer[48] );
698     h->i_lavc_qmin = GetDWLE( &buffer[52] );
699     h->i_lavc_maxqdiff = GetDWLE( &buffer[56] );
700     h->i_seektable_offset = GetQWLE( &buffer[60] );
701     h->i_keyframe_adjust_offset= GetQWLE( &buffer[68] );
702 #if 0
703     msg_Dbg( p_demux, "ex hdr: v=%d vffc=%4.4s afcc=%4.4s %dHz %dbits ach=%d acr=%d aq=%d"
704                       "rtjpeg q=%d lf=%d lc=%d lavc br=%d qmin=%d qmax=%d maxqdiff=%d seekableoff=%"PRIi64" keyfao=%"PRIi64,
705              h->i_version,
706              (char*)&h->i_video_fcc,
707              (char*)&h->i_audio_fcc, h->i_audio_sample_rate, h->i_audio_bits_per_sample, h->i_audio_channels,
708              h->i_audio_compression_ratio, h->i_audio_quality,
709              h->i_rtjpeg_quality, h->i_rtjpeg_luma_filter, h->i_rtjpeg_chroma_filter,
710              h->i_lavc_bitrate, h->i_lavc_qmin, h->i_lavc_qmax, h->i_lavc_maxqdiff,
711              h->i_seektable_offset, h->i_keyframe_adjust_offset );
712 #endif
713     return VLC_SUCCESS;
714 }
715
716 /*
717     typedef struct
718     {
719       int64_t i_file_offset;
720       int32_t i_keyframe_number;
721     } seektable_entry_t;
722     typedef struct
723     {
724        int32_t i_adjust;
725        int32_t i_keyframe_number;
726     } kfatable_entry_t;
727 */
728
729 static int SeekTableLoad( demux_t *p_demux, demux_sys_t *p_sys )
730 {
731     frame_header_t fh;
732     int64_t i_original_pos;
733     int64_t i_time, i_offset;
734     int keyframe, last_keyframe = 0, frame = 0, kfa_entry_id = 0;
735
736     if( p_sys->exh.i_seektable_offset <= 0 )
737         return VLC_SUCCESS;
738
739     /* Save current position */
740     i_original_pos = stream_Tell( p_demux->s );
741 #if 0
742     msg_Dbg( p_demux, "current offset %"PRIi64, i_original_pos );
743
744     msg_Dbg( p_demux, "seeking in stream to %"PRIi64, p_sys->exh.i_seektable_offset );
745 #endif
746     if( stream_Seek( p_demux->s, p_sys->exh.i_seektable_offset ) )
747         return VLC_EGENERIC;
748
749     if( FrameHeaderLoad( p_demux, &fh ) )
750         return VLC_EGENERIC;
751
752     if( fh.i_type != 'Q' )
753     {
754         msg_Warn( p_demux, "invalid seektable, frame type=%c", fh.i_type );
755         stream_Seek( p_demux->s, i_original_pos );
756         return VLC_EGENERIC;
757     }
758
759     /* */
760     uint8_t *p_seek_table = malloc( fh.i_length );
761     if( p_seek_table == NULL )
762         return VLC_ENOMEM;
763
764     if( stream_Read( p_demux->s, p_seek_table, fh.i_length ) != fh.i_length )
765     {
766         free( p_seek_table );
767         return VLC_EGENERIC;
768     }
769     const int32_t i_seek_elements = fh.i_length / 12;
770
771     /* Get keyframe adjust offsets */
772     int32_t i_kfa_elements = 0;
773     uint8_t *p_kfa_table = NULL;
774
775     if( p_sys->exh.i_keyframe_adjust_offset > 0 )
776     {
777         msg_Dbg( p_demux, "seeking in stream to %"PRIi64, p_sys->exh.i_keyframe_adjust_offset );
778         if( stream_Seek( p_demux->s, p_sys->exh.i_keyframe_adjust_offset ) )
779         {
780             free( p_seek_table );
781             return VLC_EGENERIC;
782         }
783
784         if( FrameHeaderLoad( p_demux, &fh ) )
785         {
786             free( p_seek_table );
787             return VLC_EGENERIC;
788         }
789
790         if( fh.i_type == 'K' && fh.i_length >= 8 )
791         {
792             p_kfa_table = malloc( fh.i_length );
793
794             if( p_kfa_table == NULL )
795             {
796                 free( p_seek_table );
797                 return VLC_ENOMEM;
798             }
799
800             if( stream_Read( p_demux->s, p_kfa_table, fh.i_length ) != fh.i_length )
801             {
802                 free( p_seek_table );
803                 free( p_kfa_table );
804                 return VLC_EGENERIC;
805             }
806
807             i_kfa_elements = fh.i_length / 8;
808         }
809     }
810
811     if( i_kfa_elements > 0 )
812         msg_Warn( p_demux, "untested keyframe adjust support, upload samples" );
813
814     for( int32_t j = 0; j < i_seek_elements; j++)
815     {
816 #if 0
817         uint8_t* p = p_seek_table + j * 12;
818         msg_Dbg( p_demux, "%x %x %x %x %x %x %x %x %x %x %x %x",
819         p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[11]);
820 #endif
821         keyframe = GetDWLE( p_seek_table + j * 12 + 8 );
822
823         frame += (keyframe - last_keyframe) * p_sys->hdr.i_keyframe_distance;
824
825         if( kfa_entry_id < i_kfa_elements && *(int32_t*)(p_kfa_table + kfa_entry_id * 12 + 4) == j )
826         {
827             frame -= *(int32_t*)(p_kfa_table + kfa_entry_id * 12);
828             msg_Dbg( p_demux, "corrected keyframe %d with current frame number %d (corrected with %d)",
829                         keyframe, frame, *(int32_t*)(p_kfa_table + kfa_entry_id * 12) );
830             kfa_entry_id++;
831         }
832
833         i_time = (double)( (int64_t)frame * 1000000 ) / p_sys->hdr.d_fps;
834         i_offset = GetQWLE( p_seek_table + j * 12 );
835
836         if( i_offset == 0 && i_time != 0 )
837             msg_Dbg( p_demux, "invalid file offset %d %"PRIi64, keyframe, i_offset );
838         else
839         {
840             demux_IndexAppend( &p_sys->idx, i_time , i_offset );
841 #if 0
842             msg_Dbg( p_demux, "adding entry position %d %"PRIi64 " file offset %"PRIi64, keyframe, i_time, i_offset );
843 #endif
844         }
845
846         last_keyframe = keyframe;
847     }
848
849     p_sys->i_total_frames = (int64_t)frame;
850
851     p_sys->b_index = true;
852
853     p_sys->i_total_length = p_sys->i_total_frames * 1000000 / p_sys->hdr.d_fps;
854
855     msg_Dbg( p_demux, "index table loaded (%d elements)", i_seek_elements );
856
857     if( i_kfa_elements )
858         free ( p_kfa_table );
859
860     free ( p_seek_table );
861
862     /* Restore stream position */
863     if( stream_Seek( p_demux->s, i_original_pos ) )
864         return VLC_EGENERIC;
865
866     return VLC_SUCCESS;
867
868 }
869
870 /*****************************************************************************/
871 #define DEMUX_INDEX_SIZE_MAX (100000)
872 static void demux_IndexInit( demux_index_t *p_idx )
873 {
874     p_idx->i_idx = 0;
875     p_idx->i_idx_max = 0;
876     p_idx->idx = NULL;
877 }
878 static void demux_IndexClean( demux_index_t *p_idx )
879 {
880     free( p_idx->idx );
881     p_idx->idx = NULL;
882 }
883 static void demux_IndexAppend( demux_index_t *p_idx,
884                                int64_t i_time, int64_t i_offset )
885 {
886     /* Be sure to append new entry (we don't insert point) */
887     if( p_idx->i_idx > 0 && p_idx->idx[p_idx->i_idx-1].i_time >= i_time )
888         return;
889
890     /* */
891     if( p_idx->i_idx >= p_idx->i_idx_max )
892     {
893         if( p_idx->i_idx >= DEMUX_INDEX_SIZE_MAX )
894         {
895             /* Avoid too big index */
896             const int64_t i_length = p_idx->idx[p_idx->i_idx-1].i_time -
897                                                         p_idx->idx[0].i_time;
898             const int i_count = DEMUX_INDEX_SIZE_MAX/2;
899             int i, j;
900
901             /* We try to reduce the resolution of the index by a factor 2 */
902             for( i = 1, j = 1; i < p_idx->i_idx; i++ )
903             {
904                 if( p_idx->idx[i].i_time < j * i_length / i_count )
905                     continue;
906
907                 p_idx->idx[j++] = p_idx->idx[i];
908             }
909             p_idx->i_idx = j;
910
911             if( p_idx->i_idx > 3 * DEMUX_INDEX_SIZE_MAX / 4 )
912             {
913                 /* We haven't created enough space
914                  * (This method won't create a good index but work for sure) */
915                 for( i = 0; i < p_idx->i_idx/2; i++ )
916                     p_idx->idx[i] = p_idx->idx[2*i];
917                 p_idx->i_idx /= 2;
918             }
919         }
920         else
921         {
922             p_idx->i_idx_max += 1000;
923             p_idx->idx = xrealloc( p_idx->idx,
924                                 p_idx->i_idx_max*sizeof(demux_index_entry_t));
925         }
926     }
927
928     /* */
929     p_idx->idx[p_idx->i_idx].i_time = i_time;
930     p_idx->idx[p_idx->i_idx].i_offset = i_offset;
931
932     p_idx->i_idx++;
933 }
934 static int64_t demux_IndexConvertTime( demux_index_t *p_idx, int64_t i_time )
935 {
936     int i_min = 0;
937     int i_max = p_idx->i_idx-1;
938
939     /* Empty index */
940     if( p_idx->i_idx <= 0 )
941         return -1;
942
943     /* Special border case */
944     if( i_time <= p_idx->idx[0].i_time )
945         return p_idx->idx[0].i_offset;
946     if( i_time >= p_idx->idx[i_max].i_time )
947         return p_idx->idx[i_max].i_offset;
948
949     /* Dicho */
950     for( ;; )
951     {
952         int i_med;
953
954         if( i_max - i_min <= 1 )
955             break;
956
957         i_med = (i_min+i_max)/2;
958         if( p_idx->idx[i_med].i_time < i_time )
959             i_min = i_med;
960         else if( p_idx->idx[i_med].i_time > i_time )
961             i_max = i_med;
962         else
963             return p_idx->idx[i_med].i_offset;
964     }
965
966     /* return nearest in time */
967     if( i_time - p_idx->idx[i_min].i_time < p_idx->idx[i_max].i_time - i_time )
968         return p_idx->idx[i_min].i_offset;
969     else
970         return p_idx->idx[i_max].i_offset;
971 }
972
973
974 static int64_t demux_IndexFindOffset( demux_index_t *p_idx, int64_t i_offset )
975 {
976     int i_min = 0;
977     int i_max = p_idx->i_idx-1;
978
979     /* Empty index */
980     if( p_idx->i_idx <= 0 )
981         return -1;
982
983     /* Special border case */
984     if( i_offset <= p_idx->idx[0].i_offset )
985         return p_idx->idx[0].i_offset;
986     if( i_offset == p_idx->idx[i_max].i_offset )
987         return p_idx->idx[i_max].i_offset;
988     if( i_offset > p_idx->idx[i_max].i_offset )
989         return -1;
990
991     /* Dicho */
992     for( ;; )
993     {
994         int i_med;
995
996         if( i_max - i_min <= 1 )
997             break;
998
999         i_med = (i_min+i_max)/2;
1000         if( p_idx->idx[i_med].i_offset < i_offset )
1001             i_min = i_med;
1002         else if( p_idx->idx[i_med].i_offset > i_offset )
1003             i_max = i_med;
1004         else
1005             return p_idx->idx[i_med].i_offset;
1006     }
1007
1008     /* return nearest */
1009     if( i_offset - p_idx->idx[i_min].i_offset < p_idx->idx[i_max].i_offset - i_offset )
1010         return p_idx->idx[i_min].i_offset;
1011     else
1012         return p_idx->idx[i_max].i_offset;
1013 }
1014