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