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