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