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