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