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