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