1121ca471a4580524332b6ff6e6dfecb5eeabaf0
[vlc.git] / modules / stream_out / transrate / transrate.c
1 /*****************************************************************************
2  * transrate.c
3  *****************************************************************************
4  * Copyright (C) 2003 VideoLAN
5  * Copyright (C) 2003 Freebox S.A.
6  * Copyright (C) 2003 Antoine Missout
7  * Copyright (C) 2000-2003 Michel Lespinasse <walken@zoy.org>
8  * Copyright (C) 1999-2000 Aaron Holtzman <aholtzma@ess.engr.uvic.ca>
9  * $Id: transrate.c,v 1.3 2003/11/21 15:32:08 fenrir Exp $
10  *
11  * Authors: Christophe Massiot <massiot@via.ecp.fr>
12  *          Laurent Aimar <fenrir@via.ecp.fr>
13  *          Antoine Missout
14  *          Michel Lespinasse <walken@zoy.org>
15  *          Aaron Holtzman <aholtzma@ess.engr.uvic.ca>
16  *
17  * This program is free software; you can redistribute it and/or modify
18  * it under the terms of the GNU General Public License as published by
19  * the Free Software Foundation; either version 2 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU General Public License for more details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with this program; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
30  *****************************************************************************/
31
32 /*****************************************************************************
33  * Preamble
34  *****************************************************************************/
35 #include <stdio.h>
36 #include <stdlib.h>
37 #define NDEBUG 1
38 #include <assert.h>
39 #include <math.h>
40
41 #include <vlc/vlc.h>
42 #include <vlc/sout.h>
43 #include <vlc/input.h>
44
45 /*****************************************************************************
46  * Exported prototypes
47  *****************************************************************************/
48 static int      Open    ( vlc_object_t * );
49 static void     Close   ( vlc_object_t * );
50
51 static sout_stream_id_t *Add ( sout_stream_t *, es_format_t * );
52 static int               Del ( sout_stream_t *, sout_stream_id_t * );
53 static int               Send( sout_stream_t *, sout_stream_id_t *, sout_buffer_t * );
54
55 static int  transrate_video_process( sout_stream_t *, sout_stream_id_t *, sout_buffer_t *, sout_buffer_t ** );
56
57 /*****************************************************************************
58  * Module descriptor
59  *****************************************************************************/
60 vlc_module_begin();
61     set_description( _("Transrate stream") );
62     set_capability( "sout stream", 50 );
63     add_shortcut( "transrate" );
64     set_callbacks( Open, Close );
65 vlc_module_end();
66
67 struct sout_stream_sys_t
68 {
69     sout_stream_t   *p_out;
70
71     int             i_vbitrate;
72
73     mtime_t         i_first_frame;
74     mtime_t         i_dts, i_pts;
75 };
76
77 /*****************************************************************************
78  * Open:
79  *****************************************************************************/
80 static int Open( vlc_object_t *p_this )
81 {
82     sout_stream_t     *p_stream = (sout_stream_t*)p_this;
83     sout_stream_sys_t *p_sys;
84     char *val;
85
86     p_sys = malloc( sizeof( sout_stream_sys_t ) );
87     p_sys->p_out = sout_stream_new( p_stream->p_sout, p_stream->psz_next );
88
89     p_sys->i_vbitrate   = 0;
90
91     if( ( val = sout_cfg_find_value( p_stream->p_cfg, "vb" ) ) )
92     {
93         p_sys->i_vbitrate = atoi( val );
94         if( p_sys->i_vbitrate < 16000 )
95         {
96             p_sys->i_vbitrate *= 1000;
97         }
98     }
99     else
100     {
101         p_sys->i_vbitrate = 3000000;
102     }
103     p_sys->i_first_frame = 0;
104
105     msg_Dbg( p_stream, "codec video %dkb/s",
106              p_sys->i_vbitrate / 1024 );
107
108     if( !p_sys->p_out )
109     {
110         msg_Err( p_stream, "cannot create chain" );
111         free( p_sys );
112         return VLC_EGENERIC;
113     }
114     p_stream->pf_add    = Add;
115     p_stream->pf_del    = Del;
116     p_stream->pf_send   = Send;
117
118     p_stream->p_sys     = p_sys;
119
120     p_stream->p_sout->i_padding += 200;
121
122     return VLC_SUCCESS;
123 }
124
125 /*****************************************************************************
126  * Close:
127  *****************************************************************************/
128 static void Close( vlc_object_t * p_this )
129 {
130     sout_stream_t       *p_stream = (sout_stream_t *)p_this;
131     sout_stream_sys_t   *p_sys = p_stream->p_sys;
132
133     sout_stream_delete( p_sys->p_out );
134     free( p_sys );
135 }
136
137
138
139 /*****************************************************************************
140  * sout_stream_id_t:
141  *****************************************************************************/
142
143 typedef struct
144 {
145     uint8_t run;
146     short level;
147 } RunLevel;
148
149 typedef struct
150 {
151     uint8_t *p_c;
152     uint8_t *p_r;
153     uint8_t *p_w;
154     uint8_t *p_ow;
155     uint8_t *p_rw;
156
157     int i_bit_in;
158     int i_bit_out;
159     uint32_t i_bit_in_cache;
160     uint32_t i_bit_out_cache;
161
162     uint32_t i_byte_in;
163     uint32_t i_byte_out;
164 } bs_transrate_t;
165
166 typedef struct
167 {
168     bs_transrate_t bs;
169
170     /* MPEG2 state */
171
172     // seq header
173     unsigned int horizontal_size_value;
174     unsigned int vertical_size_value;
175
176     // pic header
177     unsigned int picture_coding_type;
178
179     // pic code ext
180     unsigned int f_code[2][2];
181     /* unsigned int intra_dc_precision; */
182     unsigned int picture_structure;
183     unsigned int frame_pred_frame_dct;
184     unsigned int concealment_motion_vectors;
185     unsigned int q_scale_type;
186     unsigned int intra_vlc_format;
187     /* unsigned int alternate_scan; */
188
189     // slice or mb
190     // quantizer_scale_code
191     unsigned int quantizer_scale;
192     unsigned int new_quantizer_scale;
193     unsigned int last_coded_scale;
194     int   h_offset, v_offset;
195
196     // mb
197     double quant_corr, fact_x;
198 } transrate_t;
199
200
201 struct sout_stream_id_t
202 {
203     void            *id;
204     vlc_bool_t      b_transrate;
205
206     sout_buffer_t   *p_current_buffer;
207     sout_buffer_t   *p_next_gop;
208     mtime_t         i_next_gop_duration;
209     size_t          i_next_gop_size;
210
211     transrate_t     tr;
212 };
213
214
215 static sout_stream_id_t * Add( sout_stream_t *p_stream, es_format_t *p_fmt )
216 {
217     sout_stream_sys_t   *p_sys = p_stream->p_sys;
218     sout_stream_id_t    *id;
219
220     id = malloc( sizeof( sout_stream_id_t ) );
221     id->id = NULL;
222
223     if( p_fmt->i_cat == VIDEO_ES
224             && p_fmt->i_codec == VLC_FOURCC('m', 'p', 'g', 'v') )
225     {
226         msg_Dbg( p_stream,
227                  "creating video transrating for fcc=`%4.4s'",
228                  (char*)&p_fmt->i_codec );
229
230         id->p_current_buffer = NULL;
231         id->p_next_gop = NULL;
232         id->i_next_gop_duration = 0;
233         id->i_next_gop_size = 0;
234         memset( &id->tr, 0, sizeof( transrate_t ) );
235         id->tr.bs.i_byte_in = id->tr.bs.i_byte_out = 0;
236         id->tr.quant_corr = 0.0;
237         id->tr.fact_x = 1.0;
238
239         /* open output stream */
240         id->id = p_sys->p_out->pf_add( p_sys->p_out, p_fmt );
241         id->b_transrate = VLC_TRUE;
242     }
243     else
244     {
245         msg_Dbg( p_stream, "not transrating a stream (fcc=`%4.4s')", (char*)&p_fmt->i_codec );
246         id->id = p_sys->p_out->pf_add( p_sys->p_out, p_fmt );
247         id->b_transrate = VLC_FALSE;
248
249         if( id->id == NULL )
250         {
251             free( id );
252             return NULL;
253         }
254     }
255
256     return id;
257 }
258
259 static int     Del      ( sout_stream_t *p_stream, sout_stream_id_t *id )
260 {
261     sout_stream_sys_t   *p_sys = p_stream->p_sys;
262
263     if( id->id )
264     {
265         p_sys->p_out->pf_del( p_sys->p_out, id->id );
266     }
267     free( id );
268
269     return VLC_SUCCESS;
270 }
271
272 static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
273                  sout_buffer_t *p_buffer )
274 {
275     sout_stream_sys_t   *p_sys = p_stream->p_sys;
276
277     if( id->b_transrate )
278     {
279         sout_buffer_t *p_buffer_out;
280         transrate_video_process( p_stream, id, p_buffer, &p_buffer_out );
281
282         if( p_buffer_out )
283         {
284             return p_sys->p_out->pf_send( p_sys->p_out, id->id, p_buffer_out );
285         }
286         return VLC_SUCCESS;
287     }
288     else if( id->id != NULL )
289     {
290         return p_sys->p_out->pf_send( p_sys->p_out, id->id, p_buffer );
291     }
292     else
293     {
294         sout_BufferDelete( p_stream->p_sout, p_buffer );
295         return VLC_EGENERIC;
296     }
297 }
298
299 /****************************************************************************
300  * transrater, code from M2VRequantizer http://www.metakine.com/
301  ****************************************************************************/
302
303 // toggles:
304 // #define NDEBUG // turns off asserts
305 /* This is awful magic --Meuuh */
306 //#define REACT_DELAY (1024.0*128.0)
307 #define REACT_DELAY (1024.0*4.0)
308
309 // notes:
310 //
311 // - intra block:
312 //      - the quantiser is increment by one step
313 //
314 // - non intra block:
315 //      - in P_FRAME we keep the original quantiser but drop the last coefficient
316 //        if there is more than one
317 //      - in B_FRAME we multiply the quantiser by a factor
318 //
319 // - I_FRAME is recoded when we're 5.0 * REACT_DELAY late
320 // - P_FRAME is recoded when we're 2.5 * REACT_DELAY late
321 // - B_FRAME are always recoded
322
323 // if we're getting *very* late (60 * REACT_DELAY)
324 //
325 // - intra blocks quantiser is incremented two step
326 // - drop a few coefficients but always keep the first one
327
328 // useful constants
329 enum
330 {
331     I_TYPE = 1,
332     P_TYPE = 2,
333     B_TYPE = 3
334 };
335
336
337 // gcc
338 #ifdef HAVE_BUILTIN_EXPECT
339 #define likely(x) __builtin_expect ((x) != 0, 1)
340 #define unlikely(x) __builtin_expect ((x) != 0, 0)
341 #else
342 #define likely(x) (x)
343 #define unlikely(x) (x)
344 #endif
345
346 #define BITS_IN_BUF (8)
347
348 #define LOG(msg) fprintf (stderr, msg)
349 #define LOGF(format, args...) fprintf (stderr, format, args)
350
351 static inline void bs_write( bs_transrate_t *s, unsigned int val, int n)
352 {
353     assert(n < 32);
354     assert(!(val & (0xffffffffU << n)));
355
356     while (unlikely(n >= s->i_bit_out))
357     {
358         s->p_w[0] = (s->i_bit_out_cache << s->i_bit_out ) | (val >> (n - s->i_bit_out));
359         s->p_w++;
360         n -= s->i_bit_out;
361         s->i_bit_out_cache = 0;
362         val &= ~(0xffffffffU << n);
363         s->i_bit_out = BITS_IN_BUF;
364     }
365
366     if (likely(n))
367     {
368         s->i_bit_out_cache = (s->i_bit_out_cache << n) | val;
369         s->i_bit_out -= n;
370     }
371
372     assert(s->i_bit_out > 0);
373     assert(s->i_bit_out <= BITS_IN_BUF);
374 }
375
376 static inline void bs_refill( bs_transrate_t *s )
377 {
378     assert((s->p_r - s->p_c) >= 1);
379     s->i_bit_in_cache |= s->p_c[0] << (24 - s->i_bit_in);
380     s->i_bit_in += 8;
381     s->p_c++;
382 }
383
384 static inline void bs_flush( bs_transrate_t *s, unsigned int n )
385 {
386     assert(s->i_bit_in >= n);
387
388     s->i_bit_in_cache <<= n;
389     s->i_bit_in -= n;
390
391     assert( (!n) || ((n>0) && !(s->i_bit_in_cache & 0x1)) );
392
393     while (unlikely(s->i_bit_in < 24)) bs_refill( s );
394 }
395
396 static inline unsigned int bs_read( bs_transrate_t *s, unsigned int n)
397 {
398     unsigned int Val = ((unsigned int)s->i_bit_in_cache) >> (32 - n);
399     bs_flush( s, n );
400     return Val;
401 }
402
403 static inline unsigned int bs_copy( bs_transrate_t *s, unsigned int n)
404 {
405     unsigned int Val = bs_read( s, n);
406     bs_write(s, Val, n);
407     return Val;
408 }
409
410 static inline void bs_flush_read( bs_transrate_t *s )
411 {
412     int i = s->i_bit_in & 0x7;
413     if( i )
414     {
415         assert(((unsigned int)bs->i_bit_in_cache) >> (32 - i) == 0);
416         s->i_bit_in_cache <<= i;
417         s->i_bit_in -= i;
418     }
419     s->p_c += -1 * (s->i_bit_in >> 3);
420     s->i_bit_in = 0;
421 }
422 static inline void bs_flush_write( bs_transrate_t *s )
423 {
424     if( s->i_bit_out != 8 ) bs_write(s, 0, s->i_bit_out);
425 }
426
427 /////---- begin ext mpeg code
428
429 const uint8_t non_linear_mquant_table[32] =
430 {
431     0, 1, 2, 3, 4, 5, 6, 7,
432     8,10,12,14,16,18,20,22,
433     24,28,32,36,40,44,48,52,
434     56,64,72,80,88,96,104,112
435 };
436 const uint8_t map_non_linear_mquant[113] =
437 {
438     0,1,2,3,4,5,6,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,
439     16,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,22,22,
440     22,22,23,23,23,23,24,24,24,24,24,24,24,25,25,25,25,25,25,25,26,26,
441     26,26,26,26,26,26,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,29,
442     29,29,29,29,29,29,29,29,29,30,30,30,30,30,30,30,31,31,31,31,31
443 };
444
445 static int scale_quant( unsigned int q_scale_type, double quant )
446 {
447     int iquant;
448     if (q_scale_type)
449     {
450         iquant = (int) floor(quant+0.5);
451
452         /* clip mquant to legal (linear) range */
453         if (iquant<1) iquant = 1;
454         if (iquant>112) iquant = 112;
455
456         iquant = non_linear_mquant_table[map_non_linear_mquant[iquant]];
457     }
458     else
459     {
460         /* clip mquant to legal (linear) range */
461         iquant = (int)floor(quant+0.5);
462         if (iquant<2) iquant = 2;
463         if (iquant>62) iquant = 62;
464         iquant = (iquant/2)*2; // Must be *even*
465     }
466     return iquant;
467 }
468
469 static int increment_quant( transrate_t *tr, int quant )
470 {
471     if( tr->q_scale_type)
472     {
473         assert(quant >= 1 && quant <= 112);
474         quant = map_non_linear_mquant[quant] + 1;
475         if( tr->quant_corr < -60.0f) quant++;
476         if( quant > 31) quant = 31;
477         quant = non_linear_mquant_table[quant];
478     }
479     else
480     {
481         assert(!(quant & 1));
482         quant += 2;
483         if( tr->quant_corr < -60.0f) quant += 2;
484         if (quant > 62) quant = 62;
485     }
486     return quant;
487 }
488
489 static inline int intmax( register int x, register int y )
490 {
491     return x < y ? y : x;
492 }
493 static inline int intmin( register int x, register int y )
494 {
495     return x < y ? x : y;
496 }
497
498 static int getNewQuant( transrate_t *tr, int curQuant)
499 {
500     bs_transrate_t *bs = &tr->bs;
501
502     double calc_quant, quant_to_use;
503     int mquant = 0;
504
505     tr->quant_corr = (((bs->i_byte_in - (bs->p_r - 4 - bs->p_c)) / tr->fact_x) - (bs->i_byte_out + (bs->p_w - bs->p_ow))) / REACT_DELAY;
506     calc_quant = curQuant * tr->fact_x;
507     quant_to_use = calc_quant - tr->quant_corr;
508
509     switch (tr->picture_coding_type )
510     {
511         case I_TYPE:
512         case P_TYPE:
513             mquant = increment_quant( tr, curQuant);
514             break;
515
516         case B_TYPE:
517             mquant = intmax(scale_quant( tr->q_scale_type, quant_to_use), increment_quant( tr, curQuant));
518             break;
519
520         default:
521             assert(0);
522             break;
523     }
524
525     /*
526         LOGF("type: %s orig_quant: %3i calc_quant: %7.1f quant_corr: %7.1f using_quant: %3i\n",
527         (picture_coding_type == I_TYPE ? "I_TYPE" : (picture_coding_type == P_TYPE ? "P_TYPE" : "B_TYPE")),
528         (int)curQuant, (float)calc_quant, (float)quant_corr, (int)mquant);
529     */
530
531     assert(mquant >= curQuant);
532
533     return mquant;
534 }
535
536 static inline int isNotEmpty(RunLevel *blk)
537 {
538     return (blk->level);
539 }
540
541 #include "putvlc.h"
542
543 static void putAC( bs_transrate_t *bs, int run, int signed_level, int vlcformat)
544 {
545     int level, len;
546     const VLCtable *ptab = NULL;
547
548     level = (signed_level<0) ? -signed_level : signed_level; /* abs(signed_level) */
549
550     assert(!(run<0 || run>63 || level==0 || level>2047));
551
552     len = 0;
553
554     if (run<2 && level<41)
555     {
556         if (vlcformat)  ptab = &dct_code_tab1a[run][level-1];
557         else ptab = &dct_code_tab1[run][level-1];
558         len = ptab->len;
559     }
560     else if (run<32 && level<6)
561     {
562         if (vlcformat) ptab = &dct_code_tab2a[run-2][level-1];
563         else ptab = &dct_code_tab2[run-2][level-1];
564         len = ptab->len;
565     }
566
567     if (len) /* a VLC code exists */
568     {
569         bs_write( bs, ptab->code, len);
570         bs_write( bs, signed_level<0, 1); /* sign */
571     }
572     else
573     {
574         bs_write( bs, 1l, 6); /* Escape */
575         bs_write( bs, run, 6); /* 6 bit code for run */
576         bs_write( bs, ((unsigned int)signed_level) & 0xFFF, 12);
577     }
578 }
579
580
581 static inline void putACfirst( bs_transrate_t *bs, int run, int val)
582 {
583     if (run==0 && (val==1 || val==-1)) bs_write( bs, 2|(val<0),2);
584     else putAC( bs, run,val,0);
585 }
586
587 static void putnonintrablk( bs_transrate_t *bs, RunLevel *blk)
588 {
589     assert(blk->level);
590
591     putACfirst( bs, blk->run, blk->level);
592     blk++;
593
594     while(blk->level)
595     {
596         putAC( bs, blk->run, blk->level, 0);
597         blk++;
598     }
599
600     bs_write( bs, 2,2);
601 }
602
603 #include "getvlc.h"
604
605 static const int non_linear_quantizer_scale [] =
606 {
607      0,  1,  2,  3,  4,  5,   6,   7,
608      8, 10, 12, 14, 16, 18,  20,  22,
609     24, 28, 32, 36, 40, 44,  48,  52,
610     56, 64, 72, 80, 88, 96, 104, 112
611 };
612
613 static inline int get_macroblock_modes( transrate_t *tr )
614 {
615     bs_transrate_t *bs = &tr->bs;
616
617     int macroblock_modes;
618     const MBtab * tab;
619
620     switch( tr->picture_coding_type)
621     {
622         case I_TYPE:
623
624             tab = MB_I + UBITS (bs->i_bit_in_cache, 1);
625             bs_flush( bs, tab->len );
626             macroblock_modes = tab->modes;
627
628             if ((! ( tr->frame_pred_frame_dct)) && ( tr->picture_structure == FRAME_PICTURE))
629             {
630                 macroblock_modes |= UBITS (bs->i_bit_in_cache, 1) * DCT_TYPE_INTERLACED;
631                 bs_flush( bs, 1 );
632             }
633
634             return macroblock_modes;
635
636         case P_TYPE:
637
638             tab = MB_P + UBITS (bs->i_bit_in_cache, 5);
639             bs_flush( bs, tab->len );
640             macroblock_modes = tab->modes;
641
642             if (tr->picture_structure != FRAME_PICTURE)
643             {
644                 if (macroblock_modes & MACROBLOCK_MOTION_FORWARD)
645                 {
646                     macroblock_modes |= UBITS (bs->i_bit_in_cache, 2) * MOTION_TYPE_BASE;
647                     bs_flush( bs, 2 );
648                 }
649                 return macroblock_modes;
650             }
651             else if (tr->frame_pred_frame_dct)
652             {
653                 if (macroblock_modes & MACROBLOCK_MOTION_FORWARD)
654                     macroblock_modes |= MC_FRAME;
655                 return macroblock_modes;
656             }
657             else
658             {
659                 if (macroblock_modes & MACROBLOCK_MOTION_FORWARD)
660                 {
661                     macroblock_modes |= UBITS (bs->i_bit_in_cache, 2) * MOTION_TYPE_BASE;
662                     bs_flush( bs, 2 );
663                 }
664                 if (macroblock_modes & (MACROBLOCK_INTRA | MACROBLOCK_PATTERN))
665                 {
666                     macroblock_modes |= UBITS (bs->i_bit_in_cache, 1) * DCT_TYPE_INTERLACED;
667                     bs_flush( bs, 1 );
668                 }
669                 return macroblock_modes;
670             }
671
672         case B_TYPE:
673
674             tab = MB_B + UBITS (bs->i_bit_in_cache, 6);
675             bs_flush( bs, tab->len );
676             macroblock_modes = tab->modes;
677
678             if( tr->picture_structure != FRAME_PICTURE)
679             {
680                 if (! (macroblock_modes & MACROBLOCK_INTRA))
681                 {
682                     macroblock_modes |= UBITS (bs->i_bit_in_cache, 2) * MOTION_TYPE_BASE;
683                     bs_flush( bs, 2 );
684                 }
685                 return macroblock_modes;
686             }
687             else if (tr->frame_pred_frame_dct)
688             {
689                 /* if (! (macroblock_modes & MACROBLOCK_INTRA)) */
690                 macroblock_modes |= MC_FRAME;
691                 return macroblock_modes;
692             }
693             else
694             {
695                 if (macroblock_modes & MACROBLOCK_INTRA) goto intra;
696                 macroblock_modes |= UBITS (bs->i_bit_in_cache, 2) * MOTION_TYPE_BASE;
697                 bs_flush( bs, 2 );
698                 if (macroblock_modes & (MACROBLOCK_INTRA | MACROBLOCK_PATTERN))
699                 {
700                     intra:
701                     macroblock_modes |= UBITS (bs->i_bit_in_cache, 1) * DCT_TYPE_INTERLACED;
702                     bs_flush( bs, 1 );
703                 }
704                 return macroblock_modes;
705             }
706
707         default:
708             return 0;
709     }
710
711 }
712
713 static inline int get_quantizer_scale( transrate_t *tr )
714 {
715     bs_transrate_t *bs = &tr->bs;
716
717     int quantizer_scale_code;
718
719     quantizer_scale_code = UBITS (bs->i_bit_in_cache, 5);
720     bs_flush( bs, 5 );
721
722     if( tr->q_scale_type )
723         return non_linear_quantizer_scale[quantizer_scale_code];
724     else
725         return quantizer_scale_code << 1;
726 }
727
728 static inline int get_motion_delta( bs_transrate_t *bs, const int f_code )
729 {
730     int delta;
731     int sign;
732     const MVtab * tab;
733
734     if (bs->i_bit_in_cache & 0x80000000)
735     {
736         bs_copy( bs, 1 );
737         return 0;
738     }
739     else if (bs->i_bit_in_cache >= 0x0c000000)
740     {
741
742         tab = MV_4 + UBITS (bs->i_bit_in_cache, 4);
743         delta = (tab->delta << f_code) + 1;
744         bs_copy( bs, tab->len);
745
746         sign = SBITS (bs->i_bit_in_cache, 1);
747         bs_copy( bs, 1 );
748
749         if (f_code) delta += UBITS (bs->i_bit_in_cache, f_code);
750         bs_copy( bs, f_code);
751
752         return (delta ^ sign) - sign;
753     }
754     else
755     {
756
757         tab = MV_10 + UBITS (bs->i_bit_in_cache, 10);
758         delta = (tab->delta << f_code) + 1;
759         bs_copy( bs, tab->len);
760
761         sign = SBITS (bs->i_bit_in_cache, 1);
762         bs_copy( bs, 1);
763
764         if (f_code)
765         {
766             delta += UBITS (bs->i_bit_in_cache, f_code);
767             bs_copy( bs, f_code);
768         }
769
770         return (delta ^ sign) - sign;
771     }
772 }
773
774
775 static inline int get_dmv( bs_transrate_t *bs )
776 {
777     const DMVtab * tab;
778
779     tab = DMV_2 + UBITS (bs->i_bit_in_cache, 2);
780     bs_copy( bs, tab->len);
781     return tab->dmv;
782 }
783
784 static inline int get_coded_block_pattern( bs_transrate_t *bs )
785 {
786     const CBPtab * tab;
787
788     if (bs->i_bit_in_cache >= 0x20000000)
789     {
790         tab = CBP_7 + (UBITS (bs->i_bit_in_cache, 7) - 16);
791         bs_flush( bs, tab->len );
792         return tab->cbp;
793     }
794     else
795     {
796         tab = CBP_9 + UBITS (bs->i_bit_in_cache, 9);
797         bs_flush( bs, tab->len );
798         return tab->cbp;
799     }
800 }
801
802 static inline int get_luma_dc_dct_diff( bs_transrate_t *bs )
803 {
804     const DCtab * tab;
805     int size;
806     int dc_diff;
807
808     if (bs->i_bit_in_cache < 0xf8000000)
809     {
810         tab = DC_lum_5 + UBITS (bs->i_bit_in_cache, 5);
811         size = tab->size;
812         if (size)
813         {
814             bs_copy( bs, tab->len);
815             //dc_diff = UBITS (bs->i_bit_in_cache, size) - UBITS (SBITS (~bs->i_bit_in_cache, 1), size);
816             dc_diff = UBITS (bs->i_bit_in_cache, size);
817             if (!(dc_diff >> (size - 1))) dc_diff = (dc_diff + 1) - (1 << size);
818             bs_copy( bs, size);
819             return dc_diff;
820         }
821         else
822         {
823             bs_copy( bs, 3);
824             return 0;
825         }
826     }
827     else
828     {
829         tab = DC_long + (UBITS (bs->i_bit_in_cache, 9) - 0x1e0);
830         size = tab->size;
831         bs_copy( bs, tab->len);
832         //dc_diff = UBITS (bs->i_bit_in_cache, size) - UBITS (SBITS (~bs->i_bit_in_cache, 1), size);
833         dc_diff = UBITS (bs->i_bit_in_cache, size);
834         if (!(dc_diff >> (size - 1))) dc_diff = (dc_diff + 1) - (1 << size);
835         bs_copy( bs, size);
836         return dc_diff;
837     }
838 }
839
840 static inline int get_chroma_dc_dct_diff( bs_transrate_t *bs )
841 {
842     const DCtab * tab;
843     int size;
844     int dc_diff;
845
846     if (bs->i_bit_in_cache < 0xf8000000)
847     {
848         tab = DC_chrom_5 + UBITS (bs->i_bit_in_cache, 5);
849         size = tab->size;
850         if (size)
851         {
852             bs_copy( bs, tab->len);
853             //dc_diff = UBITS (bs->i_bit_in_cache, size) - UBITS (SBITS (~bs->i_bit_in_cache, 1), size);
854             dc_diff = UBITS (bs->i_bit_in_cache, size);
855             if (!(dc_diff >> (size - 1))) dc_diff = (dc_diff + 1) - (1 << size);
856             bs_copy( bs, size);
857             return dc_diff;
858         } else
859         {
860             bs_copy( bs, 2);
861             return 0;
862         }
863     }
864     else
865     {
866         tab = DC_long + (UBITS (bs->i_bit_in_cache, 10) - 0x3e0);
867         size = tab->size;
868         bs_copy( bs, tab->len + 1);
869         //dc_diff = UBITS (bs->i_bit_in_cache, size) - UBITS (SBITS (~bs->i_bit_in_cache, 1), size);
870         dc_diff = UBITS (bs->i_bit_in_cache, size);
871         if (!(dc_diff >> (size - 1))) dc_diff = (dc_diff + 1) - (1 << size);
872         bs_copy( bs, size);
873         return dc_diff;
874     }
875 }
876
877 static void get_intra_block_B14( bs_transrate_t *bs, const int i_qscale, const int i_qscale_new )
878 {
879     int tst;
880     int i, li;
881     int val;
882     const DCTtab * tab;
883
884     /* Basic sanity check --Meuuh */
885     if( i_qscale == 0 )
886     {
887         return;
888     }
889
890     tst = i_qscale_new/i_qscale + ((i_qscale_new%i_qscale) ? 1 : 0);
891
892     li = i = 0;
893
894     for( ;; )
895     {
896         if (bs->i_bit_in_cache >= 0x28000000)
897         {
898             tab = DCT_B14AC_5 + (UBITS (bs->i_bit_in_cache, 5) - 5);
899
900             i += tab->run;
901             if (i >= 64) break; /* end of block */
902
903     normal_code:
904             bs_flush( bs, tab->len );
905             val = tab->level;
906             if (val >= tst)
907             {
908                 val = (val ^ SBITS (bs->i_bit_in_cache, 1)) - SBITS (bs->i_bit_in_cache, 1);
909                 putAC( bs, i - li - 1, (val * i_qscale) / i_qscale_new, 0);
910                 li = i;
911             }
912
913             bs_flush( bs, 1 );
914             continue;
915         }
916         else if (bs->i_bit_in_cache >= 0x04000000)
917         {
918             tab = DCT_B14_8 + (UBITS (bs->i_bit_in_cache, 8) - 4);
919
920             i += tab->run;
921             if (i < 64) goto normal_code;
922
923             /* escape code */
924             i += (UBITS (bs->i_bit_in_cache, 12) & 0x3F) - 64;
925             if (i >= 64) break; /* illegal, check needed to avoid buffer overflow */
926
927             bs_flush( bs, 12 );
928             val = SBITS (bs->i_bit_in_cache, 12);
929             if (abs(val) >= tst)
930             {
931                 putAC( bs, i - li - 1, (val * i_qscale) / i_qscale_new, 0);
932                 li = i;
933             }
934
935             bs_flush( bs, 12 );
936
937             continue;
938         }
939         else if (bs->i_bit_in_cache >= 0x02000000)
940         {
941             tab = DCT_B14_10 + (UBITS (bs->i_bit_in_cache, 10) - 8);
942             i += tab->run;
943             if (i < 64) goto normal_code;
944         }
945         else if (bs->i_bit_in_cache >= 0x00800000)
946         {
947             tab = DCT_13 + (UBITS (bs->i_bit_in_cache, 13) - 16);
948             i += tab->run;
949             if (i < 64) goto normal_code;
950         }
951         else if (bs->i_bit_in_cache >= 0x00200000)
952         {
953             tab = DCT_15 + (UBITS (bs->i_bit_in_cache, 15) - 16);
954             i += tab->run;
955             if (i < 64) goto normal_code;
956         }
957         else
958         {
959             tab = DCT_16 + UBITS (bs->i_bit_in_cache, 16);
960             bs_flush( bs, 16);
961             i += tab->run;
962             if (i < 64) goto normal_code;
963         }
964         break;  /* illegal, check needed to avoid buffer overflow */
965     }
966
967     bs_copy( bs, 2);    /* end of block code */
968 }
969
970 static void get_intra_block_B15( bs_transrate_t *bs,  const int i_qscale, int const i_qscale_new )
971 {
972     int tst;
973     int i, li;
974     int val;
975     const DCTtab * tab;
976
977     /* Basic sanity check --Meuuh */
978     if( i_qscale == 0 )
979     {
980         return;
981     }
982
983     tst = i_qscale_new/i_qscale + ((i_qscale_new%i_qscale) ? 1 : 0);
984
985     li = i = 0;
986
987     for( ;; )
988     {
989         if (bs->i_bit_in_cache >= 0x04000000)
990         {
991             tab = DCT_B15_8 + (UBITS (bs->i_bit_in_cache, 8) - 4);
992
993             i += tab->run;
994             if (i < 64)
995             {
996     normal_code:
997                 bs_flush( bs, tab->len );
998
999                 val = tab->level;
1000                 if (val >= tst)
1001                 {
1002                     val = (val ^ SBITS (bs->i_bit_in_cache, 1)) - SBITS (bs->i_bit_in_cache, 1);
1003                     putAC( bs, i - li - 1, (val * i_qscale) / i_qscale_new, 1);
1004                     li = i;
1005                 }
1006
1007                 bs_flush( bs, 1 );
1008                 continue;
1009             }
1010             else
1011             {
1012                 i += (UBITS (bs->i_bit_in_cache, 12) & 0x3F) - 64;
1013
1014                 if (i >= 64) break; /* illegal, check against buffer overflow */
1015
1016                 bs_flush( bs, 12 );
1017                 val = SBITS (bs->i_bit_in_cache, 12);
1018                 if (abs(val) >= tst)
1019                 {
1020                     putAC( bs, i - li - 1, (val * i_qscale) / i_qscale_new, 1);
1021                     li = i;
1022                 }
1023
1024                 bs_flush( bs, 12 );
1025                 continue;
1026             }
1027         }
1028         else if (bs->i_bit_in_cache >= 0x02000000)
1029         {
1030             tab = DCT_B15_10 + (UBITS (bs->i_bit_in_cache, 10) - 8);
1031             i += tab->run;
1032             if (i < 64) goto normal_code;
1033         }
1034         else if (bs->i_bit_in_cache >= 0x00800000)
1035         {
1036             tab = DCT_13 + (UBITS (bs->i_bit_in_cache, 13) - 16);
1037             i += tab->run;
1038             if (i < 64) goto normal_code;
1039         }
1040         else if (bs->i_bit_in_cache >= 0x00200000)
1041         {
1042             tab = DCT_15 + (UBITS (bs->i_bit_in_cache, 15) - 16);
1043             i += tab->run;
1044             if (i < 64) goto normal_code;
1045         }
1046         else
1047         {
1048             tab = DCT_16 + UBITS (bs->i_bit_in_cache, 16);
1049             bs_flush( bs, 16 );
1050             i += tab->run;
1051             if (i < 64) goto normal_code;
1052         }
1053         break;  /* illegal, check needed to avoid buffer overflow */
1054     }
1055
1056     bs_copy( bs, 4);    /* end of block code */
1057 }
1058
1059
1060 static int get_non_intra_block_drop( transrate_t *tr, RunLevel *blk)
1061 {
1062     bs_transrate_t *bs = &tr->bs;
1063
1064     int i, li;
1065     int val;
1066     const DCTtab * tab;
1067     RunLevel *sblk = blk + 1;
1068
1069     li = i = -1;
1070
1071     if (bs->i_bit_in_cache >= 0x28000000)
1072     {
1073         tab = DCT_B14DC_5 + (UBITS (bs->i_bit_in_cache, 5) - 5);
1074         goto entry_1;
1075     }
1076     else goto entry_2;
1077
1078     for( ;; )
1079     {
1080         if (bs->i_bit_in_cache >= 0x28000000)
1081         {
1082             tab = DCT_B14AC_5 + (UBITS (bs->i_bit_in_cache, 5) - 5);
1083
1084     entry_1:
1085             i += tab->run;
1086             if (i >= 64) break; /* end of block */
1087
1088     normal_code:
1089
1090             bs_flush( bs, tab->len );
1091             val = tab->level;
1092             val = (val ^ SBITS (bs->i_bit_in_cache, 1)) - SBITS (bs->i_bit_in_cache, 1); /* if (bitstream_get (1)) val = -val; */
1093
1094             blk->level = val;
1095             blk->run = i - li - 1;
1096             li = i;
1097             blk++;
1098
1099             bs_flush( bs, 1 );
1100             continue;
1101         }
1102
1103     entry_2:
1104
1105         if (bs->i_bit_in_cache >= 0x04000000)
1106         {
1107             tab = DCT_B14_8 + (UBITS (bs->i_bit_in_cache, 8) - 4);
1108
1109             i += tab->run;
1110             if (i < 64) goto normal_code;
1111
1112             /* escape code */
1113
1114             i += (UBITS (bs->i_bit_in_cache, 12) & 0x3F) - 64;
1115
1116             if (i >= 64) break; /* illegal, check needed to avoid buffer overflow */
1117
1118             bs_flush( bs, 12 );
1119             val = SBITS (bs->i_bit_in_cache, 12);
1120
1121             blk->level = val;
1122             blk->run = i - li - 1;
1123             li = i;
1124             blk++;
1125
1126             bs_flush( bs, 12 );
1127             continue;
1128         }
1129         else if (bs->i_bit_in_cache >= 0x02000000)
1130         {
1131             tab = DCT_B14_10 + (UBITS (bs->i_bit_in_cache, 10) - 8);
1132             i += tab->run;
1133             if (i < 64) goto normal_code;
1134         }
1135         else if (bs->i_bit_in_cache >= 0x00800000)
1136         {
1137             tab = DCT_13 + (UBITS (bs->i_bit_in_cache, 13) - 16);
1138             i += tab->run;
1139             if (i < 64) goto normal_code;
1140         }
1141         else if (bs->i_bit_in_cache >= 0x00200000)
1142         {
1143             tab = DCT_15 + (UBITS (bs->i_bit_in_cache, 15) - 16);
1144             i += tab->run;
1145             if (i < 64) goto normal_code;
1146         }
1147         else
1148         {
1149             tab = DCT_16 + UBITS (bs->i_bit_in_cache, 16);
1150             bs_flush( bs, 16 );
1151             i += tab->run;
1152             if (i < 64) goto normal_code;
1153         }
1154         break;  /* illegal, check needed to avoid buffer overflow */
1155     }
1156     bs_flush( bs, 2 ); /* dump end of block code */
1157
1158     // remove last coeff
1159     if (blk != sblk)
1160     {
1161         blk--;
1162         // remove more coeffs if very late
1163         if ((tr->quant_corr < -60.0f) && (blk != sblk))
1164         {
1165             blk--;
1166             if ((tr->quant_corr < -80.0f) && (blk != sblk))
1167             {
1168                 blk--;
1169                 if ((tr->quant_corr < -100.0f) && (blk != sblk))
1170                 {
1171                     blk--;
1172                     if ((tr->quant_corr < -120.0f) && (blk != sblk))
1173                         blk--;
1174                 }
1175             }
1176         }
1177     }
1178
1179     blk->level = 0;
1180
1181     return i;
1182 }
1183
1184 static int get_non_intra_block_rq( bs_transrate_t *bs, RunLevel *blk,  const int i_qscale, const int i_qscale_new )
1185 {
1186     int tst;
1187     int i, li;
1188     int val;
1189     const DCTtab * tab;
1190
1191     /* Basic sanity check --Meuuh */
1192     if( i_qscale == 0 )
1193     {
1194         return 0;
1195     }
1196
1197     tst = i_qscale_new/i_qscale + ((i_qscale_new%i_qscale) ? 1 : 0);
1198
1199     li = i = -1;
1200
1201     if (bs->i_bit_in_cache >= 0x28000000)
1202     {
1203         tab = DCT_B14DC_5 + (UBITS (bs->i_bit_in_cache, 5) - 5);
1204         goto entry_1;
1205     }
1206     else goto entry_2;
1207
1208     for( ;; )
1209     {
1210         if (bs->i_bit_in_cache >= 0x28000000)
1211         {
1212             tab = DCT_B14AC_5 + (UBITS (bs->i_bit_in_cache, 5) - 5);
1213
1214     entry_1:
1215             i += tab->run;
1216             if (i >= 64)
1217             break;  /* end of block */
1218
1219     normal_code:
1220
1221             bs_flush( bs, tab->len );
1222             val = tab->level;
1223             if (val >= tst)
1224             {
1225                 val = (val ^ SBITS (bs->i_bit_in_cache, 1)) - SBITS (bs->i_bit_in_cache, 1);
1226                 blk->level = (val * i_qscale) / i_qscale_new;
1227                 blk->run = i - li - 1;
1228                 li = i;
1229                 blk++;
1230             }
1231
1232             //if ( ((val) && (tab->level < tst)) || ((!val) && (tab->level >= tst)) )
1233             //  LOGF("level: %i val: %i tst : %i q: %i nq : %i\n", tab->level, val, tst, q, nq);
1234
1235             bs_flush( bs, 1 );
1236             continue;
1237         }
1238
1239     entry_2:
1240         if (bs->i_bit_in_cache >= 0x04000000)
1241         {
1242             tab = DCT_B14_8 + (UBITS (bs->i_bit_in_cache, 8) - 4);
1243
1244             i += tab->run;
1245             if (i < 64) goto normal_code;
1246
1247             /* escape code */
1248
1249             i += (UBITS (bs->i_bit_in_cache, 12) & 0x3F) - 64;
1250
1251             if (i >= 64) break; /* illegal, check needed to avoid buffer overflow */
1252
1253             bs_flush( bs, 12 );
1254             val = SBITS (bs->i_bit_in_cache, 12);
1255             if (abs(val) >= tst)
1256             {
1257                 blk->level = (val * i_qscale) / i_qscale_new;
1258                 blk->run = i - li - 1;
1259                 li = i;
1260                 blk++;
1261             }
1262
1263             bs_flush( bs, 12 );
1264             continue;
1265         }
1266         else if (bs->i_bit_in_cache >= 0x02000000)
1267         {
1268             tab = DCT_B14_10 + (UBITS (bs->i_bit_in_cache, 10) - 8);
1269             i += tab->run;
1270             if (i < 64) goto normal_code;
1271         }
1272         else if (bs->i_bit_in_cache >= 0x00800000)
1273         {
1274             tab = DCT_13 + (UBITS (bs->i_bit_in_cache, 13) - 16);
1275             i += tab->run;
1276             if (i < 64) goto normal_code;
1277         }
1278         else if (bs->i_bit_in_cache >= 0x00200000)
1279         {
1280             tab = DCT_15 + (UBITS (bs->i_bit_in_cache, 15) - 16);
1281             i += tab->run;
1282             if (i < 64) goto normal_code;
1283         }
1284         else
1285         {
1286             tab = DCT_16 + UBITS (bs->i_bit_in_cache, 16);
1287             bs_flush( bs, 16 );
1288
1289             i += tab->run;
1290             if (i < 64) goto normal_code;
1291         }
1292         break;  /* illegal, check needed to avoid buffer overflow */
1293     }
1294     bs_flush( bs, 2 );    /* dump end of block code */
1295
1296     blk->level = 0;
1297
1298     return i;
1299 }
1300
1301 static void motion_fr_frame( bs_transrate_t *bs, unsigned int f_code[2] )
1302 {
1303     get_motion_delta( bs, f_code[0] );
1304     get_motion_delta( bs, f_code[1] );
1305 }
1306
1307 static void motion_fr_field( bs_transrate_t *bs, unsigned int f_code[2] )
1308 {
1309     bs_copy( bs, 1);
1310
1311     get_motion_delta( bs, f_code[0]);
1312     get_motion_delta( bs, f_code[1]);
1313
1314     bs_copy( bs, 1);
1315
1316     get_motion_delta( bs, f_code[0]);
1317     get_motion_delta( bs, f_code[1]);
1318 }
1319
1320 static void motion_fr_dmv( bs_transrate_t *bs, unsigned int f_code[2] )
1321 {
1322     get_motion_delta( bs, f_code[0]);
1323     get_dmv( bs );
1324
1325     get_motion_delta( bs, f_code[1]);
1326     get_dmv( bs );
1327 }
1328
1329 static void motion_fi_field( bs_transrate_t *bs, unsigned int f_code[2] )
1330 {
1331     bs_copy( bs, 1);
1332
1333     get_motion_delta( bs, f_code[0]);
1334     get_motion_delta( bs, f_code[1]);
1335 }
1336
1337 static void motion_fi_16x8( bs_transrate_t *bs, unsigned int f_code[2] )
1338 {
1339     bs_copy( bs, 1);
1340
1341     get_motion_delta( bs, f_code[0]);
1342     get_motion_delta( bs, f_code[1]);
1343
1344     bs_copy( bs, 1);
1345
1346     get_motion_delta( bs, f_code[0]);
1347     get_motion_delta( bs, f_code[1]);
1348 }
1349
1350 static void motion_fi_dmv( bs_transrate_t *bs, unsigned int f_code[2] )
1351 {
1352     get_motion_delta( bs, f_code[0]);
1353     get_dmv( bs );
1354
1355     get_motion_delta( bs, f_code[1]);
1356     get_dmv( bs );
1357 }
1358
1359
1360 #define MOTION_CALL(routine,direction)                      \
1361 do {                                                        \
1362     if ((direction) & MACROBLOCK_MOTION_FORWARD)            \
1363         routine( bs, tr->f_code[0]);                        \
1364     if ((direction) & MACROBLOCK_MOTION_BACKWARD)           \
1365         routine( bs, tr->f_code[1]);                        \
1366 } while (0)
1367
1368 #define NEXT_MACROBLOCK                                         \
1369 do {                                                            \
1370     tr->h_offset += 16;                                         \
1371     if( tr->h_offset == tr->horizontal_size_value)              \
1372     {                                                           \
1373         tr->v_offset += 16;                                         \
1374         if (tr->v_offset > (tr->vertical_size_value - 16)) return;      \
1375         tr->h_offset = 0;                                       \
1376     }                                                           \
1377 } while (0)
1378
1379 static void putmbdata( transrate_t *tr, int macroblock_modes )
1380 {
1381     bs_transrate_t *bs = &tr->bs;
1382
1383     bs_write( bs,
1384               mbtypetab[tr->picture_coding_type-1][macroblock_modes&0x1F].code,
1385               mbtypetab[tr->picture_coding_type-1][macroblock_modes&0x1F].len);
1386
1387     switch ( tr->picture_coding_type)
1388     {
1389         case I_TYPE:
1390             if ((! (tr->frame_pred_frame_dct)) && (tr->picture_structure == FRAME_PICTURE))
1391                 bs_write( bs, macroblock_modes & DCT_TYPE_INTERLACED ? 1 : 0, 1);
1392             break;
1393
1394         case P_TYPE:
1395             if (tr->picture_structure != FRAME_PICTURE)
1396             {
1397                 if (macroblock_modes & MACROBLOCK_MOTION_FORWARD)
1398                     bs_write( bs, (macroblock_modes & MOTION_TYPE_MASK) / MOTION_TYPE_BASE, 2);
1399                 break;
1400             }
1401             else if (tr->frame_pred_frame_dct) break;
1402             else
1403             {
1404                 if (macroblock_modes & MACROBLOCK_MOTION_FORWARD)
1405                     bs_write( bs, (macroblock_modes & MOTION_TYPE_MASK) / MOTION_TYPE_BASE, 2);
1406                 if (macroblock_modes & (MACROBLOCK_INTRA | MACROBLOCK_PATTERN))
1407                     bs_write( bs, macroblock_modes & DCT_TYPE_INTERLACED ? 1 : 0, 1);
1408                 break;
1409             }
1410
1411         case B_TYPE:
1412             if (tr->picture_structure != FRAME_PICTURE)
1413             {
1414                 if (! (macroblock_modes & MACROBLOCK_INTRA))
1415                     bs_write( bs, (macroblock_modes & MOTION_TYPE_MASK) / MOTION_TYPE_BASE, 2);
1416                 break;
1417             }
1418             else if (tr->frame_pred_frame_dct) break;
1419             else
1420             {
1421                 if (macroblock_modes & MACROBLOCK_INTRA) goto intra;
1422                 bs_write( bs, (macroblock_modes & MOTION_TYPE_MASK) / MOTION_TYPE_BASE, 2);
1423                 if (macroblock_modes & (MACROBLOCK_INTRA | MACROBLOCK_PATTERN))
1424                 {
1425                     intra:
1426                     bs_write( bs, macroblock_modes & DCT_TYPE_INTERLACED ? 1 : 0, 1);
1427                 }
1428                 break;
1429             }
1430     }
1431 }
1432
1433 static inline void put_quantiser( transrate_t *tr )
1434 {
1435     bs_transrate_t *bs = &tr->bs;
1436
1437     bs_write( bs, tr->q_scale_type ? map_non_linear_mquant[tr->new_quantizer_scale] : tr->new_quantizer_scale >> 1, 5);
1438     tr->last_coded_scale = tr->new_quantizer_scale;
1439 }
1440
1441 static int slice_init( transrate_t *tr,  int code)
1442 {
1443     bs_transrate_t *bs = &tr->bs;
1444     int offset;
1445     const MBAtab * mba;
1446
1447     tr->v_offset = (code - 1) * 16;
1448
1449     tr->quantizer_scale = get_quantizer_scale( tr );
1450     if ( tr->picture_coding_type == P_TYPE)
1451     {
1452         tr->new_quantizer_scale = tr->quantizer_scale;
1453     }
1454     else
1455     {
1456         tr->new_quantizer_scale = getNewQuant(tr, tr->quantizer_scale);
1457     }
1458     put_quantiser( tr );
1459
1460     /*LOGF("************************\nstart of slice %i in %s picture. ori quant: %i new quant: %i\n", code,
1461         (picture_coding_type == I_TYPE ? "I_TYPE" : (picture_coding_type == P_TYPE ? "P_TYPE" : "B_TYPE")),
1462         quantizer_scale, new_quantizer_scale);*/
1463
1464     /* ignore intra_slice and all the extra data */
1465     while (bs->i_bit_in_cache & 0x80000000)
1466     {
1467         bs_flush( bs, 9 );
1468     }
1469
1470     /* decode initial macroblock address increment */
1471     offset = 0;
1472     for( ;; )
1473     {
1474         if (bs->i_bit_in_cache >= 0x08000000)
1475         {
1476             mba = MBA_5 + (UBITS (bs->i_bit_in_cache, 6) - 2);
1477             break;
1478         }
1479         else if (bs->i_bit_in_cache >= 0x01800000)
1480         {
1481             mba = MBA_11 + (UBITS (bs->i_bit_in_cache, 12) - 24);
1482             break;
1483         }
1484         else if( UBITS (bs->i_bit_in_cache, 12 ) == 8 )
1485         {
1486             /* macroblock_escape */
1487             offset += 33;
1488             bs_copy( bs, 11);
1489         }
1490         else
1491         {
1492             return -1;
1493         }
1494     }
1495
1496     bs_copy( bs, mba->len + 1);
1497     tr->h_offset = (offset + mba->mba) << 4;
1498
1499     while( tr->h_offset - (int)tr->horizontal_size_value >= 0)
1500     {
1501         tr->h_offset -= tr->horizontal_size_value;
1502         tr->v_offset += 16;
1503     }
1504
1505     if( tr->v_offset > tr->vertical_size_value - 16 )
1506     {
1507         return -1;
1508     }
1509     return 0;
1510 }
1511
1512 static void mpeg2_slice( transrate_t *tr, const int code )
1513 {
1514     bs_transrate_t *bs = &tr->bs;
1515
1516     if( slice_init( tr, code ) )
1517     {
1518         return;
1519     }
1520
1521     for( ;; )
1522     {
1523         int macroblock_modes;
1524         int mba_inc;
1525         const MBAtab * mba;
1526
1527         macroblock_modes = get_macroblock_modes( tr );
1528         if (macroblock_modes & MACROBLOCK_QUANT) tr->quantizer_scale = get_quantizer_scale( tr );
1529
1530         //LOGF("blk %i : ", h_offset >> 4);
1531
1532         if (macroblock_modes & MACROBLOCK_INTRA)
1533         {
1534             //LOG("intra "); if (macroblock_modes & MACROBLOCK_QUANT) LOGF("got new quant: %i ", quantizer_scale);
1535
1536             tr->new_quantizer_scale = increment_quant( tr, tr->quantizer_scale);
1537             if (tr->last_coded_scale == tr->new_quantizer_scale) macroblock_modes &= 0xFFFFFFEF; // remove MACROBLOCK_QUANT
1538             else macroblock_modes |= MACROBLOCK_QUANT; //add MACROBLOCK_QUANT
1539             putmbdata( tr, macroblock_modes);
1540             if (macroblock_modes & MACROBLOCK_QUANT) put_quantiser( tr );
1541
1542             //if (macroblock_modes & MACROBLOCK_QUANT) LOGF("put new quant: %i ", new_quantizer_scale);
1543
1544             if (tr->concealment_motion_vectors)
1545             {
1546                 if (tr->picture_structure != FRAME_PICTURE)
1547                 {
1548                     bs_copy( bs, 1); /* remove field_select */
1549                 }
1550                 /* like motion_frame, but parsing without actual motion compensation */
1551                 get_motion_delta( bs, tr->f_code[0][0]);
1552                 get_motion_delta( bs, tr->f_code[0][1]);
1553
1554                 bs_copy( bs, 1); /* remove marker_bit */
1555             }
1556
1557             if( tr->intra_vlc_format )
1558             {
1559                 /* Luma */
1560                 get_luma_dc_dct_diff( bs );     get_intra_block_B15( bs, tr->quantizer_scale, tr->new_quantizer_scale );
1561                 get_luma_dc_dct_diff( bs );     get_intra_block_B15( bs, tr->quantizer_scale, tr->new_quantizer_scale );
1562                 get_luma_dc_dct_diff( bs );     get_intra_block_B15( bs, tr->quantizer_scale, tr->new_quantizer_scale );
1563                 get_luma_dc_dct_diff( bs );     get_intra_block_B15( bs, tr->quantizer_scale, tr->new_quantizer_scale );
1564                 /* Chroma */
1565                 get_chroma_dc_dct_diff( bs );   get_intra_block_B15( bs, tr->quantizer_scale, tr->new_quantizer_scale );
1566                 get_chroma_dc_dct_diff( bs );   get_intra_block_B15( bs, tr->quantizer_scale, tr->new_quantizer_scale );
1567             }
1568             else
1569             {
1570                 /* Luma */
1571                 get_luma_dc_dct_diff( bs );     get_intra_block_B14( bs, tr->quantizer_scale, tr->new_quantizer_scale );
1572                 get_luma_dc_dct_diff( bs );     get_intra_block_B14( bs, tr->quantizer_scale, tr->new_quantizer_scale );
1573                 get_luma_dc_dct_diff( bs );     get_intra_block_B14( bs, tr->quantizer_scale, tr->new_quantizer_scale );
1574                 get_luma_dc_dct_diff( bs );     get_intra_block_B14( bs, tr->quantizer_scale, tr->new_quantizer_scale );
1575                 /* Chroma */
1576                 get_chroma_dc_dct_diff( bs );   get_intra_block_B14( bs, tr->quantizer_scale, tr->new_quantizer_scale );
1577                 get_chroma_dc_dct_diff( bs );   get_intra_block_B14( bs, tr->quantizer_scale, tr->new_quantizer_scale );
1578             }
1579         }
1580         else
1581         {
1582             RunLevel block[6][65]; // terminated by level = 0, so we need 64+1
1583             int new_coded_block_pattern = 0;
1584
1585             // begin saving data
1586             int batb;
1587             uint8_t   p_n_ow[32], *p_n_w,
1588                     *p_o_ow = bs->p_ow, *p_o_w = bs->p_w;
1589             uint32_t  i_n_bit_out, i_n_bit_out_cache,
1590                     i_o_bit_out  = bs->i_bit_out, i_o_bit_out_cache = bs->i_bit_out_cache;
1591
1592             bs->i_bit_out_cache = 0; bs->i_bit_out = BITS_IN_BUF;
1593             bs->p_ow = bs->p_w = p_n_ow;
1594
1595             if (tr->picture_structure == FRAME_PICTURE)
1596                 switch (macroblock_modes & MOTION_TYPE_MASK)
1597                 {
1598                     case MC_FRAME: MOTION_CALL (motion_fr_frame, macroblock_modes); break;
1599                     case MC_FIELD: MOTION_CALL (motion_fr_field, macroblock_modes); break;
1600                     case MC_DMV: MOTION_CALL (motion_fr_dmv, MACROBLOCK_MOTION_FORWARD); break;
1601                 }
1602             else
1603                 switch (macroblock_modes & MOTION_TYPE_MASK)
1604                 {
1605                     case MC_FIELD: MOTION_CALL (motion_fi_field, macroblock_modes); break;
1606                     case MC_16X8: MOTION_CALL (motion_fi_16x8, macroblock_modes); break;
1607                     case MC_DMV: MOTION_CALL (motion_fi_dmv, MACROBLOCK_MOTION_FORWARD); break;
1608                 }
1609
1610             assert(bs->p_w - bs->p_ow < 32);
1611
1612             p_n_w = bs->p_w;
1613             i_n_bit_out = bs->i_bit_out;
1614             i_n_bit_out_cache = bs->i_bit_out_cache;
1615             assert(bs->p_ow == p_n_ow);
1616
1617             bs->i_bit_out = i_o_bit_out ;
1618             bs->i_bit_out_cache = i_o_bit_out_cache;
1619             bs->p_ow = p_o_ow;
1620             bs->p_w = p_o_w;
1621             // end saving data
1622
1623             if ( tr->picture_coding_type == P_TYPE) tr->new_quantizer_scale = tr->quantizer_scale;
1624             else tr->new_quantizer_scale = getNewQuant( tr, tr->quantizer_scale);
1625
1626             //LOG("non intra "); if (macroblock_modes & MACROBLOCK_QUANT) LOGF("got new quant: %i ", quantizer_scale);
1627
1628             if (macroblock_modes & MACROBLOCK_PATTERN)
1629             {
1630                 const int cbp = get_coded_block_pattern( bs );
1631
1632                 if( tr->picture_coding_type == P_TYPE )
1633                 {
1634                     if( cbp&0x20 ) get_non_intra_block_drop( tr, block[0] );
1635                     if( cbp&0x10 ) get_non_intra_block_drop( tr, block[1] );
1636                     if( cbp&0x08 ) get_non_intra_block_drop( tr, block[2] );
1637                     if( cbp&0x04 ) get_non_intra_block_drop( tr, block[3] );
1638                     if( cbp&0x02 ) get_non_intra_block_drop( tr, block[4] );
1639                     if( cbp&0x01 ) get_non_intra_block_drop( tr, block[5] );
1640
1641                     new_coded_block_pattern = cbp;
1642                 }
1643                 else
1644                 {
1645                     if( cbp&0x20 )
1646                     {
1647                         get_non_intra_block_rq( bs, block[0], tr->quantizer_scale, tr->new_quantizer_scale );
1648                         if( isNotEmpty( block[0] ) ) new_coded_block_pattern |= 0x20;
1649                     }
1650                     if( cbp&0x10 )
1651                     {
1652                         get_non_intra_block_rq( bs, block[1], tr->quantizer_scale, tr->new_quantizer_scale );
1653                         if( isNotEmpty( block[1] ) ) new_coded_block_pattern |= 0x10;
1654                     }
1655                     if( cbp&0x08 )
1656                     {
1657                         get_non_intra_block_rq( bs, block[2], tr->quantizer_scale, tr->new_quantizer_scale );
1658                         if( isNotEmpty( block[2] ) ) new_coded_block_pattern |= 0x08;
1659                     }
1660                     if( cbp&0x04 )
1661                     {
1662                         get_non_intra_block_rq( bs, block[3], tr->quantizer_scale, tr->new_quantizer_scale );
1663                         if( isNotEmpty( block[3] ) ) new_coded_block_pattern |= 0x04;
1664                     }
1665                     if( cbp&0x02 )
1666                     {
1667                         get_non_intra_block_rq( bs, block[4], tr->quantizer_scale, tr->new_quantizer_scale );
1668                         if( isNotEmpty( block[4] ) ) new_coded_block_pattern |= 0x02;
1669                     }
1670                     if( cbp&0x01 )
1671                     {
1672                         get_non_intra_block_rq( bs, block[5], tr->quantizer_scale, tr->new_quantizer_scale );
1673                         if( isNotEmpty( block[5] ) ) new_coded_block_pattern |= 0x01;
1674                     }
1675                     if( !new_coded_block_pattern) macroblock_modes &= 0xFFFFFFED; // remove MACROBLOCK_PATTERN and MACROBLOCK_QUANT flag
1676                 }
1677             }
1678
1679             if (tr->last_coded_scale == tr->new_quantizer_scale) macroblock_modes &= 0xFFFFFFEF; // remove MACROBLOCK_QUANT
1680             else if (macroblock_modes & MACROBLOCK_PATTERN) macroblock_modes |= MACROBLOCK_QUANT; //add MACROBLOCK_QUANT
1681             assert( (macroblock_modes & MACROBLOCK_PATTERN) || !(macroblock_modes & MACROBLOCK_QUANT) );
1682
1683             putmbdata( tr, macroblock_modes);
1684             if( macroblock_modes & MACROBLOCK_QUANT )
1685             {
1686                 put_quantiser( tr );
1687             }
1688
1689             // put saved motion data...
1690             for (batb = 0; batb < (p_n_w - p_n_ow); batb++)
1691             {
1692                 bs_write( bs, p_n_ow[batb], 8 );
1693             }
1694             bs_write( bs, i_n_bit_out_cache, BITS_IN_BUF - i_n_bit_out);
1695             // end saved motion data...
1696
1697             if (macroblock_modes & MACROBLOCK_PATTERN)
1698             {
1699                 /* Write CBP */
1700                 bs_write( bs, cbptable[new_coded_block_pattern].code,cbptable[new_coded_block_pattern].len);
1701
1702                 if (new_coded_block_pattern & 0x20) putnonintrablk( bs, block[0]);
1703                 if (new_coded_block_pattern & 0x10) putnonintrablk( bs, block[1]);
1704                 if (new_coded_block_pattern & 0x08) putnonintrablk( bs, block[2]);
1705                 if (new_coded_block_pattern & 0x04) putnonintrablk( bs, block[3]);
1706                 if (new_coded_block_pattern & 0x02) putnonintrablk( bs, block[4]);
1707                 if (new_coded_block_pattern & 0x01) putnonintrablk( bs, block[5]);
1708             }
1709         }
1710
1711         //LOGF("\n\to: %i c: %i n: %i\n", quantizer_scale, last_coded_scale, new_quantizer_scale);
1712
1713         NEXT_MACROBLOCK;
1714
1715         mba_inc = 0;
1716         for( ;; )
1717         {
1718             if (bs->i_bit_in_cache >= 0x10000000)
1719             {
1720                 mba = MBA_5 + (UBITS (bs->i_bit_in_cache, 5) - 2);
1721                 break;
1722             }
1723             else if (bs->i_bit_in_cache >= 0x03000000)
1724             {
1725                 mba = MBA_11 + (UBITS (bs->i_bit_in_cache, 11) - 24);
1726                 break;
1727             }
1728             else if( UBITS (bs->i_bit_in_cache, 11 ) == 8 )
1729             {
1730                 /* macroblock_escape */
1731                 mba_inc += 33;
1732                 bs_copy( bs, 11);
1733             }
1734             else
1735             {
1736                 /* EOS or error */
1737                 return;
1738             }
1739         }
1740         bs_copy( bs, mba->len);
1741         mba_inc += mba->mba;
1742
1743         while( mba_inc-- )
1744         {
1745             NEXT_MACROBLOCK;
1746         }
1747     }
1748 }
1749
1750 /////---- end ext mpeg code
1751
1752 static int do_next_start_code( transrate_t *tr )
1753 {
1754     bs_transrate_t *bs = &tr->bs;
1755     uint8_t ID;
1756
1757     // get start code
1758     ID = bs->p_c[0];
1759
1760     /* Copy one byte */
1761     *bs->p_w++ = *bs->p_c++;
1762
1763     if (ID == 0x00) // pic header
1764     {
1765         tr->picture_coding_type = (bs->p_c[1] >> 3) & 0x7;
1766         bs->p_c[1] |= 0x7; bs->p_c[2] = 0xFF; bs->p_c[3] |= 0xF8; // vbv_delay is now 0xFFFF
1767
1768         memcpy(bs->p_w, bs->p_c, 4);
1769         bs->p_c += 4;
1770         bs->p_w += 4;
1771     }
1772     else if (ID == 0xB3) // seq header
1773     {
1774         tr->horizontal_size_value = (bs->p_c[0] << 4) | (bs->p_c[1] >> 4);
1775         tr->vertical_size_value = ((bs->p_c[1] & 0xF) << 8) | bs->p_c[2];
1776         if(!tr->horizontal_size_value || !tr->vertical_size_value )
1777         {
1778             return -1;
1779         }
1780
1781         memcpy(bs->p_w, bs->p_c, 8 );
1782         bs->p_c += 8;
1783         bs->p_w += 8;
1784     }
1785     else if (ID == 0xB5) // extension
1786     {
1787         if ((bs->p_c[0] >> 4) == 0x8) // pic coding ext
1788         {
1789             tr->f_code[0][0] = (bs->p_c[0] & 0xF) - 1;
1790             tr->f_code[0][1] = (bs->p_c[1] >> 4) - 1;
1791             tr->f_code[1][0] = (bs->p_c[1] & 0xF) - 1;
1792             tr->f_code[1][1] = (bs->p_c[2] >> 4) - 1;
1793
1794             /* tr->intra_dc_precision = (bs->p_c[2] >> 2) & 0x3; */
1795             tr->picture_structure = bs->p_c[2] & 0x3;
1796             tr->frame_pred_frame_dct = (bs->p_c[3] >> 6) & 0x1;
1797             tr->concealment_motion_vectors = (bs->p_c[3] >> 5) & 0x1;
1798             tr->q_scale_type = (bs->p_c[3] >> 4) & 0x1;
1799             tr->intra_vlc_format = (bs->p_c[3] >> 3) & 0x1;
1800             /* tr->alternate_scan = (bs->p_c[3] >> 2) & 0x1; */
1801
1802
1803             memcpy(bs->p_w, bs->p_c, 5);
1804             bs->p_c += 5;
1805             bs->p_w += 5;
1806         }
1807         else
1808         {
1809             *bs->p_w++ = *bs->p_c++;
1810         }
1811     }
1812     else if (ID == 0xB8) // gop header
1813     {
1814         memcpy(bs->p_w, bs->p_c, 4);
1815         bs->p_c += 4;
1816         bs->p_w += 4;
1817     }
1818     else if ((ID >= 0x01) && (ID <= 0xAF)) // slice
1819     {
1820         uint8_t *outTemp = bs->p_w, *inTemp = bs->p_c;
1821
1822         if( ( tr->picture_coding_type == B_TYPE && tr->quant_corr <  2.5f ) || // don't recompress if we're in advance!
1823             ( tr->picture_coding_type == P_TYPE && tr->quant_corr < -2.5f ) ||
1824             ( tr->picture_coding_type == I_TYPE && tr->quant_corr < -5.0f ) )
1825         {
1826             if( !tr->horizontal_size_value || !tr->vertical_size_value )
1827             {
1828                 return -1;
1829             }
1830
1831             // init bit buffer
1832             bs->i_bit_in_cache = 0; bs->i_bit_in = 0;
1833             bs->i_bit_out_cache = 0; bs->i_bit_out = BITS_IN_BUF;
1834
1835             // get 32 bits
1836             bs_refill( bs );
1837             bs_refill( bs );
1838             bs_refill( bs );
1839             bs_refill( bs );
1840
1841             // begin bit level recoding
1842             mpeg2_slice(tr, ID);
1843
1844             bs_flush_read( bs );
1845             bs_flush_write( bs );
1846             // end bit level recoding
1847
1848             /* Basic sanity checks --Meuuh */
1849             if (bs->p_c > bs->p_r || bs->p_w > bs->p_rw)
1850             {
1851                 return -1;
1852             }
1853
1854             /*LOGF("type: %s code: %02i in : %6i out : %6i diff : %6i fact: %2.2f\n",
1855             (picture_coding_type == I_TYPE ? "I_TYPE" : (picture_coding_type == P_TYPE ? "P_TYPE" : "B_TYPE")),
1856             ID,  bs->p_c - inTemp, bs->p_w - outTemp, (bs->p_w - outTemp) - (bs->p_c - inTemp), (float)(bs->p_c - inTemp) / (float)(bs->p_w - outTemp));*/
1857
1858             if (bs->p_w - outTemp > bs->p_c - inTemp) // yes that might happen, rarely
1859             {
1860                 /*LOGF("*** slice bigger than before !! (type: %s code: %i in : %i out : %i diff : %i)\n",
1861                 (picture_coding_type == I_TYPE ? "I_TYPE" : (picture_coding_type == P_TYPE ? "P_TYPE" : "B_TYPE")),
1862                 ID, bs->p_c - inTemp, bs->p_w - outTemp, (bs->p_w - outTemp) - (bs->p_c - inTemp));*/
1863
1864                 // in this case, we'll just use the original slice !
1865                 memcpy(outTemp, inTemp, bs->p_c - inTemp);
1866                 bs->p_w = outTemp + (bs->p_c - inTemp);
1867
1868                 // adjust bs->i_byte_out
1869                 bs->i_byte_out -= (bs->p_w - outTemp) - (bs->p_c - inTemp);
1870             }
1871         }
1872     }
1873     return 0;
1874 }
1875
1876 static void process_frame( sout_stream_t *p_stream,
1877                            sout_stream_id_t *id, sout_buffer_t *in, sout_buffer_t **out )
1878 {
1879     transrate_t *tr = &id->tr;
1880     bs_transrate_t *bs = &tr->bs;
1881
1882     sout_buffer_t       *p_out;
1883
1884     /* The output buffer can't be bigger than the input buffer. */
1885     p_out = sout_BufferNew( p_stream->p_sout, in->i_size );
1886
1887     p_out->i_length = in->i_length;
1888     p_out->i_dts    = in->i_dts;
1889     p_out->i_pts    = in->i_pts;
1890
1891     sout_BufferChain( out, p_out );
1892
1893     bs->p_rw = bs->p_ow = bs->p_w = p_out->p_buffer;
1894     bs->p_c = bs->p_r = in->p_buffer;
1895     bs->p_r += in->i_size + 4;
1896     bs->p_rw += in->i_size;
1897     *(in->p_buffer + in->i_size) = 0;
1898     *(in->p_buffer + in->i_size + 1) = 0;
1899     *(in->p_buffer + in->i_size + 2) = 1;
1900     *(in->p_buffer + in->i_size + 3) = 0;
1901     bs->i_byte_in += in->i_size;
1902
1903     for ( ; ; )
1904     {
1905         uint8_t *p_end = &in->p_buffer[in->i_size];
1906
1907         /* Search next start code */
1908         for( ;; )
1909         {
1910             if( bs->p_c < p_end - 3 && bs->p_c[0] == 0 && bs->p_c[1] == 0 && bs->p_c[2] == 1 )
1911             {
1912                 /* Next start code */
1913                 break;
1914             }
1915             else if( bs->p_c < p_end - 6 &&
1916                      bs->p_c[0] == 0 && bs->p_c[1] == 0 && bs->p_c[2] == 0 &&
1917                      bs->p_c[3] == 0 && bs->p_c[4] == 0 && bs->p_c[5] == 0 )
1918             {
1919                 /* remove stuffing (looking for 6 0x00 bytes) */
1920                 bs->p_c++;
1921             }
1922             else
1923             {
1924                 /* Copy */
1925                 *bs->p_w++ = *bs->p_c++;
1926             }
1927
1928             if( bs->p_c >= p_end)
1929             {
1930                 break;
1931             }
1932         }
1933
1934         if( bs->p_c >= p_end )
1935         {
1936             break;
1937         }
1938
1939         /* Copy the start code */
1940         memcpy(bs->p_w, bs->p_c, 3 );
1941         bs->p_c += 3;
1942         bs->p_w += 3;
1943
1944         if (do_next_start_code( tr ) )
1945         {
1946             /* Error */
1947             break;
1948         }
1949
1950         tr->quant_corr = (((bs->i_byte_in - (bs->p_r - 4 - bs->p_c)) / tr->fact_x) - (bs->i_byte_out + (bs->p_w - bs->p_ow))) / REACT_DELAY;
1951     }
1952
1953     bs->i_byte_out += bs->p_w - bs->p_ow;
1954     p_out->i_size = bs->p_w - bs->p_ow;
1955 }
1956
1957 static int transrate_video_process( sout_stream_t *p_stream,
1958                sout_stream_id_t *id, sout_buffer_t *in, sout_buffer_t **out )
1959 {
1960     transrate_t *tr = &id->tr;
1961     bs_transrate_t *bs = &tr->bs;
1962
1963     *out = NULL;
1964
1965     if ( in->i_flags & SOUT_BUFFER_FLAGS_GOP )
1966     {
1967         while ( id->p_current_buffer != NULL )
1968         {
1969             sout_buffer_t * p_next = id->p_current_buffer->p_next;
1970             if ( tr->fact_x == 1.0 )
1971             {
1972                 bs->i_byte_out += id->p_current_buffer->i_size;
1973                 id->p_current_buffer->p_next = NULL;
1974                 sout_BufferChain( out, id->p_current_buffer );
1975             }
1976             else
1977             {
1978                 process_frame( p_stream, id, id->p_current_buffer, out );
1979                 sout_BufferDelete(p_stream->p_sout, id->p_current_buffer);
1980             }
1981             id->p_current_buffer = p_next;
1982         }
1983
1984         if ( id->i_next_gop_duration )
1985         {
1986             mtime_t i_bitrate = (mtime_t)id->i_next_gop_size * 8000
1987                                     / (id->i_next_gop_duration / 1000);
1988             static mtime_t i_old_bitrate = 0;
1989             static mtime_t i_old_duration = 0;
1990             if (i_old_bitrate)
1991             {
1992                 msg_Dbg(p_stream, "bitrate = %lld -> %lld", i_old_bitrate,
1993                         (mtime_t)bs->i_byte_out * 8000 / (i_old_duration / 1000));
1994             }
1995             i_old_bitrate = i_bitrate;
1996             i_old_duration = id->i_next_gop_duration;
1997             if ( i_bitrate > p_stream->p_sys->i_vbitrate )
1998             {
1999                 tr->fact_x = (double)i_bitrate / p_stream->p_sys->i_vbitrate;
2000             }
2001             else
2002             {
2003                 tr->fact_x = 1.0;
2004             }
2005             msg_Dbg(p_stream, "new fact_x = %f", tr->fact_x);
2006
2007             id->p_current_buffer = id->p_next_gop;
2008             id->p_next_gop = NULL;
2009             id->i_next_gop_duration = 0;
2010             id->i_next_gop_size = 0;
2011             bs->i_byte_in = 0;
2012             bs->i_byte_out  = 0;
2013         }
2014     }
2015
2016     /* Store the buffer for the next GOP. */
2017     sout_BufferChain( &id->p_next_gop, in );
2018     id->i_next_gop_duration += in->i_length;
2019     id->i_next_gop_size += in->i_size;
2020
2021     if ( id->p_current_buffer != NULL )
2022     {
2023         sout_buffer_t * p_next = id->p_current_buffer->p_next;
2024         if ( tr->fact_x == 1.0 )
2025         {
2026             bs->i_byte_out += id->p_current_buffer->i_size;
2027             id->p_current_buffer->p_next = NULL;
2028             sout_BufferChain( out, id->p_current_buffer );
2029         }
2030         else
2031         {
2032             process_frame( p_stream, id, id->p_current_buffer, out );
2033             sout_BufferDelete(p_stream->p_sout, id->p_current_buffer);
2034         }
2035         id->p_current_buffer = p_next;
2036     }
2037
2038     return VLC_SUCCESS;
2039 }
2040