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