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