]> git.sesse.net Git - vlc/blob - modules/codec/dvbsub.c
macosx: fixed menubar appearance in fullscreen mode by partially reverting [46c93c9cc...
[vlc] / modules / codec / dvbsub.c
1 /*****************************************************************************
2  * dvbsub.c : DVB subtitles decoder
3  *            DVB subtitles encoder (developed for Anevia, www.anevia.com)
4  *****************************************************************************
5  * Copyright (C) 2003 ANEVIA
6  * Copyright (C) 2003-2005 the VideoLAN team
7  * $Id$
8  *
9  * Authors: Gildas Bazin <gbazin@videolan.org>
10  *          Damien LUCAS <damien.lucas@anevia.com>
11  *          Laurent Aimar <fenrir@via.ecp.fr>
12  *          Jean-Paul Saman <jpsaman #_at_# m2x dot nl>
13  *          Derk-Jan Hartman <hartman #at# videolan dot org>
14  *
15  * This program is free software; you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation; either version 2 of the License, or
18  * (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  * GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with this program; if not, write to the Free Software
27  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
28  *****************************************************************************/
29 /*****************************************************************************
30  * Preamble
31  *
32  * FIXME:
33  * DVB subtitles coded as strings of characters are not handled correctly.
34  * The character codes in the string should actually be indexes referring to a
35  * character table identified in the subtitle descriptor.
36  *
37  * The spec is quite vague in this area, but what is meant is perhaps that it
38  * refers to the character index in the codepage belonging to the language specified
39  * in the subtitle descriptor. Potentially it's designed for widechar
40  * (but not for UTF-*) codepages.
41  *****************************************************************************/
42 #ifdef HAVE_CONFIG_H
43 # include "config.h"
44 #endif
45
46 #include <vlc_common.h>
47 #include <vlc_plugin.h>
48 #include <vlc_vout.h>
49 #include <vlc_codec.h>
50 #include <vlc_sout.h>
51
52 #include "vlc_bits.h"
53
54 /* #define DEBUG_DVBSUB 1 */
55
56 #define POSX_TEXT N_("Decoding X coordinate")
57 #define POSX_LONGTEXT N_("X coordinate of the rendered subtitle")
58
59 #define POSY_TEXT N_("Decoding Y coordinate")
60 #define POSY_LONGTEXT N_("Y coordinate of the rendered subtitle")
61
62 #define POS_TEXT N_("Subpicture position")
63 #define POS_LONGTEXT N_( \
64   "You can enforce the subpicture position on the video " \
65   "(0=center, 1=left, 2=right, 4=top, 8=bottom, you can " \
66   "also use combinations of these values, e.g. 6=top-right).")
67
68 #define ENC_POSX_TEXT N_("Encoding X coordinate")
69 #define ENC_POSX_LONGTEXT N_("X coordinate of the encoded subtitle" )
70 #define ENC_POSY_TEXT N_("Encoding Y coordinate")
71 #define ENC_POSY_LONGTEXT N_("Y coordinate of the encoded subtitle" )
72
73 static const int pi_pos_values[] = { 0, 1, 2, 4, 8, 5, 6, 9, 10 };
74 static const char *const ppsz_pos_descriptions[] =
75 { N_("Center"), N_("Left"), N_("Right"), N_("Top"), N_("Bottom"),
76   N_("Top-Left"), N_("Top-Right"), N_("Bottom-Left"), N_("Bottom-Right") };
77
78 /*****************************************************************************
79  * Module descriptor.
80  *****************************************************************************/
81 static int  Open ( vlc_object_t * );
82 static void Close( vlc_object_t * );
83 static subpicture_t *Decode( decoder_t *, block_t ** );
84
85 static int OpenEncoder  ( vlc_object_t * );
86 static void CloseEncoder( vlc_object_t * );
87 static block_t *Encode  ( encoder_t *, subpicture_t * );
88
89 vlc_module_begin ()
90 #   define DVBSUB_CFG_PREFIX "dvbsub-"
91     set_description( N_("DVB subtitles decoder") )
92     set_shortname( N_("DVB subtitles") )
93     set_capability( "decoder", 50 )
94     set_category( CAT_INPUT )
95     set_subcategory( SUBCAT_INPUT_SCODEC )
96     set_callbacks( Open, Close )
97
98     add_integer( DVBSUB_CFG_PREFIX "position", 8, NULL, POS_TEXT, POS_LONGTEXT, true )
99         change_integer_list( pi_pos_values, ppsz_pos_descriptions, NULL )
100     add_integer( DVBSUB_CFG_PREFIX "x", -1, NULL, POSX_TEXT, POSX_LONGTEXT, false )
101     add_integer( DVBSUB_CFG_PREFIX "y", -1, NULL, POSY_TEXT, POSY_LONGTEXT, false )
102
103 #   define ENC_CFG_PREFIX "sout-dvbsub-"
104     add_submodule ()
105     set_description( N_("DVB subtitles encoder") )
106     set_capability( "encoder", 100 )
107     set_callbacks( OpenEncoder, CloseEncoder )
108
109     add_integer( ENC_CFG_PREFIX "x", -1, NULL, ENC_POSX_TEXT, ENC_POSX_LONGTEXT, false )
110     add_integer( ENC_CFG_PREFIX "y", -1, NULL, ENC_POSY_TEXT, ENC_POSY_LONGTEXT, false )
111     add_obsolete_integer( ENC_CFG_PREFIX "timeout" ) /* Suppressed since 0.8.5 */
112 vlc_module_end ()
113
114 static const char *const ppsz_enc_options[] = { "x", "y", NULL };
115
116 /****************************************************************************
117  * Local structures
118  ****************************************************************************
119  * Those structures refer closely to the ETSI 300 743 Object model
120  ****************************************************************************/
121
122 /* The object definition gives the position of the object in a region [7.2.5] */
123 typedef struct dvbsub_objectdef_s
124 {
125     int i_id;
126     int i_type;
127     int i_x;
128     int i_y;
129     int i_fg_pc;
130     int i_bg_pc;
131     char *psz_text; /* for string of characters objects */
132
133 } dvbsub_objectdef_t;
134
135 /* The entry in the palette CLUT */
136 typedef struct
137 {
138     uint8_t                 Y;
139     uint8_t                 Cr;
140     uint8_t                 Cb;
141     uint8_t                 T;
142
143 } dvbsub_color_t;
144
145 /* The displays dimensions [7.2.1] */
146 typedef struct dvbsub_display_s
147 {
148     uint8_t                 i_id;
149     uint8_t                 i_version;
150
151     int                     i_width;
152     int                     i_height;
153
154     bool              b_windowed;
155     int                     i_x;
156     int                     i_y;
157     int                     i_max_x;
158     int                     i_max_y;
159
160 } dvbsub_display_t;
161
162 /* [7.2.4] */
163 typedef struct dvbsub_clut_s
164 {
165     uint8_t                 i_id;
166     uint8_t                 i_version;
167     dvbsub_color_t          c_2b[4];
168     dvbsub_color_t          c_4b[16];
169     dvbsub_color_t          c_8b[256];
170
171     struct dvbsub_clut_s    *p_next;
172
173 } dvbsub_clut_t;
174
175 /* The Region is an aera on the image [7.2.3]
176  * with a list of the object definitions associated and a CLUT */
177 typedef struct dvbsub_region_s
178 {
179     int i_id;
180     int i_version;
181     int i_x;
182     int i_y;
183     int i_width;
184     int i_height;
185     int i_level_comp;
186     int i_depth;
187     int i_clut;
188
189     uint8_t *p_pixbuf;
190
191     int                    i_object_defs;
192     dvbsub_objectdef_t     *p_object_defs;
193
194     struct dvbsub_region_s *p_next;
195
196 } dvbsub_region_t;
197
198 /* The object definition gives the position of the object in a region */
199 typedef struct dvbsub_regiondef_s
200 {
201     int i_id;
202     int i_x;
203     int i_y;
204
205 } dvbsub_regiondef_t;
206
207 /* The page defines the list of regions [7.2.2] */
208 typedef struct
209 {
210     int i_id;
211     int i_timeout; /* in seconds */
212     int i_state;
213     int i_version;
214
215     int                i_region_defs;
216     dvbsub_regiondef_t *p_region_defs;
217
218 } dvbsub_page_t;
219
220 struct decoder_sys_t
221 {
222     bs_t            bs;
223
224     /* Decoder internal data */
225     int             i_id;
226     int             i_ancillary_id;
227     mtime_t         i_pts;
228
229     bool      b_absolute;
230     int             i_spu_position;
231     int             i_spu_x;
232     int             i_spu_y;
233
234     bool      b_page;
235     dvbsub_page_t   *p_page;
236     dvbsub_region_t *p_regions;
237     dvbsub_clut_t   *p_cluts;
238     dvbsub_display_t *p_display;
239     dvbsub_clut_t    default_clut;
240 };
241
242
243 /* List of different SEGMENT TYPES */
244 /* According to EN 300-743, table 2 */
245 #define DVBSUB_ST_PAGE_COMPOSITION      0x10
246 #define DVBSUB_ST_REGION_COMPOSITION    0x11
247 #define DVBSUB_ST_CLUT_DEFINITION       0x12
248 #define DVBSUB_ST_OBJECT_DATA           0x13
249 #define DVBSUB_ST_DISPLAY_DEFINITION    0x14
250 #define DVBSUB_ST_ENDOFDISPLAY          0x80
251 #define DVBSUB_ST_STUFFING              0xff
252 /* List of different OBJECT TYPES */
253 /* According to EN 300-743, table 6 */
254 #define DVBSUB_OT_BASIC_BITMAP          0x00
255 #define DVBSUB_OT_BASIC_CHAR            0x01
256 #define DVBSUB_OT_COMPOSITE_STRING      0x02
257 /* Pixel DATA TYPES */
258 /* According to EN 300-743, table 9 */
259 #define DVBSUB_DT_2BP_CODE_STRING       0x10
260 #define DVBSUB_DT_4BP_CODE_STRING       0x11
261 #define DVBSUB_DT_8BP_CODE_STRING       0x12
262 #define DVBSUB_DT_24_TABLE_DATA         0x20
263 #define DVBSUB_DT_28_TABLE_DATA         0x21
264 #define DVBSUB_DT_48_TABLE_DATA         0x22
265 #define DVBSUB_DT_END_LINE              0xf0
266 /* List of different Page Composition Segment state */
267 /* According to EN 300-743, 7.2.1 table 3 */
268 #define DVBSUB_PCS_STATE_ACQUISITION    0x01
269 #define DVBSUB_PCS_STATE_CHANGE         0x02
270
271 /*****************************************************************************
272  * Local prototypes
273  *****************************************************************************/
274 static void decode_segment( decoder_t *, bs_t * );
275 static void decode_page_composition( decoder_t *, bs_t * );
276 static void decode_region_composition( decoder_t *, bs_t * );
277 static void decode_object( decoder_t *, bs_t * );
278 static void decode_display_definition( decoder_t *, bs_t * );
279 static void decode_clut( decoder_t *, bs_t * );
280 static void free_all( decoder_t * );
281
282 static void default_clut_init( decoder_t * );
283
284 static subpicture_t *render( decoder_t * );
285
286 /*****************************************************************************
287  * Open: probe the decoder and return score
288  *****************************************************************************
289  * Tries to launch a decoder and return score so that the interface is able
290  * to chose.
291  *****************************************************************************/
292 static int Open( vlc_object_t *p_this )
293 {
294     decoder_t     *p_dec = (decoder_t *) p_this;
295     decoder_sys_t *p_sys;
296     vlc_value_t    val;
297     int i_posx, i_posy;
298
299     if( p_dec->fmt_in.i_codec != VLC_FOURCC('d','v','b','s') )
300     {
301         return VLC_EGENERIC;
302     }
303
304     p_dec->pf_decode_sub = Decode;
305     p_sys = p_dec->p_sys = malloc( sizeof(decoder_sys_t) );
306     if( !p_sys )
307         return VLC_ENOMEM;
308     memset( p_sys, 0, sizeof(decoder_sys_t) );
309
310     p_sys->i_pts          = (mtime_t) 0;
311     p_sys->i_id           = p_dec->fmt_in.subs.dvb.i_id & 0xFFFF;
312     p_sys->i_ancillary_id = p_dec->fmt_in.subs.dvb.i_id >> 16;
313
314     p_sys->p_regions      = NULL;
315     p_sys->p_cluts        = NULL;
316     p_sys->p_page         = NULL;
317     p_sys->p_display      = NULL;
318
319     var_Create( p_this, DVBSUB_CFG_PREFIX "position",
320                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
321     var_Get( p_this, DVBSUB_CFG_PREFIX "position", &val );
322     p_sys->i_spu_position = val.i_int;
323     var_Create( p_this, DVBSUB_CFG_PREFIX "x",
324                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
325     var_Get( p_this, DVBSUB_CFG_PREFIX "x", &val );
326     i_posx = val.i_int;
327     var_Create( p_this, DVBSUB_CFG_PREFIX "y",
328                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
329     var_Get( p_this, DVBSUB_CFG_PREFIX "y", &val );
330     i_posy = val.i_int;
331
332     /* Check if subpicture position was overridden */
333     p_sys->b_absolute = true;
334     p_sys->i_spu_x = p_sys->i_spu_y = 0;
335
336     if( ( i_posx >= 0 ) && ( i_posy >= 0 ) )
337     {
338         p_sys->b_absolute = true;
339         p_sys->i_spu_x = i_posx;
340         p_sys->i_spu_y = i_posy;
341     }
342
343     p_dec->fmt_out.i_cat = SPU_ES;
344     p_dec->fmt_out.i_codec = 0;
345
346     default_clut_init( p_dec );
347
348     return VLC_SUCCESS;
349 }
350
351 /*****************************************************************************
352  * Close:
353  *****************************************************************************/
354 static void Close( vlc_object_t *p_this )
355 {
356     decoder_t     *p_dec = (decoder_t*) p_this;
357     decoder_sys_t *p_sys = p_dec->p_sys;
358
359     var_Destroy( p_this, DVBSUB_CFG_PREFIX "x" );
360     var_Destroy( p_this, DVBSUB_CFG_PREFIX "y" );
361     var_Destroy( p_this, DVBSUB_CFG_PREFIX "position" );
362
363     free_all( p_dec );
364     free( p_sys );
365 }
366
367 /*****************************************************************************
368  * Decode:
369  *****************************************************************************/
370 static subpicture_t *Decode( decoder_t *p_dec, block_t **pp_block )
371 {
372     decoder_sys_t *p_sys = p_dec->p_sys;
373     block_t       *p_block;
374     subpicture_t  *p_spu = NULL;
375
376     if( ( pp_block == NULL ) || ( *pp_block == NULL ) ) return NULL;
377     p_block = *pp_block;
378     *pp_block = NULL;
379
380     p_sys->i_pts = p_block->i_pts;
381     if( p_sys->i_pts <= 0 )
382     {
383 #ifdef DEBUG_DVBSUB
384         /* Some DVB channels send stuffing segments in non-dated packets so
385          * don't complain too loudly. */
386         msg_Warn( p_dec, "non dated subtitle" );
387 #endif
388         block_Release( p_block );
389         return NULL;
390     }
391
392     bs_init( &p_sys->bs, p_block->p_buffer, p_block->i_buffer );
393
394     if( bs_read( &p_sys->bs, 8 ) != 0x20 ) /* Data identifier */
395     {
396         msg_Dbg( p_dec, "invalid data identifier" );
397         block_Release( p_block );
398         return NULL;
399     }
400
401     if( bs_read( &p_sys->bs, 8 ) ) /* Subtitle stream id */
402     {
403         msg_Dbg( p_dec, "invalid subtitle stream id" );
404         block_Release( p_block );
405         return NULL;
406     }
407
408 #ifdef DEBUG_DVBSUB
409     msg_Dbg( p_dec, "subtitle packet received: %"PRId64, p_sys->i_pts );
410 #endif
411
412     p_sys->b_page = false;
413     while( bs_show( &p_sys->bs, 8 ) == 0x0f ) /* Sync byte */
414     {
415         decode_segment( p_dec, &p_sys->bs );
416     }
417
418     if( bs_read( &p_sys->bs, 8 ) != 0xff ) /* End marker */
419     {
420         msg_Warn( p_dec, "end marker not found (corrupted subtitle ?)" );
421         block_Release( p_block );
422         return NULL;
423     }
424
425     /* Check if the page is to be displayed */
426     if( p_sys->p_page && p_sys->b_page )
427         p_spu = render( p_dec );
428
429     block_Release( p_block );
430
431     return p_spu;
432 }
433
434 /* following functions are local */
435
436 /*****************************************************************************
437  * default_clut_init: default clut as defined in EN 300-743 section 10
438  *****************************************************************************/
439 static void default_clut_init( decoder_t *p_dec )
440 {
441     decoder_sys_t *p_sys = p_dec->p_sys;
442     uint8_t i;
443
444 #define RGB_TO_Y(r, g, b) ((int16_t) 77 * r + 150 * g + 29 * b) / 256;
445 #define RGB_TO_U(r, g, b) ((int16_t) -44 * r - 87 * g + 131 * b) / 256;
446 #define RGB_TO_V(r, g, b) ((int16_t) 131 * r - 110 * g - 21 * b) / 256;
447
448     /* 4 entries CLUT */
449     for( i = 0; i < 4; i++ )
450     {
451         uint8_t R = 0, G = 0, B = 0, T = 0;
452
453         if( !(i & 0x2) && !(i & 0x1) ) T = 0xFF;
454         else if( !(i & 0x2) && (i & 0x1) ) R = G = B = 0xFF;
455         else if( (i & 0x2) && !(i & 0x1) ) R = G = B = 0;
456         else R = G = B = 0x7F;
457
458         p_sys->default_clut.c_2b[i].Y = RGB_TO_Y(R,G,B);
459         p_sys->default_clut.c_2b[i].Cb = RGB_TO_V(R,G,B);
460         p_sys->default_clut.c_2b[i].Cr = RGB_TO_U(R,G,B);
461         p_sys->default_clut.c_2b[i].T = T;
462     }
463
464     /* 16 entries CLUT */
465     for( i = 0; i < 16; i++ )
466     {
467         uint8_t R = 0, G = 0, B = 0, T = 0;
468
469         if( !(i & 0x8) )
470         {
471             if( !(i & 0x4) && !(i & 0x2) && !(i & 0x1) )
472             {
473                 T = 0xFF;
474             }
475             else
476             {
477                 R = (i & 0x1) ? 0xFF : 0;
478                 G = (i & 0x2) ? 0xFF : 0;
479                 B = (i & 0x4) ? 0xFF : 0;
480             }
481         }
482         else
483         {
484             R = (i & 0x1) ? 0x7F : 0;
485             G = (i & 0x2) ? 0x7F : 0;
486             B = (i & 0x4) ? 0x7F : 0;
487         }
488
489         p_sys->default_clut.c_4b[i].Y = RGB_TO_Y(R,G,B);
490         p_sys->default_clut.c_4b[i].Cr = RGB_TO_V(R,G,B);
491         p_sys->default_clut.c_4b[i].Cb = RGB_TO_U(R,G,B);
492         p_sys->default_clut.c_4b[i].T = T;
493     }
494
495     /* 256 entries CLUT */
496     memset( p_sys->default_clut.c_8b, 0xFF, 256 * sizeof(dvbsub_color_t) );
497 }
498
499 static void decode_segment( decoder_t *p_dec, bs_t *s )
500 {
501     decoder_sys_t *p_sys = p_dec->p_sys;
502     int i_type;
503     int i_page_id;
504     int i_size;
505
506     /* sync_byte (already checked) */
507     bs_skip( s, 8 );
508
509     /* segment type */
510     i_type = bs_read( s, 8 );
511
512     /* page id */
513     i_page_id = bs_read( s, 16 );
514
515     /* segment size */
516     i_size = bs_show( s, 16 );
517
518     if( ( i_page_id != p_sys->i_id ) &&
519         ( i_page_id != p_sys->i_ancillary_id ) )
520     {
521 #ifdef DEBUG_DVBSUB
522         msg_Dbg( p_dec, "subtitle skipped (page id: %i, %i)",
523                  i_page_id, p_sys->i_id );
524 #endif
525         bs_skip( s,  8 * ( 2 + i_size ) );
526         return;
527     }
528
529     if( ( p_sys->i_ancillary_id != p_sys->i_id ) &&
530         ( i_type == DVBSUB_ST_PAGE_COMPOSITION ) &&
531         ( i_page_id == p_sys->i_ancillary_id ) )
532     {
533 #ifdef DEBUG_DVBSUB
534         msg_Dbg( p_dec, "skipped invalid ancillary subtitle packet" );
535 #endif
536         bs_skip( s,  8 * ( 2 + i_size ) );
537         return;
538     }
539
540 #ifdef DEBUG_DVBSUB
541     if( i_page_id == p_sys->i_id )
542         msg_Dbg( p_dec, "segment (id: %i)", i_page_id );
543     else
544         msg_Dbg( p_dec, "ancillary segment (id: %i)", i_page_id );
545 #endif
546
547     switch( i_type )
548     {
549     case DVBSUB_ST_PAGE_COMPOSITION:
550 #ifdef DEBUG_DVBSUB
551         msg_Dbg( p_dec, "decode_page_composition" );
552 #endif
553         decode_page_composition( p_dec, s );
554         break;
555
556     case DVBSUB_ST_REGION_COMPOSITION:
557 #ifdef DEBUG_DVBSUB
558         msg_Dbg( p_dec, "decode_region_composition" );
559 #endif
560         decode_region_composition( p_dec, s );
561         break;
562
563     case DVBSUB_ST_CLUT_DEFINITION:
564 #ifdef DEBUG_DVBSUB
565         msg_Dbg( p_dec, "decode_clut" );
566 #endif
567         decode_clut( p_dec, s );
568         break;
569
570     case DVBSUB_ST_OBJECT_DATA:
571 #ifdef DEBUG_DVBSUB
572         msg_Dbg( p_dec, "decode_object" );
573 #endif
574         decode_object( p_dec, s );
575         break;
576
577     case DVBSUB_ST_DISPLAY_DEFINITION:
578 #ifdef DEBUG_DVBSUB
579         msg_Dbg( p_dec, "decode_display_definition" );
580 #endif
581         decode_display_definition( p_dec, s );
582         break;
583
584     case DVBSUB_ST_ENDOFDISPLAY:
585 #ifdef DEBUG_DVBSUB
586         msg_Dbg( p_dec, "end of display" );
587 #endif
588         bs_skip( s,  8 * ( 2 + i_size ) );
589         break;
590
591     case DVBSUB_ST_STUFFING:
592 #ifdef DEBUG_DVBSUB
593         msg_Dbg( p_dec, "skip stuffing" );
594 #endif
595         bs_skip( s,  8 * ( 2 + i_size ) );
596         break;
597
598     default:
599         msg_Warn( p_dec, "unsupported segment type: (%04x)", i_type );
600         bs_skip( s,  8 * ( 2 + i_size ) );
601         break;
602     }
603 }
604
605 static void decode_clut( decoder_t *p_dec, bs_t *s )
606 {
607     decoder_sys_t *p_sys = p_dec->p_sys;
608     uint16_t      i_segment_length;
609     uint16_t      i_processed_length;
610     dvbsub_clut_t *p_clut, *p_next;
611     int           i_id, i_version;
612
613     i_segment_length = bs_read( s, 16 );
614     i_id             = bs_read( s, 8 );
615     i_version        = bs_read( s, 4 );
616
617     /* Check if we already have this clut */
618     for( p_clut = p_sys->p_cluts; p_clut != NULL; p_clut = p_clut->p_next )
619     {
620         if( p_clut->i_id == i_id ) break;
621     }
622
623     /* Check version number */
624     if( p_clut && ( p_clut->i_version == i_version ) )
625     {
626         /* Nothing to do */
627         bs_skip( s, 8 * i_segment_length - 12 );
628         return;
629     }
630
631     if( !p_clut )
632     {
633 #ifdef DEBUG_DVBSUB
634         msg_Dbg( p_dec, "new clut: %i", i_id );
635 #endif
636         p_clut = malloc( sizeof( dvbsub_clut_t ) );
637         if( !p_clut )
638             return;
639         p_clut->p_next = p_sys->p_cluts;
640         p_sys->p_cluts = p_clut;
641     }
642
643     /* Initialize to default clut */
644     p_next = p_clut->p_next;
645     *p_clut = p_sys->default_clut;
646     p_clut->p_next = p_next;
647
648     /* We don't have this version of the CLUT: Parse it */
649     p_clut->i_version = i_version;
650     p_clut->i_id = i_id;
651     bs_skip( s, 4 ); /* Reserved bits */
652     i_processed_length = 2;
653     while( i_processed_length < i_segment_length )
654     {
655         uint8_t y, cb, cr, t;
656         uint8_t i_id;
657         uint8_t i_type;
658
659         i_id = bs_read( s, 8 );
660         i_type = bs_read( s, 3 );
661
662         bs_skip( s, 4 );
663
664         if( bs_read( s, 1 ) )
665         {
666             y  = bs_read( s, 8 );
667             cr = bs_read( s, 8 );
668             cb = bs_read( s, 8 );
669             t  = bs_read( s, 8 );
670             i_processed_length += 6;
671         }
672         else
673         {
674             y  = bs_read( s, 6 ) << 2;
675             cr = bs_read( s, 4 ) << 4;
676             cb = bs_read( s, 4 ) << 4;
677             t  = bs_read( s, 2 ) << 6;
678             i_processed_length += 4;
679         }
680
681         /* We are not entirely compliant here as full transparency is indicated
682          * with a luma value of zero, not a transparency value of 0xff
683          * (full transparency would actually be 0xff + 1). */
684         if( y == 0 )
685         {
686             cr = cb = 0;
687             t  = 0xff;
688         }
689
690         /* According to EN 300-743 section 7.2.3 note 1, type should
691          * not have more than 1 bit set to one, but some streams don't
692          * respect this note. */
693         if( ( i_type & 0x04 ) && ( i_id < 4 ) )
694         {
695             p_clut->c_2b[i_id].Y = y;
696             p_clut->c_2b[i_id].Cr = cr;
697             p_clut->c_2b[i_id].Cb = cb;
698             p_clut->c_2b[i_id].T = t;
699         }
700         if( ( i_type & 0x02 ) && ( i_id < 16 ) )
701         {
702             p_clut->c_4b[i_id].Y = y;
703             p_clut->c_4b[i_id].Cr = cr;
704             p_clut->c_4b[i_id].Cb = cb;
705             p_clut->c_4b[i_id].T = t;
706         }
707         if( i_type & 0x01 )
708         {
709             p_clut->c_8b[i_id].Y = y;
710             p_clut->c_8b[i_id].Cr = cr;
711             p_clut->c_8b[i_id].Cb = cb;
712             p_clut->c_8b[i_id].T = t;
713         }
714     }
715 }
716
717 static void decode_page_composition( decoder_t *p_dec, bs_t *s )
718 {
719     decoder_sys_t *p_sys = p_dec->p_sys;
720     int i_version, i_state, i_segment_length, i_timeout, i;
721
722     /* A page is composed by 0 or more region */
723     i_segment_length = bs_read( s, 16 );
724     i_timeout = bs_read( s, 8 );
725     i_version = bs_read( s, 4 );
726     i_state = bs_read( s, 2 );
727     bs_skip( s, 2 ); /* Reserved */
728
729     if( i_state == DVBSUB_PCS_STATE_CHANGE )
730     {
731         /* End of an epoch, reset decoder buffer */
732 #ifdef DEBUG_DVBSUB
733         msg_Dbg( p_dec, "page composition mode change" );
734 #endif
735         free_all( p_dec );
736     }
737     else if( !p_sys->p_page && ( i_state != DVBSUB_PCS_STATE_ACQUISITION ) &&
738              ( i_state != DVBSUB_PCS_STATE_CHANGE ) )
739     {
740         /* Not a full PCS, we need to wait for one */
741         msg_Dbg( p_dec, "didn't receive an acquisition page yet" );
742
743 #if 0
744         /* Try to start decoding even without an acquisition page */
745         bs_skip( s,  8 * (i_segment_length - 2) );
746         return;
747 #endif
748     }
749
750 #ifdef DEBUG_DVBSUB
751     if( i_state == DVBSUB_PCS_STATE_ACQUISITION )
752         msg_Dbg( p_dec, "acquisition page composition" );
753 #endif
754
755     /* Check version number */
756     if( p_sys->p_page && ( p_sys->p_page->i_version == i_version ) )
757     {
758         bs_skip( s,  8 * (i_segment_length - 2) );
759         return;
760     }
761     else if( p_sys->p_page )
762     {
763         if( p_sys->p_page->i_region_defs )
764             free( p_sys->p_page->p_region_defs );
765         p_sys->p_page->p_region_defs = NULL;
766         p_sys->p_page->i_region_defs = 0;
767     }
768
769     if( !p_sys->p_page )
770     {
771 #ifdef DEBUG_DVBSUB
772         msg_Dbg( p_dec, "new page" );
773 #endif
774         /* Allocate a new page */
775         p_sys->p_page = malloc( sizeof(dvbsub_page_t) );
776         if( !p_sys->p_page )
777             return;
778     }
779
780     p_sys->p_page->i_version = i_version;
781     p_sys->p_page->i_timeout = i_timeout;
782     p_sys->b_page = true;
783
784     /* Number of regions */
785     p_sys->p_page->i_region_defs = (i_segment_length - 2) / 6;
786
787     if( p_sys->p_page->i_region_defs == 0 ) return;
788
789     p_sys->p_page->p_region_defs =
790         malloc( p_sys->p_page->i_region_defs * sizeof(dvbsub_region_t) );
791     if( p_sys->p_page->p_region_defs )
792     {
793         for( i = 0; i < p_sys->p_page->i_region_defs; i++ )
794         {
795             p_sys->p_page->p_region_defs[i].i_id = bs_read( s, 8 );
796             bs_skip( s, 8 ); /* Reserved */
797             p_sys->p_page->p_region_defs[i].i_x = bs_read( s, 16 );
798             p_sys->p_page->p_region_defs[i].i_y = bs_read( s, 16 );
799
800 #ifdef DEBUG_DVBSUB
801             msg_Dbg( p_dec, "page_composition, region %i (%i,%i)",
802                     i, p_sys->p_page->p_region_defs[i].i_x,
803                     p_sys->p_page->p_region_defs[i].i_y );
804 #endif
805         }
806     }
807 }
808
809 static void decode_region_composition( decoder_t *p_dec, bs_t *s )
810 {
811     decoder_sys_t *p_sys = p_dec->p_sys;
812     dvbsub_region_t *p_region, **pp_region = &p_sys->p_regions;
813     int i_segment_length, i_processed_length, i_id, i_version;
814     int i_width, i_height, i_level_comp, i_depth, i_clut;
815     int i_8_bg, i_4_bg, i_2_bg;
816     bool b_fill;
817
818     i_segment_length = bs_read( s, 16 );
819     i_id = bs_read( s, 8 );
820     i_version = bs_read( s, 4 );
821
822     /* Check if we already have this region */
823     for( p_region = p_sys->p_regions; p_region != NULL;
824          p_region = p_region->p_next )
825     {
826         pp_region = &p_region->p_next;
827         if( p_region->i_id == i_id ) break;
828     }
829
830     /* Check version number */
831     if( p_region && ( p_region->i_version == i_version ) )
832     {
833         bs_skip( s, 8 * (i_segment_length - 1) - 4 );
834         return;
835     }
836
837     if( !p_region )
838     {
839 #ifdef DEBUG_DVBSUB
840         msg_Dbg( p_dec, "new region: %i", i_id );
841 #endif
842         p_region = *pp_region = malloc( sizeof(dvbsub_region_t) );
843         if( !p_region )
844             return;
845         memset( p_region, 0, sizeof(dvbsub_region_t) );
846         p_region->p_object_defs = NULL;
847         p_region->p_pixbuf = NULL;
848         p_region->p_next = NULL;
849     }
850
851     /* Region attributes */
852     p_region->i_id = i_id;
853     p_region->i_version = i_version;
854     b_fill = bs_read( s, 1 );
855     bs_skip( s, 3 ); /* Reserved */
856
857     i_width = bs_read( s, 16 );
858     i_height = bs_read( s, 16 );
859 #ifdef DEBUG_DVBSUB
860     msg_Dbg( p_dec, " width=%d height=%d", i_width, i_height );
861 #endif
862     i_level_comp = bs_read( s, 3 );
863     i_depth = bs_read( s, 3 );
864     bs_skip( s, 2 ); /* Reserved */
865     i_clut = bs_read( s, 8 );
866
867     i_8_bg = bs_read( s, 8 );
868     i_4_bg = bs_read( s, 4 );
869     i_2_bg = bs_read( s, 2 );
870     bs_skip( s, 2 ); /* Reserved */
871
872     /* Free old object defs */
873     while( p_region->i_object_defs )
874         free( p_region->p_object_defs[--p_region->i_object_defs].psz_text );
875
876     free( p_region->p_object_defs );
877     p_region->p_object_defs = NULL;
878
879     /* Extra sanity checks */
880     if( ( p_region->i_width != i_width ) ||
881         ( p_region->i_height != i_height ) )
882     {
883         if( p_region->p_pixbuf )
884         {
885             msg_Dbg( p_dec, "region size changed (%dx%d->%dx%d)",
886                      p_region->i_width, p_region->i_height, i_width, i_height );
887             free( p_region->p_pixbuf );
888         }
889
890         p_region->p_pixbuf = malloc( i_height * i_width );
891         p_region->i_depth = 0;
892         b_fill = true;
893     }
894     if( p_region->i_depth &&
895         ( ( p_region->i_depth != i_depth ) ||
896           ( p_region->i_level_comp != i_level_comp ) ||
897           ( p_region->i_clut != i_clut) ) )
898     {
899         msg_Dbg( p_dec, "region parameters changed (not allowed)" );
900     }
901
902     /* Erase background of region */
903     if( b_fill )
904     {
905         int i_background = ( p_region->i_depth == 1 ) ? i_2_bg :
906             ( ( p_region->i_depth == 2 ) ? i_4_bg : i_8_bg );
907         memset( p_region->p_pixbuf, i_background, i_width * i_height );
908     }
909
910     p_region->i_width = i_width;
911     p_region->i_height = i_height;
912     p_region->i_level_comp = i_level_comp;
913     p_region->i_depth = i_depth;
914     p_region->i_clut = i_clut;
915
916     /* List of objects in the region */
917     i_processed_length = 10;
918     while( i_processed_length < i_segment_length )
919     {
920         dvbsub_objectdef_t *p_obj;
921
922         /* We create a new object */
923         p_region->i_object_defs++;
924         p_region->p_object_defs =
925             realloc( p_region->p_object_defs,
926                      sizeof(dvbsub_objectdef_t) * p_region->i_object_defs );
927
928         /* We parse object properties */
929         p_obj = &p_region->p_object_defs[p_region->i_object_defs - 1];
930         p_obj->i_id         = bs_read( s, 16 );
931         p_obj->i_type       = bs_read( s, 2 );
932         bs_skip( s, 2 ); /* Provider */
933         p_obj->i_x          = bs_read( s, 12 );
934         bs_skip( s, 4 ); /* Reserved */
935         p_obj->i_y          = bs_read( s, 12 );
936         p_obj->psz_text     = NULL;
937
938         i_processed_length += 6;
939
940         if( ( p_obj->i_type == DVBSUB_OT_BASIC_CHAR ) ||
941             ( p_obj->i_type == DVBSUB_OT_COMPOSITE_STRING ) )
942         {
943             p_obj->i_fg_pc =  bs_read( s, 8 );
944             p_obj->i_bg_pc =  bs_read( s, 8 );
945             i_processed_length += 2;
946         }
947     }
948 }
949
950 /* ETSI 300 743 [7.2.1] */
951 static void decode_display_definition( decoder_t *p_dec, bs_t *s )
952 {
953     decoder_sys_t *p_sys = p_dec->p_sys;
954     uint16_t      i_segment_length;
955     uint16_t      i_processed_length = 40;
956     dvbsub_display_t *p_display;
957     dvbsub_display_t *p_old = p_sys->p_display;
958     int           i_version;
959
960     i_segment_length = bs_read( s, 16 );
961     i_version        = bs_read( s, 4 );
962
963     /* Check version number */
964     if( p_old && ( p_old->i_version == i_version ) )
965     {
966         /* The definition did not change */
967         bs_skip( s, 8*i_segment_length - 4 );
968         return;
969     }
970
971 #ifdef DEBUG_DVBSUB
972     msg_Dbg( p_dec, "new display definition: %i", i_version );
973 #endif
974     p_display = malloc( sizeof(dvbsub_display_t) );
975     if( p_display )
976     {
977         /* We don't have this version of the display definition: Parse it */
978         p_display->i_version = i_version;
979         p_display->b_windowed = bs_read( s, 1 );
980         bs_skip( s, 3 ); /* Reserved bits */
981         p_display->i_width = bs_read( s, 16 )+1;
982         p_display->i_height = bs_read( s, 16 )+1;
983
984         if( p_display->b_windowed )
985         {
986 #ifdef DEBUG_DVBSUB
987             msg_Dbg( p_dec, "display definition with offsets (windowed)" );
988 #endif
989             /* Coordinates are measured from the top left corner */
990             p_display->i_x     = bs_read( s, 16 );
991             p_display->i_max_x = bs_read( s, 16 );
992             p_display->i_y     = bs_read( s, 16 );
993             p_display->i_max_y = bs_read( s, 16 );
994             i_processed_length += 64;
995         }
996     }
997
998     p_sys->p_display = p_display;
999     free( p_old );
1000
1001     if( i_processed_length != i_segment_length*8 )
1002     {
1003         msg_Err( p_dec, "processed length %d != segment length %d",
1004                  i_processed_length, i_segment_length );
1005     }
1006
1007 #ifdef DEBUG_DVBSUB
1008     msg_Dbg( p_dec, "version: %d, width: %d, height: %d",
1009              p_display->i_version, p_display->i_width, p_display->i_height );
1010     if( p_display->b_windowed )
1011         msg_Dbg( p_dec, "xmin: %d, xmax: %d, ymin: %d, ymax: %d",
1012                  p_display->i_x, p_display->i_max_x, p_display->i_y, p_display->i_max_y );
1013 #endif
1014 }
1015
1016 static void dvbsub_render_pdata( decoder_t *, dvbsub_region_t *, int, int,
1017                                  uint8_t *, int );
1018 static void dvbsub_pdata2bpp( bs_t *, uint8_t *, int, int * );
1019 static void dvbsub_pdata4bpp( bs_t *, uint8_t *, int, int * );
1020 static void dvbsub_pdata8bpp( bs_t *, uint8_t *, int, int * );
1021
1022 static void decode_object( decoder_t *p_dec, bs_t *s )
1023 {
1024     decoder_sys_t *p_sys = p_dec->p_sys;
1025     dvbsub_region_t *p_region;
1026     int i_segment_length, i_coding_method, i_version, i_id, i;
1027     bool b_non_modify_color;
1028
1029     /* ETSI 300-743 paragraph 7.2.4
1030      * sync_byte, segment_type and page_id have already been processed.
1031      */
1032     i_segment_length = bs_read( s, 16 );
1033     i_id             = bs_read( s, 16 );
1034     i_version        = bs_read( s, 4 );
1035     i_coding_method  = bs_read( s, 2 );
1036
1037     if( i_coding_method > 1 )
1038     {
1039         msg_Dbg( p_dec, "unknown DVB subtitling coding %d is not handled!", i_coding_method );
1040         bs_skip( s, 8 * (i_segment_length - 2) - 6 );
1041         return;
1042     }
1043
1044     /* Check if the object needs to be rendered in at least one
1045      * of the regions */
1046     for( p_region = p_sys->p_regions; p_region != NULL;
1047          p_region = p_region->p_next )
1048     {
1049         for( i = 0; i < p_region->i_object_defs; i++ )
1050             if( p_region->p_object_defs[i].i_id == i_id ) break;
1051
1052         if( i != p_region->i_object_defs ) break;
1053     }
1054     if( !p_region )
1055     {
1056         bs_skip( s, 8 * (i_segment_length - 2) - 6 );
1057         return;
1058     }
1059
1060 #ifdef DEBUG_DVBSUB
1061     msg_Dbg( p_dec, "new object: %i", i_id );
1062 #endif
1063
1064     b_non_modify_color = bs_read( s, 1 );
1065     bs_skip( s, 1 ); /* Reserved */
1066
1067     if( i_coding_method == 0x00 )
1068     {
1069         int i_topfield, i_bottomfield;
1070         uint8_t *p_topfield, *p_bottomfield;
1071
1072         i_topfield    = bs_read( s, 16 );
1073         i_bottomfield = bs_read( s, 16 );
1074         p_topfield    = s->p_start + bs_pos( s ) / 8;
1075         p_bottomfield = p_topfield + i_topfield;
1076
1077         bs_skip( s, 8 * (i_segment_length - 7) );
1078
1079         /* Sanity check */
1080         if( ( i_segment_length < ( i_topfield + i_bottomfield + 7 ) ) ||
1081             ( ( p_topfield + i_topfield + i_bottomfield ) > s->p_end ) )
1082         {
1083             msg_Dbg( p_dec, "corrupted object data" );
1084             return;
1085         }
1086
1087         for( p_region = p_sys->p_regions; p_region != NULL;
1088              p_region = p_region->p_next )
1089         {
1090             for( i = 0; i < p_region->i_object_defs; i++ )
1091             {
1092                 if( p_region->p_object_defs[i].i_id != i_id ) continue;
1093
1094                 dvbsub_render_pdata( p_dec, p_region,
1095                                      p_region->p_object_defs[i].i_x,
1096                                      p_region->p_object_defs[i].i_y,
1097                                      p_topfield, i_topfield );
1098
1099                 if( i_bottomfield )
1100                 {
1101                     dvbsub_render_pdata( p_dec, p_region,
1102                                          p_region->p_object_defs[i].i_x,
1103                                          p_region->p_object_defs[i].i_y + 1,
1104                                          p_bottomfield, i_bottomfield );
1105                 }
1106                 else
1107                 {
1108                     /* Duplicate the top field */
1109                     dvbsub_render_pdata( p_dec, p_region,
1110                                          p_region->p_object_defs[i].i_x,
1111                                          p_region->p_object_defs[i].i_y + 1,
1112                                          p_topfield, i_topfield );
1113                 }
1114             }
1115         }
1116     }
1117     else
1118     {
1119         /* DVB subtitling as characters */
1120         int i_number_of_codes = bs_read( s, 8 );
1121         uint8_t* p_start = s->p_start + bs_pos( s ) / 8;
1122
1123         /* Sanity check */
1124         if( ( i_segment_length < ( i_number_of_codes*2 + 4 ) ) ||
1125             ( ( p_start + i_number_of_codes*2 ) > s->p_end ) )
1126         {
1127             msg_Dbg( p_dec, "corrupted object data" );
1128             return;
1129         }
1130
1131         for( p_region = p_sys->p_regions; p_region != NULL;
1132              p_region = p_region->p_next )
1133         {
1134             for( i = 0; i < p_region->i_object_defs; i++ )
1135             {
1136                 int j;
1137
1138                 if( p_region->p_object_defs[i].i_id != i_id ) continue;
1139
1140                 p_region->p_object_defs[i].psz_text =
1141                     realloc( p_region->p_object_defs[i].psz_text,
1142                              i_number_of_codes + 1 );
1143
1144                 /* FIXME 16bits -> char ??? See Preamble */
1145                 for( j = 0; j < i_number_of_codes; j++ )
1146                 {
1147                     p_region->p_object_defs[i].psz_text[j] = (char)(bs_read( s, 16 ) & 0xFF);
1148                 }
1149                 /* Null terminate the string */
1150                 p_region->p_object_defs[i].psz_text[j] = 0;
1151             }
1152         }
1153     }
1154
1155 #ifdef DEBUG_DVBSUB
1156     msg_Dbg( p_dec, "end object: %i", i_id );
1157 #endif
1158 }
1159
1160 static void dvbsub_render_pdata( decoder_t *p_dec, dvbsub_region_t *p_region,
1161                                  int i_x, int i_y,
1162                                  uint8_t *p_field, int i_field )
1163 {
1164     uint8_t *p_pixbuf;
1165     int i_offset = 0;
1166     bs_t bs;
1167
1168     /* Sanity check */
1169     if( !p_region->p_pixbuf )
1170     {
1171         msg_Err( p_dec, "region %i has no pixel buffer!", p_region->i_id );
1172         return;
1173     }
1174     if( i_y < 0 || i_x < 0 || i_y >= p_region->i_height ||
1175         i_x >= p_region->i_width )
1176     {
1177         msg_Dbg( p_dec, "invalid offset (%i,%i)", i_x, i_y );
1178         return;
1179     }
1180
1181     p_pixbuf = p_region->p_pixbuf + i_y * p_region->i_width;
1182     bs_init( &bs, p_field, i_field );
1183
1184     while( !bs_eof( &bs ) )
1185     {
1186         /* Sanity check */
1187         if( i_y >= p_region->i_height ) return;
1188
1189         switch( bs_read( &bs, 8 ) )
1190         {
1191         case 0x10:
1192             dvbsub_pdata2bpp( &bs, p_pixbuf + i_x, p_region->i_width - i_x,
1193                               &i_offset );
1194             break;
1195
1196         case 0x11:
1197             dvbsub_pdata4bpp( &bs, p_pixbuf + i_x, p_region->i_width - i_x,
1198                               &i_offset );
1199             break;
1200
1201         case 0x12:
1202             dvbsub_pdata8bpp( &bs, p_pixbuf + i_x, p_region->i_width - i_x,
1203                               &i_offset );
1204             break;
1205
1206         case 0x20:
1207         case 0x21:
1208         case 0x22:
1209             /* We don't use map tables */
1210             break;
1211
1212         case 0xf0: /* End of line code */
1213             p_pixbuf += 2*p_region->i_width;
1214             i_offset = 0; i_y += 2;
1215             break;
1216         }
1217     }
1218 }
1219
1220 static void dvbsub_pdata2bpp( bs_t *s, uint8_t *p, int i_width, int *pi_off )
1221 {
1222     bool b_stop = false;
1223
1224     while( !b_stop && !bs_eof( s ) )
1225     {
1226         int i_count = 0, i_color = 0;
1227
1228         i_color = bs_read( s, 2 );
1229         if( i_color != 0x00 )
1230         {
1231             i_count = 1;
1232         }
1233         else
1234         {
1235             if( bs_read( s, 1 ) == 0x01 )         // Switch1
1236             {
1237                 i_count = 3 + bs_read( s, 3 );
1238                 i_color = bs_read( s, 2 );
1239             }
1240             else
1241             {
1242                 if( bs_read( s, 1 ) == 0x00 )     //Switch2
1243                 {
1244                     switch( bs_read( s, 2 ) )     //Switch3
1245                     {
1246                     case 0x00:
1247                         b_stop = true;
1248                         break;
1249                     case 0x01:
1250                         i_count = 2;
1251                         break;
1252                     case 0x02:
1253                         i_count =  12 + bs_read( s, 4 );
1254                         i_color = bs_read( s, 2 );
1255                         break;
1256                     case 0x03:
1257                         i_count =  29 + bs_read( s, 8 );
1258                         i_color = bs_read( s, 2 );
1259                         break;
1260                     default:
1261                         break;
1262                     }
1263                 }
1264                 else
1265                 {
1266                     /* 1 pixel color 0 */
1267                     i_count = 1;
1268                 }
1269             }
1270         }
1271
1272         if( !i_count ) continue;
1273
1274         /* Sanity check */
1275         if( ( i_count + *pi_off ) > i_width ) break;
1276
1277         if( i_count == 1 ) p[*pi_off] = i_color;
1278         else memset( ( p + *pi_off ), i_color, i_count );
1279
1280         (*pi_off) += i_count;
1281     }
1282
1283     bs_align( s );
1284 }
1285
1286 static void dvbsub_pdata4bpp( bs_t *s, uint8_t *p, int i_width, int *pi_off )
1287 {
1288     bool b_stop = false;
1289
1290     while( !b_stop && !bs_eof( s ) )
1291     {
1292         int i_count = 0, i_color = 0;
1293
1294         i_color = bs_read( s, 4 );
1295         if( i_color != 0x00 )
1296         {
1297             /* Add 1 pixel */
1298             i_count = 1;
1299         }
1300         else
1301         {
1302             if( bs_read( s, 1 ) == 0x00 )           // Switch1
1303             {
1304                 if( bs_show( s, 3 ) != 0x00 )
1305                 {
1306                     i_count = 2 + bs_read( s, 3 );
1307                 }
1308                 else
1309                 {
1310                     bs_skip( s, 3 );
1311                     b_stop = true;
1312                 }
1313             }
1314             else
1315             {
1316                 if( bs_read( s, 1 ) == 0x00)        //Switch2
1317                 {
1318                     i_count =  4 + bs_read( s, 2 );
1319                     i_color = bs_read( s, 4 );
1320                 }
1321                 else
1322                 {
1323                     switch ( bs_read( s, 2 ) )     //Switch3
1324                     {
1325                     case 0x0:
1326                         i_count = 1;
1327                         break;
1328                     case 0x1:
1329                         i_count = 2;
1330                         break;
1331                     case 0x2:
1332                         i_count = 9 + bs_read( s, 4 );
1333                         i_color = bs_read( s, 4 );
1334                         break;
1335                     case 0x3:
1336                         i_count= 25 + bs_read( s, 8 );
1337                         i_color = bs_read( s, 4 );
1338                         break;
1339                     }
1340                 }
1341             }
1342         }
1343
1344         if( !i_count ) continue;
1345
1346         /* Sanity check */
1347         if( ( i_count + *pi_off ) > i_width ) break;
1348
1349         if( i_count == 1 ) p[*pi_off] = i_color;
1350         else memset( ( p + *pi_off ), i_color, i_count );
1351
1352         (*pi_off) += i_count;
1353     }
1354
1355     bs_align( s );
1356 }
1357
1358 static void dvbsub_pdata8bpp( bs_t *s, uint8_t *p, int i_width, int *pi_off )
1359 {
1360     bool b_stop = false;
1361
1362     while( !b_stop && !bs_eof( s ) )
1363     {
1364         int i_count = 0, i_color = 0;
1365
1366         i_color = bs_read( s, 8 );
1367         if( i_color != 0x00 )
1368         {
1369             /* Add 1 pixel */
1370             i_count = 1;
1371         }
1372         else
1373         {
1374             if( bs_read( s, 1 ) == 0x00 )           // Switch1
1375             {
1376                 if( bs_show( s, 7 ) != 0x00 )
1377                 {
1378                     i_count = bs_read( s, 7 );
1379                 }
1380                 else
1381                 {
1382                     bs_skip( s, 7 );
1383                     b_stop = true;
1384                 }
1385             }
1386             else
1387             {
1388                 i_count = bs_read( s, 7 );
1389                 i_color = bs_read( s, 8 );
1390             }
1391         }
1392
1393         if( !i_count ) continue;
1394
1395         /* Sanity check */
1396         if( ( i_count + *pi_off ) > i_width ) break;
1397
1398         if( i_count == 1 ) p[*pi_off] = i_color;
1399         else memset( ( p + *pi_off ), i_color, i_count );
1400
1401         (*pi_off) += i_count;
1402     }
1403
1404     bs_align( s );
1405 }
1406
1407 static void free_all( decoder_t *p_dec )
1408 {
1409     decoder_sys_t *p_sys = p_dec->p_sys;
1410     dvbsub_region_t *p_reg, *p_reg_next;
1411     dvbsub_clut_t *p_clut, *p_clut_next;
1412
1413     free( p_sys->p_display );
1414
1415     for( p_clut = p_sys->p_cluts; p_clut != NULL; p_clut = p_clut_next )
1416     {
1417         p_clut_next = p_clut->p_next;
1418         free( p_clut );
1419     }
1420     p_sys->p_cluts = NULL;
1421
1422     for( p_reg = p_sys->p_regions; p_reg != NULL; p_reg = p_reg_next )
1423     {
1424         int i;
1425
1426         p_reg_next = p_reg->p_next;
1427         for( i = 0; i < p_reg->i_object_defs; i++ )
1428             free( p_reg->p_object_defs[i].psz_text );
1429         if( p_reg->i_object_defs ) free( p_reg->p_object_defs );
1430         free( p_reg->p_pixbuf );
1431         free( p_reg );
1432     }
1433     p_sys->p_regions = NULL;
1434
1435     if( p_sys->p_page )
1436     {
1437         if( p_sys->p_page->i_region_defs )
1438             free( p_sys->p_page->p_region_defs );
1439         free( p_sys->p_page );
1440     }
1441     p_sys->p_page = NULL;
1442 }
1443
1444 static subpicture_t *render( decoder_t *p_dec )
1445 {
1446     decoder_sys_t *p_sys = p_dec->p_sys;
1447     subpicture_t *p_spu;
1448     subpicture_region_t **pp_spu_region;
1449     int i, j, i_timeout = 0;
1450     int i_base_x;
1451     int i_base_y;
1452
1453     /* Allocate the subpicture internal data. */
1454     p_spu = decoder_NewSubpicture( p_dec );
1455     if( !p_spu )
1456         return NULL;
1457
1458     p_spu->b_absolute = p_sys->b_absolute;
1459     /* Set the pf_render callback */
1460     p_spu->i_start = (mtime_t) p_sys->i_pts;
1461     //p_spu->i_stop = (mtime_t) 0;
1462     p_spu->b_ephemer = true;
1463     //p_spu->b_fade = true;
1464     //p_spu->i_stop = p_spu->i_start + (mtime_t) (i_timeout * 1000000);
1465
1466     /* Correct positioning of SPU */
1467     i_base_x = p_sys->i_spu_x;
1468     i_base_y = p_sys->i_spu_y;
1469     p_spu->i_original_picture_width = 720;
1470     p_spu->i_original_picture_height = 576;
1471
1472     if( p_sys->p_display )
1473     {
1474         p_spu->i_original_picture_width = p_sys->p_display->i_width;
1475         p_spu->i_original_picture_height = p_sys->p_display->i_height;
1476
1477         if( p_sys->p_display->b_windowed )
1478         {
1479             /* TODO: check that this actually works */
1480             p_spu->i_original_picture_width = p_sys->p_display->i_max_x - p_sys->p_display->i_x;
1481             p_spu->i_original_picture_height = p_sys->p_display->i_max_y - p_sys->p_display->i_y;
1482             i_base_x += p_sys->p_display->i_x;
1483             i_base_y += p_sys->p_display->i_y;
1484         }
1485     }
1486
1487     pp_spu_region = &p_spu->p_region;
1488
1489     /* Loop on region definitions */
1490 #ifdef DEBUG_DVBSUB
1491     if( p_sys->p_page )
1492         msg_Dbg( p_dec, "rendering %i regions", p_sys->p_page->i_region_defs );
1493 #endif
1494
1495     for( i = 0; p_sys->p_page && ( i < p_sys->p_page->i_region_defs ); i++ )
1496     {
1497         dvbsub_region_t     *p_region;
1498         dvbsub_regiondef_t  *p_regiondef;
1499         dvbsub_clut_t       *p_clut;
1500         dvbsub_color_t      *p_color;
1501         subpicture_region_t *p_spu_region;
1502         uint8_t *p_src, *p_dst;
1503         video_format_t fmt;
1504         video_palette_t palette;
1505         int i_pitch;
1506
1507         i_timeout = p_sys->p_page->i_timeout;
1508
1509         p_regiondef = &p_sys->p_page->p_region_defs[i];
1510
1511 #ifdef DEBUG_DVBSUB
1512         msg_Dbg( p_dec, "rendering region %i (%i,%i)", i,
1513                  p_regiondef->i_x, p_regiondef->i_y );
1514 #endif
1515
1516         /* Find associated region */
1517         for( p_region = p_sys->p_regions; p_region != NULL;
1518              p_region = p_region->p_next )
1519         {
1520             if( p_regiondef->i_id == p_region->i_id ) break;
1521         }
1522
1523         if( !p_region )
1524         {
1525             msg_Dbg( p_dec, "region %i not found", p_regiondef->i_id );
1526             continue;
1527         }
1528
1529         /* Find associated CLUT */
1530         for( p_clut = p_sys->p_cluts; p_clut != NULL; p_clut = p_clut->p_next )
1531         {
1532             if( p_region->i_clut == p_clut->i_id ) break;
1533         }
1534         if( !p_clut )
1535         {
1536             msg_Dbg( p_dec, "clut %i not found", p_region->i_clut );
1537             continue;
1538         }
1539
1540         /* FIXME: don't create a subpicture region with VLC_FOURCC YUVP 
1541          * when it actually is a TEXT region */
1542
1543         /* Create new SPU region */
1544         memset( &fmt, 0, sizeof(video_format_t) );
1545         fmt.i_chroma = VLC_FOURCC('Y','U','V','P');
1546         fmt.i_aspect = 0; /* 0 means use aspect ratio of background video */
1547         fmt.i_width = fmt.i_visible_width = p_region->i_width;
1548         fmt.i_height = fmt.i_visible_height = p_region->i_height;
1549         fmt.i_x_offset = fmt.i_y_offset = 0;
1550         fmt.p_palette = &palette;
1551         fmt.p_palette->i_entries = ( p_region->i_depth == 1 ) ? 4 :
1552             ( ( p_region->i_depth == 2 ) ? 16 : 256 );
1553         p_color = ( p_region->i_depth == 1 ) ? p_clut->c_2b :
1554             ( ( p_region->i_depth == 2 ) ? p_clut->c_4b : p_clut->c_8b );
1555         for( j = 0; j < fmt.p_palette->i_entries; j++ )
1556         {
1557             fmt.p_palette->palette[j][0] = p_color[j].Y;
1558             fmt.p_palette->palette[j][1] = p_color[j].Cb; /* U == Cb */
1559             fmt.p_palette->palette[j][2] = p_color[j].Cr; /* V == Cr */
1560             fmt.p_palette->palette[j][3] = 0xff - p_color[j].T;
1561         }
1562
1563         p_spu_region = subpicture_region_New( &fmt );
1564         if( !p_spu_region )
1565         {
1566             msg_Err( p_dec, "cannot allocate SPU region" );
1567             continue;
1568         }
1569         p_spu_region->i_x = i_base_x + p_regiondef->i_x;
1570         p_spu_region->i_y = i_base_y + p_regiondef->i_y;
1571         p_spu_region->i_align = p_sys->i_spu_position;
1572         *pp_spu_region = p_spu_region;
1573         pp_spu_region = &p_spu_region->p_next;
1574
1575         p_src = p_region->p_pixbuf;
1576         p_dst = p_spu_region->p_picture->Y_PIXELS;
1577         i_pitch = p_spu_region->p_picture->Y_PITCH;
1578
1579         /* Copy pixel buffer */
1580         for( j = 0; j < p_region->i_height; j++ )
1581         {
1582             memcpy( p_dst, p_src, p_region->i_width );
1583             p_src += p_region->i_width;
1584             p_dst += i_pitch;
1585         }
1586
1587         /* Check subtitles encoded as strings of characters
1588          * (since there are not rendered in the pixbuffer) */
1589         for( j = 0; j < p_region->i_object_defs; j++ )
1590         {
1591             dvbsub_objectdef_t *p_object_def = &p_region->p_object_defs[j];
1592
1593             if( ( p_object_def->i_type != 1 ) || !p_object_def->psz_text )
1594                 continue;
1595
1596             /* Create new SPU region */
1597             memset( &fmt, 0, sizeof(video_format_t) );
1598             fmt.i_chroma = VLC_FOURCC('T','E','X','T');
1599             fmt.i_aspect = VOUT_ASPECT_FACTOR;
1600             fmt.i_width = fmt.i_visible_width = p_region->i_width;
1601             fmt.i_height = fmt.i_visible_height = p_region->i_height;
1602             fmt.i_x_offset = fmt.i_y_offset = 0;
1603             p_spu_region = subpicture_region_New( &fmt );
1604             if( !p_region )
1605             {
1606                 msg_Err( p_dec, "cannot allocate SPU region" );
1607                 continue;
1608             }
1609
1610             p_spu_region->psz_text = strdup( p_object_def->psz_text );
1611             p_spu_region->i_x = i_base_x + p_regiondef->i_x + p_object_def->i_x;
1612             p_spu_region->i_y = i_base_y + p_regiondef->i_y + p_object_def->i_y;
1613             p_spu_region->i_align = p_sys->i_spu_position;
1614             *pp_spu_region = p_spu_region;
1615             pp_spu_region = &p_spu_region->p_next;
1616         }
1617     }
1618
1619     return p_spu;
1620 }
1621
1622 /*****************************************************************************
1623  * encoder_sys_t : encoder descriptor
1624  *****************************************************************************/
1625 typedef struct encoder_region_t
1626 {
1627     int i_width;
1628     int i_height;
1629
1630 } encoder_region_t;
1631
1632 struct encoder_sys_t
1633 {
1634     unsigned int i_page_ver;
1635     unsigned int i_region_ver;
1636     unsigned int i_clut_ver;
1637
1638     int i_regions;
1639     encoder_region_t *p_regions;
1640
1641     mtime_t i_pts;
1642
1643     /* subpicture positioning */
1644     int i_offset_x;
1645     int i_offset_y;
1646 };
1647
1648 static void encode_page_composition( encoder_t *, bs_t *, subpicture_t * );
1649 static void encode_clut( encoder_t *, bs_t *, subpicture_t * );
1650 static void encode_region_composition( encoder_t *, bs_t *, subpicture_t * );
1651 static void encode_object( encoder_t *, bs_t *, subpicture_t * );
1652
1653 /*****************************************************************************
1654  * OpenEncoder: probe the encoder and return score
1655  *****************************************************************************/
1656 static int OpenEncoder( vlc_object_t *p_this )
1657 {
1658     encoder_t *p_enc = (encoder_t *)p_this;
1659     encoder_sys_t *p_sys;
1660     vlc_value_t val;
1661
1662     if( ( p_enc->fmt_out.i_codec != VLC_FOURCC('d','v','b','s') ) &&
1663         !p_enc->b_force )
1664     {
1665         return VLC_EGENERIC;
1666     }
1667
1668     /* Allocate the memory needed to store the decoder's structure */
1669     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
1670         return VLC_ENOMEM;
1671     p_enc->p_sys = p_sys;
1672
1673     p_enc->pf_encode_sub = Encode;
1674     p_enc->fmt_out.i_codec = VLC_FOURCC('d','v','b','s');
1675     p_enc->fmt_out.subs.dvb.i_id  = 1 << 16 | 1;
1676
1677     config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
1678
1679     p_sys->i_page_ver = 0;
1680     p_sys->i_region_ver = 0;
1681     p_sys->i_clut_ver = 0;
1682     p_sys->i_regions = 0;
1683     p_sys->p_regions = 0;
1684
1685     var_Create( p_this, ENC_CFG_PREFIX "x", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
1686     var_Get( p_this, ENC_CFG_PREFIX "x", &val );
1687     p_sys->i_offset_x = val.i_int;
1688     var_Create( p_this, ENC_CFG_PREFIX "y", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
1689     var_Get( p_this, ENC_CFG_PREFIX "y", &val );
1690     p_sys->i_offset_y = val.i_int;
1691
1692     return VLC_SUCCESS;
1693 }
1694
1695 /* FIXME: this routine is a hack to convert VLC_FOURCC('Y','U','V','A')
1696  *        into VLC_FOURCC('Y','U','V','P')
1697  */
1698 static subpicture_t *YuvaYuvp( subpicture_t *p_subpic )
1699 {
1700     subpicture_region_t *p_region = NULL;
1701
1702     if( !p_subpic ) return NULL;
1703
1704     for( p_region = p_subpic->p_region; p_region; p_region = p_region->p_next )
1705     {
1706         video_format_t *p_fmt = &p_region->fmt;
1707         int i = 0, j = 0, n = 0, p = 0;
1708         int i_max_entries = 256;
1709
1710 #ifdef RANDOM_DITHERING
1711         int i_seed = 0xdeadbeef; /* random seed */
1712 #else
1713         int *pi_delta;
1714 #endif
1715         int i_pixels = p_region->p_picture->p[0].i_visible_lines
1716                         * p_region->p_picture->p[0].i_pitch;
1717         int i_iterator = p_region->p_picture->p[0].i_visible_lines * 3 / 4
1718                             * p_region->p_picture->p[0].i_pitch
1719                         + p_region->p_picture->p[0].i_pitch * 1 / 3;
1720         int i_tolerance = 0;
1721
1722 #ifdef DEBUG_DVBSUB
1723         msg_Dbg( p_enc, "YuvaYuvp: i_pixels=%d, i_iterator=%d", i_pixels, i_iterator );
1724 #endif
1725         p_fmt->i_chroma = VLC_FOURCC('Y','U','V','P');
1726         p_fmt->p_palette = (video_palette_t *) malloc( sizeof( video_palette_t ) );
1727         if( !p_fmt->p_palette ) break;
1728         p_fmt->p_palette->i_entries = 0;
1729
1730         /* Find best iterator using Euclide’s algorithm */
1731         for( ; i_iterator > 1 ; i_iterator-- )
1732         {
1733             int a = i_pixels;
1734             int b = i_iterator;
1735             int c;
1736
1737             while( b )
1738             {
1739                 c = a % b;
1740                 a = b;
1741                 b = c;
1742             }
1743
1744             if( a == 1 )
1745             {
1746                 break;
1747             }
1748         }
1749
1750         /* Count colors, build best palette */
1751         for( i_tolerance = 0; i_tolerance < 128; i_tolerance++ )
1752         {
1753             bool b_success = true;
1754             p_fmt->p_palette->i_entries = 0;
1755
1756             for( i = 0; i < i_pixels ; )
1757             {
1758                 uint8_t y, u, v, a;
1759                 y = p_region->p_picture->p[0].p_pixels[i];
1760                 u = p_region->p_picture->p[1].p_pixels[i];
1761                 v = p_region->p_picture->p[2].p_pixels[i];
1762                 a = p_region->p_picture->p[3].p_pixels[i];
1763                 for( j = 0; j < p_fmt->p_palette->i_entries; j++ )
1764                 {
1765                     if( abs((int)p_fmt->p_palette->palette[j][0] - (int)y) <= i_tolerance &&
1766                         abs((int)p_fmt->p_palette->palette[j][1] - (int)u) <= i_tolerance &&
1767                         abs((int)p_fmt->p_palette->palette[j][2] - (int)v) <= i_tolerance &&
1768                         abs((int)p_fmt->p_palette->palette[j][3] - (int)a) <= i_tolerance / 2 )
1769                     {
1770                         break;
1771                     }
1772                 }
1773                 if( j == p_fmt->p_palette->i_entries )
1774                 {
1775                     p_fmt->p_palette->palette[j][0] = y;
1776                     p_fmt->p_palette->palette[j][1] = u;
1777                     p_fmt->p_palette->palette[j][2] = v;
1778                     p_fmt->p_palette->palette[j][3] = a;
1779                     p_fmt->p_palette->i_entries++;
1780                 }
1781                 if( p_fmt->p_palette->i_entries >= i_max_entries )
1782                 {
1783                     b_success = false;
1784                     break;
1785                 }
1786                 i += i_iterator;
1787                 if( i > i_pixels )
1788                 {
1789                     i -= i_pixels;
1790                 }
1791             }
1792
1793             if( b_success )
1794             {
1795                 break;
1796             }
1797         }
1798
1799 #ifdef DEBUG_DVBSUB
1800         msg_Dbg( p_enc, "best palette has %d colors", p_fmt->p_palette->i_entries );
1801 #endif
1802
1803 #ifndef RANDOM_DITHERING
1804         pi_delta = malloc( ( p_region->p_picture->p[0].i_pitch + 1 )
1805                             * sizeof(int) * 4  );
1806         for( i = 0; i < (p_region->p_picture->p[0].i_pitch + 1) * 4 ; i++ )
1807         {
1808             pi_delta[ i ] = 0;
1809         }
1810 #endif
1811
1812         /* Fill image with our new colours */
1813         for( p = 0; p < p_region->p_picture->p[0].i_visible_lines ; p++ )
1814         {
1815             int i_ydelta = 0, i_udelta = 0, i_vdelta = 0, i_adelta = 0;
1816
1817             for( n = 0; n < p_region->p_picture->p[0].i_pitch ; n++ )
1818             {
1819                 int i_offset = p * p_region->p_picture->p[0].i_pitch + n;
1820                 int y, u, v, a;
1821                 int i_mindist, i_best;
1822
1823                 y = (int)p_region->p_picture->p[0].p_pixels[i_offset];
1824                 u = (int)p_region->p_picture->p[1].p_pixels[i_offset];
1825                 v = (int)p_region->p_picture->p[2].p_pixels[i_offset];
1826                 a = (int)p_region->p_picture->p[3].p_pixels[i_offset];
1827
1828                 /* Add dithering compensation */
1829 #ifdef RANDOM_DITHERING
1830                 y += ((i_seed & 0xff) - 0x80) * i_tolerance / 0x80;
1831                 u += (((i_seed >> 8) & 0xff) - 0x80) * i_tolerance / 0x80;
1832                 v += (((i_seed >> 16) & 0xff) - 0x80) * i_tolerance / 0x80;
1833                 a += (((i_seed >> 24) & 0xff) - 0x80) * i_tolerance / 0x80;
1834 #else
1835                 y += i_ydelta + pi_delta[ n * 4 ];
1836                 u += i_udelta + pi_delta[ n * 4 + 1 ];
1837                 v += i_vdelta + pi_delta[ n * 4 + 2 ];
1838                 a += i_adelta + pi_delta[ n * 4 + 3 ];
1839 #endif
1840
1841                 /* Find best colour in palette */
1842                 for( i_mindist = 99999999, i_best = 0, j = 0; j < p_fmt->p_palette->i_entries; j++ )
1843                 {
1844                     int i_dist = 0;
1845
1846                     i_dist += abs((int)p_fmt->p_palette->palette[j][0] - y);
1847                     i_dist += abs((int)p_fmt->p_palette->palette[j][1] - u);
1848                     i_dist += abs((int)p_fmt->p_palette->palette[j][2] - v);
1849                     i_dist += 2 * abs((int)p_fmt->p_palette->palette[j][3] - a);
1850
1851                     if( i_dist < i_mindist )
1852                     {
1853                         i_mindist = i_dist;
1854                         i_best = j;
1855                     }
1856                 }
1857
1858                 /* Set pixel to best color */
1859                 p_region->p_picture->p[0].p_pixels[i_offset] = i_best;
1860
1861                 /* Update dithering state */
1862 #ifdef RANDOM_DITHERING
1863                 i_seed = (i_seed * 0x1283837) ^ 0x789479 ^ (i_seed >> 13);
1864 #else
1865                 i_ydelta = y - (int)p_fmt->p_palette->palette[i_best][0];
1866                 i_udelta = u - (int)p_fmt->p_palette->palette[i_best][1];
1867                 i_vdelta = v - (int)p_fmt->p_palette->palette[i_best][2];
1868                 i_adelta = a - (int)p_fmt->p_palette->palette[i_best][3];
1869                 pi_delta[ n * 4 ] = i_ydelta * 3 / 8;
1870                 pi_delta[ n * 4 + 1 ] = i_udelta * 3 / 8;
1871                 pi_delta[ n * 4 + 2 ] = i_vdelta * 3 / 8;
1872                 pi_delta[ n * 4 + 3 ] = i_adelta * 3 / 8;
1873                 i_ydelta = i_ydelta * 5 / 8;
1874                 i_udelta = i_udelta * 5 / 8;
1875                 i_vdelta = i_vdelta * 5 / 8;
1876                 i_adelta = i_adelta * 5 / 8;
1877 #endif
1878             }
1879         }
1880 #ifndef RANDOM_DITHERING
1881         free( pi_delta );
1882 #endif
1883
1884         /* pad palette */
1885         for( i = p_fmt->p_palette->i_entries; i < i_max_entries; i++ )
1886         {
1887             p_fmt->p_palette->palette[i][0] = 0;
1888             p_fmt->p_palette->palette[i][1] = 0;
1889             p_fmt->p_palette->palette[i][2] = 0;
1890             p_fmt->p_palette->palette[i][3] = 0;
1891         }
1892         p_fmt->p_palette->i_entries = i_max_entries;
1893 #ifdef DEBUG_DVBSUB
1894         msg_Dbg( p_enc, "best palette has %d colors", p_fmt->p_palette->i_entries );
1895 #endif
1896     }
1897     return p_subpic;
1898 } /* End of hack */
1899
1900 /****************************************************************************
1901  * Encode: the whole thing
1902  ****************************************************************************/
1903 static block_t *Encode( encoder_t *p_enc, subpicture_t *p_subpic )
1904 {
1905     subpicture_t *p_temp = NULL;
1906     subpicture_region_t *p_region = NULL;
1907     bs_t bits, *s = &bits;
1908     block_t *p_block;
1909
1910     if( !p_subpic || !p_subpic->p_region ) return NULL;
1911
1912     /* FIXME: this is a hack to convert VLC_FOURCC('Y','U','V','A') into
1913      *  VLC_FOURCC('Y','U','V','P')
1914      */
1915     p_region = p_subpic->p_region;
1916     if( p_region->fmt.i_chroma == VLC_FOURCC('Y','U','V','A') )
1917     {
1918         p_temp = YuvaYuvp( p_subpic );
1919         if( !p_temp )
1920         {
1921             msg_Err( p_enc, "no picture in subpicture" );
1922             return NULL;
1923         }
1924         p_region = p_subpic->p_region;
1925     }
1926
1927     /* Sanity check */
1928     if( !p_region ) return NULL;
1929
1930     if( ( p_region->fmt.i_chroma != VLC_FOURCC('T','E','X','T') ) &&
1931         ( p_region->fmt.i_chroma != VLC_FOURCC('Y','U','V','P') ) )
1932     {
1933         char psz_fourcc[5];
1934         memset( &psz_fourcc, 0, sizeof( psz_fourcc ) );
1935         vlc_fourcc_to_char( p_region->fmt.i_chroma, &psz_fourcc );
1936         msg_Err( p_enc, "chroma %4s not supported", psz_fourcc );
1937         return NULL;
1938     }
1939
1940     if( p_region->fmt.p_palette )
1941     {
1942         switch( p_region->fmt.p_palette->i_entries )
1943         {
1944             case 0:
1945             case 4:
1946             case 16:
1947             case 256:
1948                 break;
1949             default:
1950                 msg_Err( p_enc, "subpicture palette (%d) not handled",
1951                             p_region->fmt.p_palette->i_entries );
1952                 return NULL;
1953         }
1954     }
1955     /* End of hack */
1956
1957 #ifdef DEBUG_DVBSUB
1958     msg_Dbg( p_enc, "encoding subpicture" );
1959 #endif
1960     p_block = block_New( p_enc, 64000 );
1961     bs_init( s, p_block->p_buffer, p_block->i_buffer );
1962
1963     bs_write( s, 8, 0x20 ); /* Data identifier */
1964     bs_write( s, 8, 0x0 );  /* Subtitle stream id */
1965
1966     encode_page_composition( p_enc, s, p_subpic );
1967     encode_region_composition( p_enc, s, p_subpic );
1968     encode_clut( p_enc, s, p_subpic );
1969     encode_object( p_enc, s, p_subpic );
1970
1971     /* End of display */
1972     bs_write( s, 8, 0x0f ); /* Sync byte */
1973     bs_write( s, 8, DVBSUB_ST_ENDOFDISPLAY ); /* Segment type */
1974     bs_write( s, 16, 1 );  /* Page id */
1975     bs_write( s, 16, 0 );  /* Segment length */
1976
1977     bs_write( s, 8, 0xff );/* End marker */
1978     p_block->i_buffer = bs_pos( s ) / 8;
1979     p_block->i_pts = p_block->i_dts = p_subpic->i_start;
1980     if( !p_subpic->b_ephemer && ( p_subpic->i_stop > p_subpic->i_start ) )
1981     {
1982         block_t *p_block_stop;
1983
1984         p_block->i_length = p_subpic->i_stop - p_subpic->i_start;
1985
1986         /* Send another (empty) subtitle to signal the end of display */
1987         p_block_stop = block_New( p_enc, 64000 );
1988         bs_init( s, p_block_stop->p_buffer, p_block_stop->i_buffer );
1989         bs_write( s, 8, 0x20 ); /* Data identifier */
1990         bs_write( s, 8, 0x0 );  /* Subtitle stream id */
1991         encode_page_composition( p_enc, s, 0 );
1992         bs_write( s, 8, 0x0f ); /* Sync byte */
1993         bs_write( s, 8, DVBSUB_ST_ENDOFDISPLAY ); /* Segment type */
1994         bs_write( s, 16, 1 );  /* Page id */
1995         bs_write( s, 16, 0 );  /* Segment length */
1996         bs_write( s, 8, 0xff );/* End marker */
1997         p_block_stop->i_buffer = bs_pos( s ) / 8;
1998         p_block_stop->i_pts = p_block_stop->i_dts = p_subpic->i_stop;
1999         block_ChainAppend( &p_block, p_block_stop );
2000         p_block_stop->i_length = 100000; /* p_subpic->i_stop - p_subpic->i_start; */
2001     }
2002 #ifdef DEBUG_DVBSUB
2003     msg_Dbg( p_enc, "subpicture encoded properly" );
2004 #endif
2005     return p_block;
2006 }
2007
2008 /*****************************************************************************
2009  * CloseEncoder: encoder destruction
2010  *****************************************************************************/
2011 static void CloseEncoder( vlc_object_t *p_this )
2012 {
2013     encoder_t *p_enc = (encoder_t *)p_this;
2014     encoder_sys_t *p_sys = p_enc->p_sys;
2015
2016     var_Destroy( p_this , ENC_CFG_PREFIX "x" );
2017     var_Destroy( p_this , ENC_CFG_PREFIX "y" );
2018     var_Destroy( p_this , ENC_CFG_PREFIX "timeout" );
2019
2020     if( p_sys->i_regions ) free( p_sys->p_regions );
2021     free( p_sys );
2022 }
2023
2024 static void encode_page_composition( encoder_t *p_enc, bs_t *s,
2025                                      subpicture_t *p_subpic )
2026 {
2027     encoder_sys_t *p_sys = p_enc->p_sys;
2028     subpicture_region_t *p_region;
2029     bool b_mode_change = false;
2030     int i_regions, i_timeout;
2031
2032     bs_write( s, 8, 0x0f ); /* Sync byte */
2033     bs_write( s, 8, DVBSUB_ST_PAGE_COMPOSITION ); /* Segment type */
2034     bs_write( s, 16, 1 ); /* Page id */
2035
2036     for( i_regions = 0, p_region = p_subpic ? p_subpic->p_region : 0;
2037          p_region; p_region = p_region->p_next, i_regions++ )
2038     {
2039         if( i_regions >= p_sys->i_regions )
2040         {
2041             encoder_region_t region;
2042             region.i_width = region.i_height = 0;
2043             p_sys->p_regions =
2044                 realloc( p_sys->p_regions, sizeof(encoder_region_t) *
2045                          (p_sys->i_regions + 1) );
2046             p_sys->p_regions[p_sys->i_regions++] = region;
2047         }
2048
2049         if( ( p_sys->p_regions[i_regions].i_width <
2050               (int)p_region->fmt.i_visible_width ) ||
2051             ( p_sys->p_regions[i_regions].i_width >
2052               (int)p_region->fmt.i_visible_width ) )
2053         {
2054             b_mode_change = true;
2055             msg_Dbg( p_enc, "region %i width change: %i -> %i",
2056                      i_regions, p_sys->p_regions[i_regions].i_width,
2057                      p_region->fmt.i_visible_width );
2058             p_sys->p_regions[i_regions].i_width =
2059                 p_region->fmt.i_visible_width;
2060         }
2061         if( p_sys->p_regions[i_regions].i_height <
2062              (int)p_region->fmt.i_visible_height )
2063         {
2064             b_mode_change = true;
2065             msg_Dbg( p_enc, "region %i height change: %i -> %i",
2066                      i_regions, p_sys->p_regions[i_regions].i_height,
2067                      p_region->fmt.i_visible_height );
2068             p_sys->p_regions[i_regions].i_height =
2069                 p_region->fmt.i_visible_height;
2070         }
2071     }
2072
2073     bs_write( s, 16, i_regions * 6 + 2 ); /* Segment length */
2074
2075     i_timeout = 0;
2076     if( p_subpic && !p_subpic->b_ephemer &&
2077         ( p_subpic->i_stop > p_subpic->i_start ) )
2078     {
2079         i_timeout = (p_subpic->i_stop - p_subpic->i_start) / 1000000;
2080     }
2081
2082     bs_write( s, 8, i_timeout ); /* Timeout */
2083     bs_write( s, 4, p_sys->i_page_ver++ );
2084     bs_write( s, 2, b_mode_change ?
2085               DVBSUB_PCS_STATE_CHANGE : DVBSUB_PCS_STATE_ACQUISITION );
2086     bs_write( s, 2, 0 ); /* Reserved */
2087
2088     for( i_regions = 0, p_region = p_subpic ? p_subpic->p_region : 0;
2089          p_region; p_region = p_region->p_next, i_regions++ )
2090     {
2091         bs_write( s, 8, i_regions );
2092         bs_write( s, 8, 0 ); /* Reserved */
2093         if( (p_sys->i_offset_x > 0) && (p_sys->i_offset_y > 0) )
2094         {
2095             bs_write( s, 16, p_sys->i_offset_x ); /* override x position */
2096             bs_write( s, 16, p_sys->i_offset_y ); /* override y position */
2097         }
2098         else
2099         {
2100             bs_write( s, 16, p_region->i_x );
2101             bs_write( s, 16, p_region->i_y );
2102         }
2103     }
2104 }
2105
2106 static void encode_clut( encoder_t *p_enc, bs_t *s, subpicture_t *p_subpic )
2107 {
2108     encoder_sys_t *p_sys = p_enc->p_sys;
2109     subpicture_region_t *p_region = p_subpic->p_region;
2110     video_palette_t *p_pal, pal;
2111     int i;
2112
2113     /* Sanity check */
2114     if( !p_region ) return;
2115
2116     if( p_region->fmt.i_chroma == VLC_FOURCC('Y','U','V','P') )
2117     {
2118         p_pal = p_region->fmt.p_palette;
2119     }
2120     else
2121     {
2122         pal.i_entries = 4;
2123         for( i = 0; i < 4; i++ )
2124         {
2125             pal.palette[i][0] = 0;
2126             pal.palette[i][1] = 0;
2127             pal.palette[i][2] = 0;
2128             pal.palette[i][3] = 0;
2129         }
2130         p_pal = &pal;
2131     }
2132
2133     bs_write( s, 8, 0x0f ); /* Sync byte */
2134     bs_write( s, 8, DVBSUB_ST_CLUT_DEFINITION ); /* Segment type */
2135     bs_write( s, 16, 1 );  /* Page id */
2136
2137     bs_write( s, 16, p_pal->i_entries * 6 + 2 ); /* Segment length */
2138     bs_write( s, 8, 1 ); /* Clut id */
2139     bs_write( s, 4, p_sys->i_clut_ver++ );
2140     bs_write( s, 4, 0 ); /* Reserved */
2141
2142     for( i = 0; i < p_pal->i_entries; i++ )
2143     {
2144         bs_write( s, 8, i ); /* Clut entry id */
2145         bs_write( s, 1, p_pal->i_entries == 4 );   /* 2bit/entry flag */
2146         bs_write( s, 1, p_pal->i_entries == 16 );  /* 4bit/entry flag */
2147         bs_write( s, 1, p_pal->i_entries == 256 ); /* 8bit/entry flag */
2148         bs_write( s, 4, 0 ); /* Reserved */
2149         bs_write( s, 1, 1 ); /* Full range flag */
2150         bs_write( s, 8, p_pal->palette[i][3] ?  /* Y value */
2151                   (p_pal->palette[i][0] ? p_pal->palette[i][0] : 16) : 0 );
2152         bs_write( s, 8, p_pal->palette[i][1] ); /* Cr value */
2153         bs_write( s, 8, p_pal->palette[i][2] ); /* Cb value */
2154         bs_write( s, 8, 0xff - p_pal->palette[i][3] ); /* T value */
2155     }
2156 }
2157
2158 static void encode_region_composition( encoder_t *p_enc, bs_t *s,
2159                                        subpicture_t *p_subpic )
2160 {
2161     encoder_sys_t *p_sys = p_enc->p_sys;
2162     subpicture_region_t *p_region;
2163     int i_region;
2164
2165     for( i_region = 0, p_region = p_subpic->p_region; p_region;
2166          p_region = p_region->p_next, i_region++ )
2167     {
2168         int i_entries = 4, i_depth = 0x1, i_bg = 0;
2169         bool b_text =
2170             ( p_region->fmt.i_chroma == VLC_FOURCC('T','E','X','T') );
2171
2172         if( !b_text )
2173         {
2174             video_palette_t *p_pal = p_region->fmt.p_palette;
2175
2176             if( !p_pal )
2177             {
2178                 msg_Err( p_enc, "subpicture has no palette - ignoring it" );
2179                 break;
2180             }
2181
2182             i_entries = p_pal->i_entries;
2183             i_depth = i_entries == 4 ? 0x1 : i_entries == 16 ? 0x2 : 0x3;
2184
2185             for( i_bg = 0; i_bg < p_pal->i_entries; i_bg++ )
2186             {
2187                 if( !p_pal->palette[i_bg][3] ) break;
2188             }
2189         }
2190
2191         bs_write( s, 8, 0x0f ); /* Sync byte */
2192         bs_write( s, 8, DVBSUB_ST_REGION_COMPOSITION ); /* Segment type */
2193         bs_write( s, 16, 1 );   /* Page id */
2194
2195         bs_write( s, 16, 10 + 6 + (b_text ? 2 : 0) ); /* Segment length */
2196         bs_write( s, 8, i_region );
2197         bs_write( s, 4, p_sys->i_region_ver++ );
2198
2199         /* Region attributes */
2200         bs_write( s, 1, i_bg < i_entries ); /* Fill */
2201         bs_write( s, 3, 0 ); /* Reserved */
2202         bs_write( s, 16, p_sys->p_regions[i_region].i_width );
2203         bs_write( s, 16, p_sys->p_regions[i_region].i_height );
2204         bs_write( s, 3, i_depth );  /* Region level of compatibility */
2205         bs_write( s, 3, i_depth  ); /* Region depth */
2206         bs_write( s, 2, 0 ); /* Reserved */
2207         bs_write( s, 8, 1 ); /* Clut id */
2208         bs_write( s, 8, i_bg ); /* region 8bit pixel code */
2209         bs_write( s, 4, i_bg ); /* region 4bit pixel code */
2210         bs_write( s, 2, i_bg ); /* region 2bit pixel code */
2211         bs_write( s, 2, 0 ); /* Reserved */
2212
2213         /* In our implementation we only have 1 object per region */
2214         bs_write( s, 16, i_region );
2215         bs_write( s, 2, b_text ? DVBSUB_OT_BASIC_CHAR:DVBSUB_OT_BASIC_BITMAP );
2216         bs_write( s, 2, 0 ); /* object provider flag */
2217         bs_write( s, 12, 0 );/* object horizontal position */
2218         bs_write( s, 4, 0 ); /* Reserved */
2219         bs_write( s, 12, 0 );/* object vertical position */
2220
2221         if( b_text )
2222         {
2223             bs_write( s, 8, 1 ); /* foreground pixel code */
2224             bs_write( s, 8, 0 ); /* background pixel code */
2225         }
2226     }
2227 }
2228
2229 static void encode_pixel_data( encoder_t *p_enc, bs_t *s,
2230                                subpicture_region_t *p_region,
2231                                bool b_top );
2232
2233 static void encode_object( encoder_t *p_enc, bs_t *s, subpicture_t *p_subpic )
2234 {
2235     encoder_sys_t *p_sys = p_enc->p_sys;
2236     subpicture_region_t *p_region;
2237     int i_region;
2238
2239     int i_length_pos, i_update_pos, i_pixel_data_pos;
2240
2241     for( i_region = 0, p_region = p_subpic->p_region; p_region;
2242          p_region = p_region->p_next, i_region++ )
2243     {
2244         bs_write( s, 8, 0x0f ); /* Sync byte */
2245         bs_write( s, 8, DVBSUB_ST_OBJECT_DATA ); /* Segment type */
2246         bs_write( s, 16, 1 ); /* Page id */
2247
2248         i_length_pos = bs_pos( s );
2249         bs_write( s, 16, 0 ); /* Segment length */
2250         bs_write( s, 16, i_region ); /* Object id */
2251         bs_write( s, 4, p_sys->i_region_ver++ );
2252
2253         /* object coding method */
2254         switch( p_region->fmt.i_chroma )
2255         {
2256         case VLC_FOURCC( 'Y','U','V','P' ):
2257             bs_write( s, 2, 0 );
2258             break;
2259         case VLC_FOURCC( 'T','E','X','T' ):
2260             bs_write( s, 2, 1 );
2261             break;
2262         default:
2263             msg_Err( p_enc, "FOURCC %d not supported by encoder.", p_region->fmt.i_chroma );
2264             continue;
2265         }
2266
2267         bs_write( s, 1, 0 ); /* non modifying color flag */
2268         bs_write( s, 1, 0 ); /* Reserved */
2269
2270         if( p_region->fmt.i_chroma == VLC_FOURCC( 'T','E','X','T' ) )
2271         {
2272             int i_size, i;
2273
2274             if( !p_region->psz_text ) continue;
2275
2276             i_size = __MIN( strlen( p_region->psz_text ), 256 );
2277
2278             bs_write( s, 8, i_size ); /* number of characters in string */
2279             for( i = 0; i < i_size; i++ )
2280             {
2281                 bs_write( s, 16, p_region->psz_text[i] );
2282             }
2283
2284             /* Update segment length */
2285             SetWBE( &s->p_start[i_length_pos/8],
2286                     (bs_pos(s) - i_length_pos)/8 -2 );
2287             continue;
2288         }
2289
2290         /* Coding of a bitmap object */
2291         i_update_pos = bs_pos( s );
2292         bs_write( s, 16, 0 ); /* topfield data block length */
2293         bs_write( s, 16, 0 ); /* bottomfield data block length */
2294
2295         /* Top field */
2296         i_pixel_data_pos = bs_pos( s );
2297         encode_pixel_data( p_enc, s, p_region, true );
2298         i_pixel_data_pos = ( bs_pos( s ) - i_pixel_data_pos ) / 8;
2299         SetWBE( &s->p_start[i_update_pos/8], i_pixel_data_pos );
2300
2301         /* Bottom field */
2302         i_pixel_data_pos = bs_pos( s );
2303         encode_pixel_data( p_enc, s, p_region, false );
2304         i_pixel_data_pos = ( bs_pos( s ) - i_pixel_data_pos ) / 8;
2305         SetWBE( &s->p_start[i_update_pos/8+2], i_pixel_data_pos );
2306
2307         /* Stuffing for word alignment */
2308         bs_align_0( s );
2309         if( bs_pos( s ) % 16 ) bs_write( s, 8, 0 );
2310
2311         /* Update segment length */
2312         SetWBE( &s->p_start[i_length_pos/8], (bs_pos(s) - i_length_pos)/8 -2 );
2313     }
2314 }
2315
2316 static void encode_pixel_line_2bp( bs_t *s, subpicture_region_t *p_region,
2317                                    int i_line );
2318 static void encode_pixel_line_4bp( bs_t *s, subpicture_region_t *p_region,
2319                                    int i_line );
2320 static void encode_pixel_line_8bp( bs_t *s, subpicture_region_t *p_region,
2321                                    int i_line );
2322 static void encode_pixel_data( encoder_t *p_enc, bs_t *s,
2323                                subpicture_region_t *p_region,
2324                                bool b_top )
2325 {
2326     unsigned int i_line;
2327
2328     /* Sanity check */
2329     if( p_region->fmt.i_chroma != VLC_FOURCC('Y','U','V','P') ) return;
2330
2331     /* Encode line by line */
2332     for( i_line = !b_top; i_line < p_region->fmt.i_visible_height;
2333          i_line += 2 )
2334     {
2335         switch( p_region->fmt.p_palette->i_entries )
2336         {
2337         case 0:
2338             break;
2339
2340         case 4:
2341             bs_write( s, 8, 0x10 ); /* 2 bit/pixel code string */
2342             encode_pixel_line_2bp( s, p_region, i_line );
2343             break;
2344
2345         case 16:
2346             bs_write( s, 8, 0x11 ); /* 4 bit/pixel code string */
2347             encode_pixel_line_4bp( s, p_region, i_line );
2348             break;
2349
2350         case 256:
2351             bs_write( s, 8, 0x12 ); /* 8 bit/pixel code string */
2352             encode_pixel_line_8bp( s, p_region, i_line );
2353             break;
2354
2355         default:
2356             msg_Err( p_enc, "subpicture palette (%i) not handled",
2357                      p_region->fmt.p_palette->i_entries );
2358             break;
2359         }
2360
2361         bs_write( s, 8, 0xf0 ); /* End of object line code */
2362     }
2363 }
2364
2365 static void encode_pixel_line_2bp( bs_t *s, subpicture_region_t *p_region,
2366                                    int i_line )
2367 {
2368     unsigned int i, i_length = 0;
2369     int i_pitch = p_region->p_picture->p->i_pitch;
2370     uint8_t *p_data = &p_region->p_picture->p->p_pixels[ i_pitch * i_line ];
2371     int i_last_pixel = p_data[0];
2372
2373     for( i = 0; i <= p_region->fmt.i_visible_width; i++ )
2374     {
2375         if( ( i != p_region->fmt.i_visible_width ) &&
2376             ( p_data[i] == i_last_pixel ) && ( i_length != 284 ) )
2377         {
2378             i_length++;
2379             continue;
2380         }
2381
2382         if( ( i_length == 1 ) || ( i_length == 11 ) || ( i_length == 28 ) )
2383         {
2384             /* 2bit/pixel code */
2385             if( i_last_pixel )
2386                 bs_write( s, 2, i_last_pixel );
2387             else
2388             {
2389                 bs_write( s, 2, 0 );
2390                 bs_write( s, 1, 0 );
2391                 bs_write( s, 1, 1 ); /* pseudo color 0 */
2392             }
2393             i_length--;
2394         }
2395
2396         if( i_length == 2 )
2397         {
2398             if( i_last_pixel )
2399             {
2400                 bs_write( s, 2, i_last_pixel );
2401                 bs_write( s, 2, i_last_pixel );
2402             }
2403             else
2404             {
2405                 bs_write( s, 2, 0 );
2406                 bs_write( s, 1, 0 );
2407                 bs_write( s, 1, 0 );
2408                 bs_write( s, 2, 1 ); /* 2 * pseudo color 0 */
2409             }
2410         }
2411         else if( i_length > 2 )
2412         {
2413             bs_write( s, 2, 0 );
2414             if( i_length <= 10 )
2415             {
2416                 bs_write( s, 1, 1 );
2417                 bs_write( s, 3, i_length - 3 );
2418                 bs_write( s, 2, i_last_pixel );
2419             }
2420             else
2421             {
2422                 bs_write( s, 1, 0 );
2423                 bs_write( s, 1, 0 );
2424
2425                 if( i_length <= 27 )
2426                 {
2427                     bs_write( s, 2, 2 );
2428                     bs_write( s, 4, i_length - 12 );
2429                     bs_write( s, 2, i_last_pixel );
2430                 }
2431                 else
2432                 {
2433                     bs_write( s, 2, 3 );
2434                     bs_write( s, 8, i_length - 29 );
2435                     bs_write( s, 2, i_last_pixel );
2436                 }
2437             }
2438         }
2439
2440         if( i == p_region->fmt.i_visible_width ) break;
2441
2442         i_last_pixel = p_data[i];
2443         i_length = 1;
2444     }
2445
2446     /* Stop */
2447     bs_write( s, 2, 0 );
2448     bs_write( s, 1, 0 );
2449     bs_write( s, 1, 0 );
2450     bs_write( s, 2, 0 );
2451
2452     /* Stuffing */
2453     bs_align_0( s );
2454 }
2455
2456 static void encode_pixel_line_4bp( bs_t *s, subpicture_region_t *p_region,
2457                                    int i_line )
2458 {
2459     unsigned int i, i_length = 0;
2460     int i_pitch = p_region->p_picture->p->i_pitch;
2461     uint8_t *p_data = &p_region->p_picture->p->p_pixels[ i_pitch * i_line ];
2462     int i_last_pixel = p_data[0];
2463
2464     for( i = 0; i <= p_region->fmt.i_visible_width; i++ )
2465     {
2466         if( i != p_region->fmt.i_visible_width &&
2467             p_data[i] == i_last_pixel && i_length != 280 )
2468         {
2469             i_length++;
2470             continue;
2471         }
2472
2473         if( ( i_length == 1 ) ||
2474             ( ( i_length == 3 ) && i_last_pixel ) ||
2475             ( i_length == 8 ) )
2476         {
2477             /* 4bit/pixel code */
2478             if( i_last_pixel )
2479                 bs_write( s, 4, i_last_pixel );
2480             else
2481             {
2482                 bs_write( s, 4, 0 );
2483                 bs_write( s, 1, 1 );
2484                 bs_write( s, 1, 1 );
2485                 bs_write( s, 2, 0 ); /* pseudo color 0 */
2486             }
2487             i_length--;
2488         }
2489
2490         if( i_length == 2 )
2491         {
2492             if( i_last_pixel )
2493             {
2494                 bs_write( s, 4, i_last_pixel );
2495                 bs_write( s, 4, i_last_pixel );
2496             }
2497             else
2498             {
2499                 bs_write( s, 4, 0 );
2500                 bs_write( s, 1, 1 );
2501                 bs_write( s, 1, 1 );
2502                 bs_write( s, 2, 1 ); /* 2 * pseudo color 0 */
2503             }
2504         }
2505         else if( !i_last_pixel && ( i_length >= 3 ) && ( i_length <= 9 ) )
2506         {
2507             bs_write( s, 4, 0 );
2508             bs_write( s, 1, 0 );
2509             bs_write( s, 3, i_length - 2 ); /* (i_length - 2) * color 0 */
2510         }
2511         else if( i_length > 2 )
2512         {
2513             bs_write( s, 4, 0 );
2514             bs_write( s, 1, 1 );
2515
2516             if( i_length <= 7 )
2517             {
2518                 bs_write( s, 1, 0 );
2519                 bs_write( s, 2, i_length - 4 );
2520                 bs_write( s, 4, i_last_pixel );
2521             }
2522             else
2523             {
2524                 bs_write( s, 1, 1 );
2525
2526                 if( i_length <= 24 )
2527                 {
2528                     bs_write( s, 2, 2 );
2529                     bs_write( s, 4, i_length - 9 );
2530                     bs_write( s, 4, i_last_pixel );
2531                 }
2532                 else
2533                 {
2534                     bs_write( s, 2, 3 );
2535                     bs_write( s, 8, i_length - 25 );
2536                     bs_write( s, 4, i_last_pixel );
2537                 }
2538             }
2539         }
2540
2541         if( i == p_region->fmt.i_visible_width ) break;
2542
2543         i_last_pixel = p_data[i];
2544         i_length = 1;
2545     }
2546
2547     /* Stop */
2548     bs_write( s, 8, 0 );
2549
2550     /* Stuffing */
2551     bs_align_0( s );
2552 }
2553
2554 static void encode_pixel_line_8bp( bs_t *s, subpicture_region_t *p_region,
2555                                    int i_line )
2556 {
2557     unsigned int i, i_length = 0;
2558     int i_pitch = p_region->p_picture->p->i_pitch;
2559     uint8_t *p_data = &p_region->p_picture->p->p_pixels[ i_pitch * i_line ];
2560     int i_last_pixel = p_data[0];
2561
2562     for( i = 0; i <= p_region->fmt.i_visible_width; i++ )
2563     {
2564         if( ( i != p_region->fmt.i_visible_width ) &&
2565             ( p_data[i] == i_last_pixel ) && ( i_length != 127 ) )
2566         {
2567             i_length++;
2568             continue;
2569         }
2570
2571         if( ( i_length == 1 ) && i_last_pixel )
2572         {
2573             /* 8bit/pixel code */
2574             bs_write( s, 8, i_last_pixel );
2575         }
2576         else if( ( i_length == 2 ) && i_last_pixel )
2577         {
2578             /* 8bit/pixel code */
2579             bs_write( s, 8, i_last_pixel );
2580             bs_write( s, 8, i_last_pixel );
2581         }
2582         else if( i_length <= 127 )
2583         {
2584             bs_write( s, 8, 0 );
2585
2586             if( !i_last_pixel )
2587             {
2588                 bs_write( s, 1, 0 );
2589                 bs_write( s, 7, i_length ); /* pseudo color 0 */
2590             }
2591             else
2592             {
2593                 bs_write( s, 1, 1 );
2594                 bs_write( s, 7, i_length );
2595                 bs_write( s, 8, i_last_pixel );
2596             }
2597         }
2598
2599         if( i == p_region->fmt.i_visible_width ) break;
2600
2601         i_last_pixel = p_data[i];
2602         i_length = 1;
2603     }
2604
2605     /* Stop */
2606     bs_write( s, 8, 0 );
2607     bs_write( s, 8, 0 );
2608
2609     /* Stuffing */
2610     bs_align_0( s );
2611 }