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