97d8d44f8233b2736880c3e3fe162ddd4ec14219
[vlc.git] / 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  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
33 #include <vlc_demux.h>
34
35 /* TODO:
36  *  - complete support (add support for rtjpeg and raw)
37  *  - better seek support (to key frame)
38  *  - control GET_LENGTH (harder, unless we have an extended header+index)
39  *  - test
40  */
41
42 /*****************************************************************************
43  * Module descriptor
44  *****************************************************************************/
45 static int  Open  ( vlc_object_t * );
46 static void Close ( vlc_object_t * );
47
48 vlc_module_begin();
49     set_category( CAT_INPUT );
50     set_subcategory( SUBCAT_INPUT_DEMUX );
51     set_description( N_("Nuv demuxer") );
52     set_capability( "demux", 145 );
53     set_callbacks( Open, Close );
54     add_shortcut( "nuv" );
55 vlc_module_end();
56
57 /*****************************************************************************
58  * Local prototypes
59  *****************************************************************************/
60 static int Demux  ( demux_t * );
61 static int Control( demux_t *, int, va_list );
62
63 /* */
64 typedef struct
65 {
66     int64_t i_time;
67     int64_t i_offset;
68
69 } demux_index_entry_t;
70
71 typedef struct
72 {
73     int i_idx;
74     int i_idx_max;
75
76     demux_index_entry_t *idx;
77 } demux_index_t;
78
79
80 static void demux_IndexInit( demux_index_t * );
81 static void demux_IndexClean( demux_index_t * );
82 static void demux_IndexAppend( demux_index_t *,
83                                int64_t i_time, int64_t i_offset );
84 /* Convert a time into offset */
85 static int64_t demux_IndexConvertTime( demux_index_t *, int64_t i_time );
86 /* Find the nearest offset in the index */
87 static int64_t demux_IndexFindOffset( demux_index_t *, int64_t i_offset );
88
89
90 /* */
91 typedef struct
92 {
93     char id[12];       /* "NuppelVideo\0" or "MythTVVideo\0" */
94     char version[5];    /* "x.xx\0" */
95
96     int  i_width;
97     int  i_height;
98     int  i_width_desired;
99     int  i_height_desired;
100
101     char i_mode;            /* P progressive, I interlaced */
102
103     double  d_aspect;       /* 1.0 squared pixel */
104     double  d_fps;
105
106     int     i_video_blocks; /* 0 no video, -1 unknown */
107     int     i_audio_blocks;
108     int     i_text_blocks;
109
110     int     i_keyframe_distance;
111
112 } header_t;
113
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     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 /* FIXME Not sure of this one */
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_seekable_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 };
188
189 static int HeaderLoad( demux_t *, header_t *h );
190 static int FrameHeaderLoad( demux_t *, frame_header_t *h );
191 static int ExtendedHeaderLoad( demux_t *, extended_header_t *h );
192
193 /*****************************************************************************
194  * Open: initializes ES structures
195  *****************************************************************************/
196 static int Open( vlc_object_t * p_this )
197 {
198     demux_t     *p_demux = (demux_t*)p_this;
199     demux_sys_t *p_sys;
200     const uint8_t *p_peek;
201     frame_header_t fh;
202     bool  b_extended;
203
204     /* Check id */
205     if( stream_Peek( p_demux->s, &p_peek, 12 ) != 12 ||
206         ( strncmp( (char *)p_peek, "MythTVVideo", 11 ) &&
207           strncmp( (char *)p_peek, "NuppelVideo", 11 ) ) )
208         return VLC_EGENERIC;
209
210     p_sys = malloc( sizeof( demux_sys_t ) );
211     memset( p_sys, 0, sizeof( demux_sys_t ) );
212     p_sys->p_es_video = NULL;
213     p_sys->p_es_audio = NULL;
214     p_sys->p_extra_f = NULL;
215     p_sys->i_pcr = -1;
216     demux_IndexInit( &p_sys->idx );
217
218     if( HeaderLoad( p_demux, &p_sys->hdr ) )
219         goto error;
220
221     /* Load 'D' */
222     if( FrameHeaderLoad( p_demux, &fh ) || fh.i_type != 'D' )
223         goto error;
224     if( fh.i_length > 0 )
225     {
226         if( fh.i_compression == 'F' )
227         {
228             /* ffmpeg extra data */
229             p_sys->i_extra_f = fh.i_length;
230             p_sys->p_extra_f = malloc( fh.i_length );
231             if( stream_Read( p_demux->s,
232                              p_sys->p_extra_f, fh.i_length ) != fh.i_length )
233                 goto error;
234         }
235         else
236         {
237             /* TODO handle rtjpeg */
238             msg_Warn( p_demux, "unsupported 'D' frame (c=%c)", fh.i_compression );
239             if( stream_Read( p_demux->s, NULL, fh.i_length ) != fh.i_length )
240                 goto error;
241         }
242     }
243
244     /* Check and load extented */
245     if( stream_Peek( p_demux->s, &p_peek, 1 ) != 1 )
246         goto error;
247     if( p_peek[0] == 'X' )
248     {
249         b_extended = true;
250
251         if( FrameHeaderLoad( p_demux, &fh ) )
252             goto error;
253         if( fh.i_length != 512 )
254             goto error;
255
256         if( ExtendedHeaderLoad( p_demux, &p_sys->exh ) )
257             goto error;
258
259     }
260     else
261     {
262         b_extended = false;
263
264         /* XXX: for now only file with extended chunk are supported
265          * why: because else we need to have support for rtjpeg+stupid nuv shit */
266         msg_Err( p_demux, "incomplete NUV support (upload samples)" );
267         goto error;
268     }
269
270     /* Create audio/video (will work only with extended header and audio=mp3 */
271     if( p_sys->hdr.i_video_blocks != 0 )
272     {
273         es_format_t fmt;
274
275         es_format_Init( &fmt, VIDEO_ES, p_sys->exh.i_video_fcc );
276         fmt.video.i_width = p_sys->hdr.i_width;
277         fmt.video.i_height = p_sys->hdr.i_height;
278         fmt.i_extra = p_sys->i_extra_f;
279         fmt.p_extra = p_sys->p_extra_f;
280
281         p_sys->p_es_video = es_out_Add( p_demux->out, &fmt );
282     }
283     if( p_sys->hdr.i_audio_blocks != 0 )
284     {
285         es_format_t fmt;
286
287         es_format_Init( &fmt, AUDIO_ES, VLC_FOURCC('m','p','g','a') );
288         fmt.audio.i_rate = p_sys->exh.i_audio_sample_rate;
289         fmt.audio.i_bitspersample = p_sys->exh.i_audio_bits_per_sample;
290
291         p_sys->p_es_audio = es_out_Add( p_demux->out, &fmt );
292     }
293     if( p_sys->hdr.i_text_blocks != 0 )
294     {
295         msg_Warn( p_demux, "text not yet supported (upload samples)" );
296     }
297
298
299     /* Fill p_demux fields */
300     p_demux->pf_demux = Demux;
301     p_demux->pf_control = Control;
302     p_demux->p_sys = p_sys;
303
304     return VLC_SUCCESS;
305
306 error:
307     msg_Warn( p_demux, "cannot load Nuv file" );
308     free( p_sys );
309     return VLC_EGENERIC;
310 }
311
312 /*****************************************************************************
313  * Close: frees unused data
314  *****************************************************************************/
315 static void Close( vlc_object_t * p_this )
316 {
317     demux_t        *p_demux = (demux_t*)p_this;
318     demux_sys_t    *p_sys = p_demux->p_sys;
319
320     free( p_sys->p_extra_f );
321     demux_IndexClean( &p_sys->idx );
322     free( p_sys );
323 }
324
325 /*****************************************************************************
326  * Demux: reads and demuxes data packets
327  *****************************************************************************
328  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
329  *****************************************************************************/
330 static int Demux( demux_t *p_demux )
331 {
332     demux_sys_t *p_sys = p_demux->p_sys;
333     frame_header_t fh;
334     block_t *p_data;
335
336     for( ;; )
337     {
338         if( !vlc_object_alive (p_demux) )
339             return -1;
340
341         if( FrameHeaderLoad( p_demux, &fh ) )
342             return 0;
343
344         if( fh.i_type == 'A' || fh.i_type == 'V' )
345             break;
346
347         /* TODO add support for some block type */
348
349         if( fh.i_type != 'R' )
350         {
351             stream_Read( p_demux->s, NULL, fh.i_length );
352         }
353     }
354
355     /* */
356     p_data = stream_Block( p_demux->s, fh.i_length );
357     p_data->i_dts = (int64_t)fh.i_timecode * 1000;
358     p_data->i_pts = (fh.i_type == 'V') ? 0 : p_data->i_dts;
359
360     /* */
361     demux_IndexAppend( &p_sys->idx, p_data->i_dts, stream_Tell(p_demux->s) );
362
363     /* */
364     if( p_data->i_dts > p_sys->i_pcr )
365     {
366         p_sys->i_pcr = p_data->i_dts;
367         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr );
368     }
369
370     if( fh.i_type == 'A' && p_sys->p_es_audio )
371     {
372         if( fh.i_compression == '3' )
373             es_out_Send( p_demux->out, p_sys->p_es_audio, p_data );
374         else
375         {
376             msg_Dbg( p_demux, "unsupported compression %c for audio (upload samples)", fh.i_compression );
377             block_Release( p_data );
378         }
379     }
380     else if( fh.i_type == 'V' && p_sys->p_es_video )
381     {
382         if( fh.i_compression >= '4' )
383             es_out_Send( p_demux->out, p_sys->p_es_video, p_data );
384         else
385         {
386             msg_Dbg( p_demux, "unsupported compression %c for video (upload samples)", fh.i_compression );
387             block_Release( p_data );
388         }
389     }
390     else
391     {
392         block_Release( p_data );
393     }
394
395     return 1;
396 }
397
398 /*****************************************************************************
399  * Control:
400  *****************************************************************************/
401 static int Control( demux_t *p_demux, int i_query, va_list args )
402 {
403     demux_sys_t *p_sys  = p_demux->p_sys;
404
405     double   f, *pf;
406     int64_t i64, *pi64;
407
408     switch( i_query )
409     {
410
411         case DEMUX_GET_POSITION:
412             pf = (double*)va_arg( args, double * );
413             i64 = stream_Size( p_demux->s );
414             if( i64 > 0 )
415                 *pf = (double)stream_Tell( p_demux->s ) / (double)i64;
416             else
417                 *pf = 0.0;
418             return VLC_SUCCESS;
419
420         case DEMUX_SET_POSITION:
421         {
422             int64_t i_pos;
423
424             f = (double)va_arg( args, double );
425             i_pos = stream_Size( p_demux->s ) * f;
426
427             i64 = demux_IndexFindOffset( &p_sys->idx, i_pos );
428
429             p_sys->i_pcr = -1;
430
431             if( i64 >= 0 )
432                 return stream_Seek( p_demux->s, i64 );
433
434             if( p_sys->idx.i_idx > 0 )
435             {
436                 if( stream_Seek( p_demux->s, p_sys->idx.idx[p_sys->idx.i_idx-1].i_offset ) )
437                     return VLC_EGENERIC;
438             }
439             else
440             {
441                 if( stream_Seek( p_demux->s, 0 ) )
442                     return VLC_EGENERIC;
443             }
444
445             while( vlc_object_alive (p_demux) )
446             {
447                 frame_header_t fh;
448                 int64_t i_tell;
449
450                 if( ( i_tell = stream_Tell( p_demux->s ) ) >= i_pos )
451                     break;
452
453                 if( FrameHeaderLoad( p_demux, &fh ) )
454                     return VLC_EGENERIC;
455
456                 if( fh.i_type == 'A' || fh.i_type == 'V' )
457                     demux_IndexAppend( &p_sys->idx,(int64_t)fh.i_timecode*1000, i_tell );
458
459                 if( fh.i_type != 'R' )
460                     stream_Read( p_demux->s, NULL, fh.i_length );
461             }
462             return VLC_SUCCESS;
463         }
464
465
466         case DEMUX_GET_TIME:
467             pi64 = (int64_t*)va_arg( args, int64_t * );
468             *pi64 = p_sys->i_pcr >= 0 ? p_sys->i_pcr : 0;
469             return VLC_SUCCESS;
470
471         case DEMUX_SET_TIME:
472         {
473             int64_t i_pos;
474             i64 = (int64_t)va_arg( args, int64_t );
475
476             i_pos = demux_IndexConvertTime( &p_sys->idx, i64 );
477             if( i_pos < 0 )
478                 return VLC_EGENERIC;
479
480             if( stream_Seek( p_demux->s, i_pos ) )
481                 return VLC_EGENERIC;
482
483             p_sys->i_pcr = -1;
484
485             while( vlc_object_alive (p_demux) )
486             {
487                 frame_header_t fh;
488
489                 if( FrameHeaderLoad( p_demux, &fh ) )
490                     return VLC_EGENERIC;
491
492                 if( fh.i_type == 'A' || fh.i_type == 'V' )
493                 {
494                     int64_t i_time = (int64_t)fh.i_timecode*1000;
495                     int64_t i_tell = stream_Tell(p_demux->s)-12;
496
497                     demux_IndexAppend( &p_sys->idx, i_time, i_tell );
498
499                     if( i_time >= i64 )
500                         return stream_Seek( p_demux->s, i_tell );
501                 }
502                 if( fh.i_type != 'R' )
503                     stream_Read( p_demux->s, NULL, fh.i_length );
504             }
505             return VLC_SUCCESS;
506         }
507
508         case DEMUX_GET_LENGTH:
509             pi64 = (int64_t*)va_arg( args, int64_t * );
510             return VLC_EGENERIC;
511
512         case DEMUX_GET_FPS:
513             pf = (double*)va_arg( args, double * );
514             *pf = p_sys->hdr.d_fps;
515             return VLC_SUCCESS;
516
517         case DEMUX_GET_META:
518         default:
519             return VLC_EGENERIC;
520
521     }
522 }
523
524 /*****************************************************************************
525  *
526  *****************************************************************************/
527 static inline void GetDoubleLE( double *pd, void *src )
528 {
529     /* FIXME works only if sizeof(double) == 8 */
530 #ifdef WORDS_BIGENDIAN
531     uint8_t *p = (uint8_t*)pd, *q = (uint8_t*)src;
532     int i;
533     for( i = 0; i < 8; i++ )
534         p[i] = q[7-i];
535 #else
536     memcpy( pd, src, 8 );
537 #endif
538 }
539
540 /* HeaderLoad:
541  */
542 static int HeaderLoad( demux_t *p_demux, header_t *h )
543 {
544     uint8_t buffer[72];
545
546     if( stream_Read( p_demux->s, buffer, 72 ) != 72 )
547         return VLC_EGENERIC;
548
549     /* XXX: they are alignment to take care of (another broken format) */
550     memcpy( h->id,      &buffer[ 0], 12 );
551     memcpy( h->version, &buffer[12], 5 );
552     h->i_width = GetDWLE( &buffer[20] );
553     h->i_height = GetDWLE( &buffer[24] );
554     h->i_width_desired = GetDWLE( &buffer[28] );
555     h->i_height_desired = GetDWLE( &buffer[32] );
556     h->i_mode = buffer[36];
557     GetDoubleLE( &h->d_aspect, &buffer[40] );
558     GetDoubleLE( &h->d_fps, &buffer[48] );
559     h->i_video_blocks = GetDWLE( &buffer[56] );
560     h->i_audio_blocks = GetDWLE( &buffer[60] );
561     h->i_text_blocks = GetDWLE( &buffer[64] );
562     h->i_keyframe_distance = GetDWLE( &buffer[68] );
563 #if 0
564     msg_Dbg( p_demux, "nuv: h=%s v=%s %dx%d a=%f fps=%f v=%d a=%d t=%d kfd=%d",
565              h->id, h->version, h->i_width, h->i_height, h->d_aspect,
566              h->d_fps, h->i_video_blocks, h->i_audio_blocks, h->i_text_blocks,
567              h->i_keyframe_distance );
568 #endif
569     return VLC_SUCCESS;
570 }
571
572 /* FrameHeaderLoad:
573  */
574 static int FrameHeaderLoad( demux_t *p_demux, frame_header_t *h )
575 {
576     uint8_t buffer[12];
577
578     if( stream_Read( p_demux->s, buffer, 12 ) != 12 )
579         return VLC_EGENERIC;
580
581     h->i_type = buffer[0];
582     h->i_compression = buffer[1];
583     h->i_keyframe = buffer[2];
584     h->i_filters = buffer[3];
585
586     h->i_timecode = GetDWLE( &buffer[4] );
587     h->i_length = GetDWLE( &buffer[8] );
588 #if 0
589     msg_Dbg( p_demux, "frame hdr: t=%c c=%c k=%d f=0x%x timecode=%d l=%d",
590              h->i_type,
591              h->i_compression ? h->i_compression : ' ',
592              h->i_keyframe ? h->i_keyframe : ' ',
593              h->i_filters,
594              h->i_timecode, h->i_length );
595 #endif
596     return VLC_SUCCESS;
597 }
598
599 static int ExtendedHeaderLoad( demux_t *p_demux, extended_header_t *h )
600 {
601     uint8_t buffer[512];
602
603     if( stream_Read( p_demux->s, buffer, 512 ) != 512 )
604         return VLC_EGENERIC;
605
606     h->i_version = GetDWLE( &buffer[0] );
607     h->i_video_fcc = VLC_FOURCC( buffer[4], buffer[5], buffer[6], buffer[7] );
608     h->i_audio_fcc = VLC_FOURCC( buffer[8], buffer[9], buffer[10], buffer[11] );
609     h->i_audio_sample_rate = GetDWLE( &buffer[12] );
610     h->i_audio_bits_per_sample = GetDWLE( &buffer[16] );
611     h->i_audio_channels = GetDWLE( &buffer[20] );
612     h->i_audio_compression_ratio = GetDWLE( &buffer[24] );
613     h->i_audio_quality = GetDWLE( &buffer[28] );
614     h->i_rtjpeg_quality = GetDWLE( &buffer[32] );
615     h->i_rtjpeg_luma_filter = GetDWLE( &buffer[36] );
616     h->i_rtjpeg_chroma_filter = GetDWLE( &buffer[40] );
617     h->i_lavc_bitrate = GetDWLE( &buffer[44] );
618     h->i_lavc_qmin = GetDWLE( &buffer[48] );
619     h->i_lavc_qmin = GetDWLE( &buffer[52] );
620     h->i_lavc_maxqdiff = GetDWLE( &buffer[56] );
621     h->i_seekable_offset = GetQWLE( &buffer[60] );
622     h->i_keyframe_adjust_offset= GetQWLE( &buffer[68] );
623 #if 0
624     msg_Dbg( p_demux, "ex hdr: v=%d vffc=%4.4s afcc=%4.4s %dHz %dbits ach=%d acr=%d aq=%d"
625                       "rtjpeg q=%d lf=%d lc=%d lavc br=%d qmin=%d qmax=%d maxqdiff=%d seekableoff=%lld keyfao=%lld",
626              h->i_version,
627              (char*)&h->i_video_fcc,
628              (char*)&h->i_audio_fcc, h->i_audio_sample_rate, h->i_audio_bits_per_sample, h->i_audio_channels,
629              h->i_audio_compression_ratio, h->i_audio_quality,
630              h->i_rtjpeg_quality, h->i_rtjpeg_luma_filter, h->i_rtjpeg_chroma_filter,
631              h->i_lavc_bitrate, h->i_lavc_qmin, h->i_lavc_qmax, h->i_lavc_maxqdiff,
632              h->i_seekable_offset, h->i_keyframe_adjust_offset );
633 #endif
634     return VLC_SUCCESS;
635 }
636
637 /*****************************************************************************/
638 #define DEMUX_INDEX_SIZE_MAX (100000)
639 static void demux_IndexInit( demux_index_t *p_idx )
640 {
641     p_idx->i_idx = 0;
642     p_idx->i_idx_max = 0;
643     p_idx->idx = NULL;
644 }
645 static void demux_IndexClean( demux_index_t *p_idx )
646 {
647     free( p_idx->idx );
648     p_idx->idx = NULL;
649 }
650 static void demux_IndexAppend( demux_index_t *p_idx,
651                                int64_t i_time, int64_t i_offset )
652 {
653     /* Be sure to append new entry (we don't insert point) */
654     if( p_idx->i_idx > 0 && p_idx->idx[p_idx->i_idx-1].i_time >= i_time )
655         return;
656
657     /* */
658     if( p_idx->i_idx >= p_idx->i_idx_max )
659     {
660         if( p_idx->i_idx >= DEMUX_INDEX_SIZE_MAX )
661         {
662             /* Avoid too big index */
663             const int64_t i_length = p_idx->idx[p_idx->i_idx-1].i_time -
664                                                         p_idx->idx[0].i_time;
665             const int i_count = DEMUX_INDEX_SIZE_MAX/2;
666             int i, j;
667
668             /* We try to reduce the resolution of the index by a factor 2 */
669             for( i = 1, j = 1; i < p_idx->i_idx; i++ )
670             {
671                 if( p_idx->idx[i].i_time < j * i_length / i_count )
672                     continue;
673
674                 p_idx->idx[j++] = p_idx->idx[i];
675             }
676             p_idx->i_idx = j;
677
678             if( p_idx->i_idx > 3 * DEMUX_INDEX_SIZE_MAX / 4 )
679             {
680                 /* We haven't created enough space
681                  * (This method won't create a good index but work for sure) */
682                 for( i = 0; i < p_idx->i_idx/2; i++ )
683                     p_idx->idx[i] = p_idx->idx[2*i];
684                 p_idx->i_idx /= 2;
685             }
686         }
687         else
688         {
689             p_idx->i_idx_max += 1000;
690             p_idx->idx = realloc( p_idx->idx,
691                                   p_idx->i_idx_max*sizeof(demux_index_entry_t));
692         }
693     }
694
695     /* */
696     p_idx->idx[p_idx->i_idx].i_time = i_time;
697     p_idx->idx[p_idx->i_idx].i_offset = i_offset;
698
699     p_idx->i_idx++;
700 }
701 static int64_t demux_IndexConvertTime( demux_index_t *p_idx, int64_t i_time )
702 {
703     int i_min = 0;
704     int i_max = p_idx->i_idx-1;
705
706     /* Empty index */
707     if( p_idx->i_idx <= 0 )
708         return -1;
709
710     /* Special border case */
711     if( i_time <= p_idx->idx[0].i_time )
712         return p_idx->idx[0].i_offset;
713     if( i_time >= p_idx->idx[i_max].i_time )
714         return p_idx->idx[i_max].i_offset;
715
716     /* Dicho */
717     for( ;; )
718     {
719         int i_med;
720
721         if( i_max - i_min <= 1 )
722             break;
723
724         i_med = (i_min+i_max)/2;
725         if( p_idx->idx[i_med].i_time < i_time )
726             i_min = i_med;
727         else if( p_idx->idx[i_med].i_time > i_time )
728             i_max = i_med;
729         else
730             return p_idx->idx[i_med].i_offset;
731     }
732
733     /* return nearest in time */
734     if( i_time - p_idx->idx[i_min].i_time < p_idx->idx[i_max].i_time - i_time )
735         return p_idx->idx[i_min].i_offset;
736     else
737         return p_idx->idx[i_max].i_offset;
738 }
739
740
741 static int64_t demux_IndexFindOffset( demux_index_t *p_idx, int64_t i_offset )
742 {
743     int i_min = 0;
744     int i_max = p_idx->i_idx-1;
745
746     /* Empty index */
747     if( p_idx->i_idx <= 0 )
748         return -1;
749
750     /* Special border case */
751     if( i_offset <= p_idx->idx[0].i_offset )
752         return p_idx->idx[0].i_offset;
753     if( i_offset == p_idx->idx[i_max].i_offset )
754         return p_idx->idx[i_max].i_offset;
755     if( i_offset > p_idx->idx[i_max].i_offset )
756         return -1;
757
758     /* Dicho */
759     for( ;; )
760     {
761         int i_med;
762
763         if( i_max - i_min <= 1 )
764             break;
765
766         i_med = (i_min+i_max)/2;
767         if( p_idx->idx[i_med].i_offset < i_offset )
768             i_min = i_med;
769         else if( p_idx->idx[i_med].i_offset > i_offset )
770             i_max = i_med;
771         else
772             return p_idx->idx[i_med].i_offset;
773     }
774
775     /* return nearest */
776     if( i_offset - p_idx->idx[i_min].i_offset < p_idx->idx[i_max].i_offset - i_offset )
777         return p_idx->idx[i_min].i_offset;
778     else
779         return p_idx->idx[i_max].i_offset;
780 }