]> git.sesse.net Git - vlc/blob - modules/codec/cc.c
macosx: fixed menubar appearance in fullscreen mode by partially reverting [46c93c9cc...
[vlc] / modules / codec / cc.c
1 /*****************************************************************************
2  * cc608.c : CC 608/708 subtitles decoder
3  *****************************************************************************
4  * Copyright (C) 2007 Laurent Aimar
5  * $Id$
6  *
7  * Authors: Laurent Aimar < fenrir # via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 /* The EIA 608 decoder part has been initialy based on ccextractor (GPL)
28  * and rewritten */
29
30 /* TODO:
31  *  On discontinuity reset the decoder state
32  *  Check parity
33  *  708 decoding
34  */
35
36 #ifdef HAVE_CONFIG_H
37 # include "config.h"
38 #endif
39
40 #include <vlc_common.h>
41 #include <vlc_plugin.h>
42 #include <vlc_vout.h>
43 #include <vlc_codec.h>
44 #include <vlc_input.h>
45
46 #include <vlc_osd.h>
47 #include <vlc_filter.h>
48 #include <vlc_image.h>
49 #include <vlc_charset.h>
50 #include <vlc_stream.h>
51 #include <vlc_xml.h>
52 #include <errno.h>
53 #include <string.h>
54
55 #include <assert.h>
56
57 /*****************************************************************************
58  * Module descriptor.
59  *****************************************************************************/
60 static int  Open ( vlc_object_t * );
61 static void Close( vlc_object_t * );
62
63 vlc_module_begin ()
64     set_shortname( N_("CC 608/708"))
65     set_description( N_("Closed Captions decoder") )
66     set_capability( "decoder", 50 )
67     set_callbacks( Open, Close )
68 vlc_module_end ()
69
70 /*****************************************************************************
71  * Local prototypes
72  *****************************************************************************/
73 typedef enum
74 {
75     EIA608_MODE_POPUP = 0,
76     EIA608_MODE_ROLLUP_2 = 1,
77     EIA608_MODE_ROLLUP_3 = 2,
78     EIA608_MODE_ROLLUP_4 = 3,
79     EIA608_MODE_PAINTON = 4,
80     EIA608_MODE_TEXT = 5
81 } eia608_mode_t;
82
83 typedef enum
84 {
85     EIA608_COLOR_WHITE = 0,
86     EIA608_COLOR_GREEN = 1,
87     EIA608_COLOR_BLUE = 2,
88     EIA608_COLOR_CYAN = 3,
89     EIA608_COLOR_RED = 4,
90     EIA608_COLOR_YELLOW = 5,
91     EIA608_COLOR_MAGENTA = 6,
92     EIA608_COLOR_USERDEFINED = 7
93 } eia608_color_t;
94
95 typedef enum
96 {
97     EIA608_FONT_REGULAR    = 0x00,
98     EIA608_FONT_ITALICS    = 0x01,
99     EIA608_FONT_UNDERLINE  = 0x02,
100     EIA608_FONT_UNDERLINE_ITALICS = EIA608_FONT_UNDERLINE | EIA608_FONT_ITALICS
101 } eia608_font_t;
102
103 #define EIA608_SCREEN_ROWS 15
104 #define EIA608_SCREEN_COLUMNS 32
105
106 struct eia608_screen // A CC buffer
107 {
108     uint8_t characters[EIA608_SCREEN_ROWS][EIA608_SCREEN_COLUMNS+1];
109     eia608_color_t colors[EIA608_SCREEN_ROWS][EIA608_SCREEN_COLUMNS+1];
110     eia608_font_t fonts[EIA608_SCREEN_ROWS][EIA608_SCREEN_COLUMNS+1]; // Extra char at the end for a 0
111     int row_used[EIA608_SCREEN_ROWS]; // Any data in row?
112 };
113 typedef struct eia608_screen eia608_screen;
114
115 typedef struct
116 {
117     /* Current channel (used to reject packet without channel information) */
118     int i_channel;
119
120     /* */
121     int           i_screen; /* Displayed screen */
122     eia608_screen screen[2];
123
124     struct
125     {
126         int i_row;
127         int i_column;
128     } cursor;
129
130     /* */
131     eia608_mode_t mode;
132     eia608_color_t color;
133     eia608_font_t font;
134     int i_row_rollup;
135
136     /* Last command pair (used to reject duplicated command) */
137     struct
138     {
139         uint8_t d1;
140         uint8_t d2;
141     } last;
142 } eia608_t;
143
144 static void         Eia608Init( eia608_t * );
145 static bool   Eia608Parse( eia608_t *h, int i_channel_selected, const uint8_t data[2] );
146 static char        *Eia608Text( eia608_t *h, bool b_html );
147 static void         Eia608Exit( eia608_t * );
148
149 /* It will be enough up to 63 B frames, which is far too high for
150  * broadcast environment */
151 #define CC_MAX_REORDER_SIZE (64)
152 struct decoder_sys_t
153 {
154     int i;
155
156     int     i_block;
157     block_t *pp_block[CC_MAX_REORDER_SIZE];
158
159     int i_field;
160     int i_channel;
161
162     eia608_t eia608;
163 };
164
165 static subpicture_t *Decode( decoder_t *, block_t ** );
166
167 /*****************************************************************************
168  * Open: probe the decoder and return score
169  *****************************************************************************
170  * Tries to launch a decoder and return score so that the interface is able
171  * to chose.
172  *****************************************************************************/
173 static int Open( vlc_object_t *p_this )
174 {
175     decoder_t     *p_dec = (decoder_t*)p_this;
176     decoder_sys_t *p_sys;
177     int i_field;
178     int i_channel;
179
180     switch( p_dec->fmt_in.i_codec )
181     {
182         case VLC_FOURCC('c','c','1',' '):
183             i_field = 0; i_channel = 1;
184             break;
185         case VLC_FOURCC('c','c','2',' '):
186             i_field = 0; i_channel = 2;
187             break;
188         case VLC_FOURCC('c','c','3',' '):
189             i_field = 1; i_channel = 1;
190             break;
191         case VLC_FOURCC('c','c','4',' '):
192             i_field = 1; i_channel = 2;
193             break;
194
195         default:
196             return VLC_EGENERIC;
197     }
198
199     p_dec->pf_decode_sub = Decode;
200
201     /* Allocate the memory needed to store the decoder's structure */
202     p_dec->p_sys = p_sys = calloc( 1, sizeof( *p_sys ) );
203     if( p_sys == NULL )
204         return VLC_ENOMEM;
205
206     /* init of p_sys */
207     p_sys->i_field = i_field;
208     p_sys->i_channel = i_channel;
209
210     Eia608Init( &p_sys->eia608 );
211
212     p_dec->fmt_out.i_cat = SPU_ES;
213     p_dec->fmt_out.i_codec = VLC_FOURCC('T','E','X','T');
214
215     return VLC_SUCCESS;
216 }
217
218 /****************************************************************************
219  * Decode: the whole thing
220  ****************************************************************************
221  *
222  ****************************************************************************/
223 static void     Push( decoder_t *, block_t * );
224 static block_t *Pop( decoder_t * );
225 static subpicture_t *Convert( decoder_t *, block_t * );
226
227 static subpicture_t *Decode( decoder_t *p_dec, block_t **pp_block )
228 {
229     if( pp_block && *pp_block )
230     {
231         Push( p_dec, *pp_block );
232         *pp_block = NULL;
233     }
234
235     for( ;; )
236     {
237         block_t *p_block = Pop( p_dec );
238         if( !p_block )
239             break;
240
241         subpicture_t *p_spu = Convert( p_dec, p_block );
242         if( p_spu )
243             return p_spu;
244     }
245     return NULL;
246 }
247
248 /*****************************************************************************
249  * CloseDecoder: clean up the decoder
250  *****************************************************************************/
251 static void Close( vlc_object_t *p_this )
252 {
253     decoder_t *p_dec = (decoder_t *)p_this;
254     decoder_sys_t *p_sys = p_dec->p_sys;
255     int i;
256
257     for( i = 0; i < p_sys->i_block; i++ )
258         block_Release( p_sys->pp_block[i] );
259     Eia608Exit( &p_sys->eia608 );
260     free( p_sys );
261 }
262
263 /*****************************************************************************
264  *
265  *****************************************************************************/
266 static void Push( decoder_t *p_dec, block_t *p_block )
267 {
268     decoder_sys_t *p_sys = p_dec->p_sys;
269
270     if( p_sys->i_block >= CC_MAX_REORDER_SIZE )
271     {
272         msg_Warn( p_dec, "Trashing a CC entry" );
273         memmove( &p_sys->pp_block[0], &p_sys->pp_block[1], sizeof(*p_sys->pp_block) * (CC_MAX_REORDER_SIZE-1) );
274         p_sys->i_block--;
275     }
276     p_sys->pp_block[p_sys->i_block++] = p_block;
277 }
278 static block_t *Pop( decoder_t *p_dec )
279 {
280     decoder_sys_t *p_sys = p_dec->p_sys;
281     block_t *p_block;
282     int i_index;
283     int i;
284     /* XXX Cc captions data are OUT OF ORDER (because we receive them in the bitstream
285      * order (ie ordered by video picture dts) instead of the display order.
286      *  We will simulate a simple IPB buffer scheme
287      * and reorder with pts.
288      * XXX it won't work with H264 which use non out of order B picture or MMCO
289      */
290
291     /* Wait for a P and output all *previous* picture by pts order (for
292      * hierarchical B frames) */
293     if( p_sys->i_block <= 1 ||
294         ( p_sys->pp_block[p_sys->i_block-1]->i_flags & BLOCK_FLAG_TYPE_B ) )
295         return NULL;
296
297     p_block = p_sys->pp_block[i_index = 0];
298     if( p_block->i_pts > 0 )
299     {
300         for( i = 1; i < p_sys->i_block-1; i++ )
301         {
302             if( p_sys->pp_block[i]->i_pts > 0 && p_block->i_pts > 0 &&
303                 p_sys->pp_block[i]->i_pts < p_block->i_pts )
304                 p_block = p_sys->pp_block[i_index = i];
305         }
306     }
307     assert( i_index+1 < p_sys->i_block );
308     memmove( &p_sys->pp_block[i_index], &p_sys->pp_block[i_index+1], sizeof(*p_sys->pp_block) * ( p_sys->i_block - i_index - 1 ) );
309     p_sys->i_block--;
310
311     return p_block;
312 }
313
314 static subpicture_t *Subtitle( decoder_t *p_dec, char *psz_subtitle, char *psz_html, mtime_t i_pts )
315 {
316     //decoder_sys_t *p_sys = p_dec->p_sys;
317     subpicture_t *p_spu = NULL;
318     video_format_t fmt;
319
320     /* We cannot display a subpicture with no date */
321     if( i_pts == 0 )
322     {
323         msg_Warn( p_dec, "subtitle without a date" );
324         return NULL;
325     }
326
327     EnsureUTF8( psz_subtitle );
328     if( psz_html )
329         EnsureUTF8( psz_html );
330
331     /* Create the subpicture unit */
332     p_spu = decoder_NewSubpicture( p_dec );
333     if( !p_spu )
334     {
335         msg_Warn( p_dec, "can't get spu buffer" );
336         free( psz_subtitle );
337         free( psz_html );
338         return NULL;
339     }
340
341     /* Create a new subpicture region */
342     memset( &fmt, 0, sizeof(video_format_t) );
343     fmt.i_chroma = VLC_FOURCC('T','E','X','T');
344     fmt.i_aspect = 0;
345     fmt.i_width = fmt.i_height = 0;
346     fmt.i_x_offset = fmt.i_y_offset = 0;
347     p_spu->p_region = subpicture_region_New( &fmt );
348     if( !p_spu->p_region )
349     {
350         msg_Err( p_dec, "cannot allocate SPU region" );
351         free( psz_subtitle );
352         free( psz_html );
353         decoder_DeleteSubpicture( p_dec, p_spu );
354         return NULL;
355     }
356
357     /* Decode and format the subpicture unit */
358     /* Normal text subs, easy markup */
359     p_spu->p_region->i_align = SUBPICTURE_ALIGN_BOTTOM;// | SUBPICTURE_ALIGN_LEFT;// | p_sys->i_align;
360     p_spu->p_region->i_x = 0; //p_sys->i_align ? 20 : 0;
361     p_spu->p_region->i_y = 10;
362
363     p_spu->p_region->psz_text = psz_subtitle;
364     p_spu->p_region->psz_html = psz_html;
365
366     p_spu->i_start = i_pts;
367     p_spu->i_stop = i_pts + 10000000;   /* 10s max */
368     p_spu->b_ephemer = true;
369     p_spu->b_absolute = false;
370
371     return p_spu;
372 }
373
374 static subpicture_t *Convert( decoder_t *p_dec, block_t *p_block )
375 {
376     assert( p_block );
377
378     decoder_sys_t *p_sys = p_dec->p_sys;
379     const int64_t i_pts = p_block->i_pts;
380     bool b_changed = false;
381
382     /* TODO do the real decoding here */
383     while( p_block->i_buffer >= 3 )
384     {
385         if( p_block->p_buffer[0] == p_sys->i_field )
386             b_changed |= Eia608Parse( &p_sys->eia608, p_sys->i_channel, &p_block->p_buffer[1] );
387
388         p_block->i_buffer -= 3;
389         p_block->p_buffer += 3;
390     }
391     if( p_block )
392         block_Release( p_block );
393
394     if( b_changed )
395     {
396         char *psz_subtitle = Eia608Text( &p_sys->eia608, false );
397         char *psz_html     = NULL;//Eia608Text( &p_sys->eia608, true );
398         return Subtitle( p_dec, psz_subtitle, psz_html, i_pts );
399     }
400     return NULL;
401 }
402
403
404 /*****************************************************************************
405  *
406  *****************************************************************************/
407 static const struct {
408     eia608_color_t  i_color;
409     eia608_font_t   i_font;
410     int             i_column;
411 } pac2_attribs[]= {
412     { EIA608_COLOR_WHITE,   EIA608_FONT_REGULAR,           0 },
413     { EIA608_COLOR_WHITE,   EIA608_FONT_UNDERLINE,         0 },
414     { EIA608_COLOR_GREEN,   EIA608_FONT_REGULAR,           0 },
415     { EIA608_COLOR_GREEN,   EIA608_FONT_UNDERLINE,         0 },
416     { EIA608_COLOR_BLUE,    EIA608_FONT_REGULAR,           0 },
417     { EIA608_COLOR_BLUE,    EIA608_FONT_UNDERLINE,         0 },
418     { EIA608_COLOR_CYAN,    EIA608_FONT_REGULAR,           0 },
419     { EIA608_COLOR_CYAN,    EIA608_FONT_UNDERLINE,         0 },
420     { EIA608_COLOR_RED,     EIA608_FONT_REGULAR,           0 },
421     { EIA608_COLOR_RED,     EIA608_FONT_UNDERLINE,         0 },
422     { EIA608_COLOR_YELLOW,  EIA608_FONT_REGULAR,           0 },
423     { EIA608_COLOR_YELLOW,  EIA608_FONT_UNDERLINE,         0 },
424     { EIA608_COLOR_MAGENTA, EIA608_FONT_REGULAR,           0 },
425     { EIA608_COLOR_MAGENTA, EIA608_FONT_UNDERLINE,         0 },
426     { EIA608_COLOR_WHITE,   EIA608_FONT_ITALICS,           0 },
427     { EIA608_COLOR_WHITE,   EIA608_FONT_UNDERLINE_ITALICS, 0 },
428
429     { EIA608_COLOR_WHITE,   EIA608_FONT_REGULAR,           0 },
430     { EIA608_COLOR_WHITE,   EIA608_FONT_UNDERLINE,         0 },
431     { EIA608_COLOR_WHITE,   EIA608_FONT_REGULAR,           4 },
432     { EIA608_COLOR_WHITE,   EIA608_FONT_UNDERLINE,         4 },
433     { EIA608_COLOR_WHITE,   EIA608_FONT_REGULAR,           8 },
434     { EIA608_COLOR_WHITE,   EIA608_FONT_UNDERLINE,         8 },
435     { EIA608_COLOR_WHITE,   EIA608_FONT_REGULAR,          12 },
436     { EIA608_COLOR_WHITE,   EIA608_FONT_UNDERLINE,        12 },
437     { EIA608_COLOR_WHITE,   EIA608_FONT_REGULAR,          16 },
438     { EIA608_COLOR_WHITE,   EIA608_FONT_UNDERLINE,        16 },
439     { EIA608_COLOR_WHITE,   EIA608_FONT_REGULAR,          20 },
440     { EIA608_COLOR_WHITE,   EIA608_FONT_UNDERLINE,        20 },
441     { EIA608_COLOR_WHITE,   EIA608_FONT_REGULAR,          24 },
442     { EIA608_COLOR_WHITE,   EIA608_FONT_UNDERLINE,        24 },
443     { EIA608_COLOR_WHITE,   EIA608_FONT_REGULAR,          28 },
444     { EIA608_COLOR_WHITE,   EIA608_FONT_UNDERLINE,        28 } ,
445 };
446
447 #define EIA608_COLOR_DEFAULT EIA608_COLOR_WHITE
448
449 static void Eia608Cursor( eia608_t *h, int dx )
450 {
451     h->cursor.i_column += dx;
452     if( h->cursor.i_column < 0 )
453         h->cursor.i_column = 0;
454     else if( h->cursor.i_column > EIA608_SCREEN_COLUMNS-1 )
455         h->cursor.i_column = EIA608_SCREEN_COLUMNS-1;
456 }
457 static void Eia608ClearScreenRowX( eia608_t *h, int i_screen, int i_row, int x )
458 {
459     eia608_screen *screen = &h->screen[i_screen];
460     int i;
461
462     if( x == 0 )
463     {
464         screen->row_used[i_row] = false;
465     }
466     else
467     {
468         screen->row_used[i_row] = false;
469         for( i = 0; i < x; i++ )
470         {
471             if( screen->characters[i_row][i] != ' ' ||
472                 screen->colors[i_row][i] != EIA608_COLOR_DEFAULT ||
473                 screen->fonts[i_row][i] != EIA608_FONT_REGULAR )
474             {
475                 screen->row_used[i_row] = true;
476                 break;
477             }
478         }
479     }
480
481     for( ; x < EIA608_SCREEN_COLUMNS+1; x++ )
482     {
483         screen->characters[i_row][x] = x < EIA608_SCREEN_COLUMNS ? ' ' : '\0';
484         screen->colors[i_row][x] = EIA608_COLOR_DEFAULT;
485         screen->fonts[i_row][x] = EIA608_FONT_REGULAR;
486     }
487 }
488
489 static void Eia608ClearScreenRow( eia608_t *h, int i_screen, int i_row )
490 {
491     Eia608ClearScreenRowX( h, i_screen, i_row, 0 );
492 }
493
494 static void Eia608ClearScreen( eia608_t *h, int i_screen )
495 {
496     int i;
497     for( i = 0; i < EIA608_SCREEN_ROWS; i++ )
498         Eia608ClearScreenRow( h, i_screen, i );
499 }
500
501 static int Eia608GetWritingScreenIndex( eia608_t *h )
502 {
503     switch( h->mode )
504     {
505     case EIA608_MODE_POPUP:    // Non displayed screen
506         return 1 - h->i_screen;
507
508     case EIA608_MODE_ROLLUP_2: // Displayed screen
509     case EIA608_MODE_ROLLUP_3:
510     case EIA608_MODE_ROLLUP_4:
511     case EIA608_MODE_PAINTON:
512         return h->i_screen;
513     default:
514         /* It cannot happen, else it is a bug */
515         assert( 0 );
516         return 0;
517     }
518 }
519
520 static void Eia608EraseScreen( eia608_t *h, bool b_displayed )
521 {
522     Eia608ClearScreen( h, b_displayed ? h->i_screen : (1-h->i_screen) );
523 }
524
525 static void Eia608Write( eia608_t *h, const uint8_t c )
526 {
527     const int i_row = h->cursor.i_row;
528     const int i_column = h->cursor.i_column;
529     eia608_screen *screen;
530
531     if( h->mode == EIA608_MODE_TEXT )
532         return;
533
534     screen = &h->screen[Eia608GetWritingScreenIndex( h )];
535
536     screen->characters[i_row][i_column] = c;
537     screen->colors[i_row][i_column] = h->color;
538     screen->fonts[i_row][i_column] = h->font;
539     screen->row_used[i_row] = true;
540     Eia608Cursor( h, 1 );
541 }
542 static void Eia608Erase( eia608_t *h )
543 {
544     const int i_row = h->cursor.i_row;
545     const int i_column = h->cursor.i_column - 1;
546     eia608_screen *screen;
547
548     if( h->mode == EIA608_MODE_TEXT )
549         return;
550     if( i_column < 0 )
551         return;
552
553     screen = &h->screen[Eia608GetWritingScreenIndex( h )];
554
555     /* FIXME do we need to reset row_used/colors/font ? */
556     screen->characters[i_row][i_column] = ' ';
557     Eia608Cursor( h, -1 );
558 }
559 static void Eia608EraseToEndOfRow( eia608_t *h )
560 {
561     if( h->mode == EIA608_MODE_TEXT )
562         return;
563
564     Eia608ClearScreenRowX( h, Eia608GetWritingScreenIndex( h ), h->cursor.i_row, h->cursor.i_column );
565 }
566
567 static void Eia608RollUp( eia608_t *h )
568 {
569     const int i_screen = Eia608GetWritingScreenIndex( h );
570     eia608_screen *screen = &h->screen[i_screen];
571
572     int keep_lines;
573     int i;
574
575     /* Window size */
576     if( h->mode == EIA608_MODE_ROLLUP_2 )
577         keep_lines = 2;
578     else if( h->mode == EIA608_MODE_ROLLUP_3 )
579         keep_lines = 3;
580     else if( h->mode == EIA608_MODE_ROLLUP_4 )
581         keep_lines = 4;
582     else
583         return;
584
585     /* Reset the cursor */
586     h->cursor.i_column = 0;
587
588     /* Erase lines above our window */
589     for( i = 0; i < h->cursor.i_row - keep_lines; i++ )
590         Eia608ClearScreenRow( h, i_screen, i );
591
592     /* Move up */
593     for( i = 0; i < keep_lines-1; i++ )
594     {
595         const int i_row = h->cursor.i_row - keep_lines + i + 1;
596         if( i_row < 0 )
597             continue;
598         assert( i_row+1 < EIA608_SCREEN_ROWS );
599         memcpy( screen->characters[i_row], screen->characters[i_row+1], sizeof(*screen->characters) );
600         memcpy( screen->colors[i_row], screen->colors[i_row+1], sizeof(*screen->colors) );
601         memcpy( screen->fonts[i_row], screen->fonts[i_row+1], sizeof(*screen->fonts) );
602         screen->row_used[i_row] = screen->row_used[i_row+1];
603     }
604     /* Reset current row */
605     Eia608ClearScreenRow( h, i_screen, h->cursor.i_row );
606 }
607 static void Eia608ParseChannel( eia608_t *h, uint8_t d[2] )
608 {
609     /* Check odd parity */
610     static const int p4[16] = {
611         0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0
612     };
613     if( p4[d[0] & 0xf] == p4[d[0] >> 4] ||
614         p4[d[1] & 0xf] == p4[ d[1] >> 4] )
615     {
616         h->i_channel = -1;
617         return;
618     }
619
620     /* */
621     const int d1 = d[0] & 0x7f;
622     const int d2 = d[1] & 0x7f;
623     if( d1 == 0x14 )
624         h->i_channel = 1;
625     else if( d1 == 0x1c )
626         h->i_channel = 2;
627     else if( d1 == 0x15 )
628         h->i_channel = 3;
629     else if( d1 == 0x1d )
630         h->i_channel = 4;
631 }
632 static bool Eia608ParseTextAttribute( eia608_t *h, uint8_t d2 )
633 {
634     const int i_index = d2 - 0x20;
635     assert( d2 >= 0x20 && d2 <= 0x2f );
636
637     h->color = pac2_attribs[i_index].i_color;
638     h->font  = pac2_attribs[i_index].i_font;
639     Eia608Cursor( h, 1 );
640
641     return false;
642 }
643 static bool Eia608ParseSingle( eia608_t *h, const uint8_t dx )
644 {
645     assert( dx >= 0x20 );
646     Eia608Write( h, dx );
647     return true;
648 }
649 static bool Eia608ParseDouble( eia608_t *h, uint8_t d2 )
650 {
651     assert( d2 >= 0x30 && d2 <= 0x3f );
652     Eia608Write( h, d2 + 0x50 ); /* We use charaters 0x80...0x8f */
653     return true;
654 }
655 static bool Eia608ParseExtended( eia608_t *h, uint8_t d1, uint8_t d2 )
656 {
657     assert( d2 >= 0x20 && d2 <= 0x3f );
658     assert( d1 == 0x12 || d1 == 0x13 );
659     if( d1 == 0x12 )
660         d2 += 0x70; /* We use charaters 0x90-0xaf */
661     else
662         d2 += 0x90; /* We use charaters 0xb0-0xcf */
663
664     /* The extended characters replace the previous one with a more
665      * advanced one */
666     Eia608Cursor( h, -1 );
667     Eia608Write( h, d2 );
668     return true;
669 }
670 static bool Eia608ParseCommand0x14( eia608_t *h, uint8_t d2 )
671 {
672     bool b_changed = false;
673
674     switch( d2 )
675     {
676     case 0x20:  /* Resume caption loading */
677         h->mode = EIA608_MODE_POPUP;
678         break;
679     case 0x21:  /* Backspace */
680         Eia608Erase( h );
681         b_changed = true;
682         break;
683     case 0x22:  /* Reserved */
684     case 0x23:
685         break;
686     case 0x24:  /* Delete to end of row */
687         Eia608EraseToEndOfRow( h );
688         break;
689     case 0x25:  /* Rollup 2 */
690     case 0x26:  /* Rollup 3 */
691     case 0x27:  /* Rollup 4 */
692         if( h->mode == EIA608_MODE_POPUP || h->mode == EIA608_MODE_PAINTON )
693         {
694             Eia608EraseScreen( h, true );
695             Eia608EraseScreen( h, false );
696             b_changed = true;
697         }
698
699         if( d2 == 0x25 )
700             h->mode = EIA608_MODE_ROLLUP_2;
701         else if( d2 == 0x26 )
702             h->mode = EIA608_MODE_ROLLUP_3;
703         else
704             h->mode = EIA608_MODE_ROLLUP_4;
705
706         h->cursor.i_column = 0;
707         h->cursor.i_row = h->i_row_rollup;
708         break;
709     case 0x28:  /* Flash on */
710         /* TODO */
711         break;
712     case 0x29:  /* Resume direct captionning */
713         h->mode = EIA608_MODE_PAINTON;
714         break;
715     case 0x2a:  /* Text restart */
716         /* TODO */
717         break;
718
719     case 0x2b: /* Resume text display */
720         h->mode = EIA608_MODE_TEXT;
721         break;
722
723     case 0x2c: /* Erase displayed memory */
724         Eia608EraseScreen( h, true );
725         b_changed = true;
726         break;
727     case 0x2d: /* Carriage return */
728         Eia608RollUp(h);
729         b_changed = true;
730         break;
731     case 0x2e: /* Erase non displayed memory */
732         Eia608EraseScreen( h, false );
733         break;
734     case 0x2f: /* End of caption (flip screen if not paint on) */
735         if( h->mode != EIA608_MODE_PAINTON )
736             h->i_screen = 1 - h->i_screen;
737         h->mode = EIA608_MODE_POPUP;
738         h->cursor.i_column = 0;
739         h->cursor.i_row = 0;
740         h->color = EIA608_COLOR_DEFAULT;
741         h->font = EIA608_FONT_REGULAR;
742         b_changed = true;
743         break;
744     }
745     return b_changed;
746 }
747 static bool Eia608ParseCommand0x17( eia608_t *h, uint8_t d2 )
748 {
749     switch( d2 )
750     {
751     case 0x21:  /* Tab offset 1 */
752         Eia608Cursor( h, 1 );
753         break;
754     case 0x22:  /* Tab offset 2 */
755         Eia608Cursor( h, 2 );
756         break;
757     case 0x23:  /* Tab offset 3 */
758         Eia608Cursor( h, 3 );
759         break;
760     }
761     return false;
762 }
763 static bool Eia608ParsePac( eia608_t *h, uint8_t d1, uint8_t d2 )
764 {
765     static const int pi_row[] = {
766         11, -1, 1, 2, 3, 4, 12, 13, 14, 15, 5, 6, 7, 8, 9, 10
767     };
768     const int i_row_index = ( (d1<<1) & 0x0e) | ( (d2>>5) & 0x01 );
769
770     assert( d2 >= 0x40 && d2 <= 0x7f );
771
772     if( pi_row[i_row_index] <= 0 )
773         return false;
774
775     /* Row */
776     if( h->mode != EIA608_MODE_TEXT )
777         h->cursor.i_row = pi_row[i_row_index] - 1;
778     h->i_row_rollup = pi_row[i_row_index] - 1;
779     /* Column */
780     if( d2 >= 0x60 )
781         d2 -= 0x60;
782     else if( d2 >= 0x40 )
783         d2 -= 0x40;
784     h->cursor.i_column = pac2_attribs[d2].i_column;
785     return false;
786 }
787
788 static bool Eia608ParseData( eia608_t *h, uint8_t d1, uint8_t d2 )
789 {
790     bool b_changed = false;
791
792     if( d1 >= 0x18 && d1 <= 0x1f )
793         d1 -= 8;
794
795 #define ON( d2min, d2max, cmd ) do { if( d2 >= d2min && d2 <= d2max ) b_changed = cmd; } while(0)
796     switch( d1 )
797     {
798     case 0x11:
799         ON( 0x20, 0x2f, Eia608ParseTextAttribute( h, d2 ) );
800         ON( 0x30, 0x3f, Eia608ParseDouble( h, d2 ) );
801         break;
802     case 0x12: case 0x13:
803         ON( 0x20, 0x3f, Eia608ParseExtended( h, d1, d2 ) );
804         break;
805     case 0x14: case 0x15:
806         ON( 0x20, 0x2f, Eia608ParseCommand0x14( h, d2 ) );
807         break;
808     case 0x17:
809         ON( 0x21, 0x22, Eia608ParseCommand0x17( h, d2 ) );
810         ON( 0x2e, 0x2f, Eia608ParseTextAttribute( h, d2 ) );
811         break;
812     }
813     if( d1 == 0x10 )
814         ON( 0x40, 0x5f, Eia608ParsePac( h, d1, d2 ) );
815     else if( d1 >= 0x11 && d1 <= 0x17 )
816         ON( 0x40, 0x7f, Eia608ParsePac( h, d1, d2 ) );
817 #undef ON
818     if( d1 >= 0x20 )
819     {
820         b_changed = Eia608ParseSingle( h, d1 );
821         if( d2 >= 0x20 )
822             b_changed |= Eia608ParseSingle( h, d2 );
823     }
824     return b_changed;
825 }
826
827 static void Eia608TextUtf8( char *psz_utf8, uint8_t c ) // Returns number of bytes used
828 {
829 #define E1(c,u) { c, { u, '\0' } }
830 #define E2(c,u1,u2) { c, { u1, u2, '\0' } }
831 #define E3(c,u1,u2,u3) { c, { u1, u2, u3, '\0' } }
832     static const struct {
833         uint8_t c;
834         char utf8[3+1];
835     } c2utf8[] = {
836         // Regular line-21 character set, mostly ASCII except these exceptions
837         E2( 0x2a, 0xc3,0xa1), // lowercase a, acute accent
838         E2( 0x5c, 0xc3,0xa9), // lowercase e, acute accent
839         E2( 0x5e, 0xc3,0xad), // lowercase i, acute accent
840         E2( 0x5f, 0xc3,0xb3), // lowercase o, acute accent
841         E2( 0x60, 0xc3,0xba), // lowercase u, acute accent
842         E2( 0x7b, 0xc3,0xa7), // lowercase c with cedilla
843         E2( 0x7c, 0xc3,0xb7), // division symbol
844         E2( 0x7d, 0xc3,0x91), // uppercase N tilde
845         E2( 0x7e, 0xc3,0xb1), // lowercase n tilde
846         // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
847         // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
848         E2( 0x80, 0xc2,0xae), // Registered symbol (R)
849         E2( 0x81, 0xc2,0xb0), // degree sign
850         E2( 0x82, 0xc2,0xbd), // 1/2 symbol
851         E2( 0x83, 0xc2,0xbf), // Inverted (open) question mark
852         E3( 0x84, 0xe2,0x84,0xa2), // Trademark symbol (TM)
853         E2( 0x85, 0xc2,0xa2), // Cents symbol
854         E2( 0x86, 0xc2,0xa3), // Pounds sterling
855         E3( 0x87, 0xe2,0x99,0xaa), // Music note
856         E2( 0x88, 0xc3,0xa0), // lowercase a, grave accent
857         E1( 0x89, 0x20), // transparent space, we make it regular
858         E2( 0x8a, 0xc3,0xa8), // lowercase e, grave accent
859         E2( 0x8b, 0xc3,0xa2), // lowercase a, circumflex accent
860         E2( 0x8c, 0xc3,0xaa), // lowercase e, circumflex accent
861         E2( 0x8d, 0xc3,0xae), // lowercase i, circumflex accent
862         E2( 0x8e, 0xc3,0xb4), // lowercase o, circumflex accent
863         E2( 0x8f, 0xc3,0xbb), // lowercase u, circumflex accent
864         // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
865         // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
866         E2( 0x90, 0xc3,0x81), // capital letter A with acute
867         E2( 0x91, 0xc3,0x89), // capital letter E with acute
868         E2( 0x92, 0xc3,0x93), // capital letter O with acute
869         E2( 0x93, 0xc3,0x9a), // capital letter U with acute
870         E2( 0x94, 0xc3,0x9c), // capital letter U with diaresis
871         E2( 0x95, 0xc3,0xbc), // lowercase letter U with diaeresis
872         E1( 0x96, 0x27), // apostrophe
873         E2( 0x97, 0xc1,0xa1), // inverted exclamation mark
874         E1( 0x98, 0x2a), // asterisk
875         E1( 0x99, 0x27), // apostrophe (yes, duped). See CCADI source code.
876         E1( 0x9a, 0x2d), // hyphen-minus
877         E2( 0x9b, 0xc2,0xa9), // copyright sign
878         E3( 0x9c, 0xe2,0x84,0xa0), // Service mark
879         E1( 0x9d, 0x2e), // Full stop (.)
880         E1( 0x9e, 0x22), // Quoatation mark
881         E1( 0x9f, 0x22), // Quoatation mark
882         E2( 0xa0, 0xc3,0x80), // uppercase A, grave accent
883         E2( 0xa1, 0xc3,0x82), // uppercase A, circumflex
884         E2( 0xa2, 0xc3,0x87), // uppercase C with cedilla
885         E2( 0xa3, 0xc3,0x88), // uppercase E, grave accent
886         E2( 0xa4, 0xc3,0x8a), // uppercase E, circumflex
887         E2( 0xa5, 0xc3,0x8b), // capital letter E with diaresis
888         E2( 0xa6, 0xc3,0xab), // lowercase letter e with diaresis
889         E2( 0xa7, 0xc3,0x8e), // uppercase I, circumflex
890         E2( 0xa8, 0xc3,0x8f), // uppercase I, with diaresis
891         E2( 0xa9, 0xc3,0xaf), // lowercase i, with diaresis
892         E2( 0xaa, 0xc3,0x94), // uppercase O, circumflex
893         E2( 0xab, 0xc3,0x99), // uppercase U, grave accent
894         E2( 0xac, 0xc3,0xb9), // lowercase u, grave accent
895         E2( 0xad, 0xc3,0x9b), // uppercase U, circumflex
896         E2( 0xae, 0xc2,0xab), // LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
897         E2( 0xaf, 0xc2,0xbb), // RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
898         // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
899         // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
900         E2( 0xb0, 0xc3,0x83), // Uppercase A, tilde
901         E2( 0xb1, 0xc3,0xa3), // Lowercase a, tilde
902         E2( 0xb2, 0xc3,0x8d), // Uppercase I, acute accent
903         E2( 0xb3, 0xc3,0x8c), // Uppercase I, grave accent
904         E2( 0xb4, 0xc3,0xac), // Lowercase i, grave accent
905         E2( 0xb5, 0xc3,0x92), // Uppercase O, grave accent
906         E2( 0xb6, 0xc3,0xb2), // Lowercase o, grave accent
907         E2( 0xb7, 0xc3,0x95), // Uppercase O, tilde
908         E2( 0xb8, 0xc3,0xb5), // Lowercase o, tilde
909         E1( 0xb9, 0x7b), // Open curly brace
910         E1( 0xba, 0x7d), // Closing curly brace
911         E1( 0xbb, 0x5c), // Backslash
912         E1( 0xbc, 0x5e), // Caret
913         E1( 0xbd, 0x5f), // Underscore
914         E2( 0xbe, 0xc2,0xa6), // Pipe (broken bar)
915         E1( 0xbf, 0x7e), // Tilde (utf8 code unsure)
916         E2( 0xc0, 0xc3,0x84), // Uppercase A, umlaut
917         E2( 0xc1, 0xc3,0xa4), // Lowercase A, umlaut
918         E2( 0xc2, 0xc3,0x96), // Uppercase O, umlaut
919         E2( 0xc3, 0xc3,0xb6), // Lowercase o, umlaut
920         E2( 0xc4, 0xc3,0x9f), // Esszett (sharp S)
921         E2( 0xc5, 0xc2,0xa5), // Yen symbol
922         E2( 0xc6, 0xc2,0xa4), // Currency symbol
923         E1( 0xc7, 0x7c), // Vertical bar
924         E2( 0xc8, 0xc3,0x85), // Uppercase A, ring
925         E2( 0xc9, 0xc3,0xa5), // Lowercase A, ring
926         E2( 0xca, 0xc3,0x98), // Uppercase O, slash
927         E2( 0xcb, 0xc3,0xb8), // Lowercase o, slash
928         E3( 0xcc, 0xe2,0x8c,0x9c), // Upper left corner
929         E3( 0xcd, 0xe2,0x8c,0x9d), // Upper right corner
930         E3( 0xce, 0xe2,0x8c,0x9e), // Lower left corner
931         E3( 0xcf, 0xe2,0x8c,0x9f), // Lower right corner
932
933         E1(0,0)
934     };
935 #undef E3
936 #undef E2
937 #undef E1
938
939     static const int i_c2utf8 = sizeof(c2utf8)/sizeof(*c2utf8);
940     int i;
941
942     for( i = 0; i < i_c2utf8; i++ )
943     {
944         if( c2utf8[i].c == c )
945             break;
946     }
947     if( i >= i_c2utf8 )
948     {
949         psz_utf8[0] = c < 0x80 ? c : '?';   /* Normal : Unsupported */
950         psz_utf8[1] = '\0';
951     }
952     else
953     {
954         strcpy( psz_utf8, c2utf8[i].utf8 );
955     }
956 }
957
958 static void Eia608Strlcat( char *d, const char *s, int i_max )
959 {
960     if( i_max > 1 )
961         strncat( d, s, i_max-1 - strnlen(d, i_max-1));
962     if( i_max > 0 )
963         d[i_max-1] = '\0';
964 }
965
966 static void Eia608TextLine( struct eia608_screen *screen, char *psz_text, int i_text_max, int i_row, bool b_html )
967 {
968     const uint8_t *p_char = screen->characters[i_row];
969     const eia608_color_t *p_color = screen->colors[i_row];
970     const eia608_font_t *p_font = screen->fonts[i_row];
971     int i_start;
972     int i_end;
973     int x;
974     eia608_color_t last_color = EIA608_COLOR_DEFAULT;
975     bool     b_last_italics = false;
976     bool     b_last_underline = false;
977
978     /* Search the start */
979     i_start = 0;
980     while( i_start < EIA608_SCREEN_COLUMNS-1 && p_char[i_start] == ' ' )
981         i_start++;
982
983     /* Search the end */
984     i_end = EIA608_SCREEN_COLUMNS-1;
985     while( i_end > i_start && p_char[i_end] == ' ' )
986         i_end--;
987
988     /* */
989 #define CAT(t) Eia608Strlcat( psz_text, t, i_text_max )
990     for( x = i_start; x <= i_end; x++ )
991     {
992         eia608_color_t color = p_color[x];
993         bool b_italics = p_font[x] & EIA608_FONT_ITALICS;
994         bool b_underline = p_font[x] & EIA608_FONT_UNDERLINE;
995         char utf8[4];
996
997         /* */
998         if( b_html )
999         {
1000             bool b_close_color, b_close_italics, b_close_underline;
1001
1002             /* We create the tags font / i / u in that orders */
1003             b_close_color = color != last_color && last_color != EIA608_COLOR_DEFAULT;
1004             b_close_italics = !b_italics && b_last_italics;
1005             b_close_underline = !b_underline && b_last_underline;
1006
1007             /* Be sure to create valid html */
1008             b_close_italics |= b_last_italics && b_close_color;
1009             b_close_underline = b_last_underline && ( b_close_italics || b_close_color );
1010
1011             if( b_close_underline )
1012                 CAT( "</u>" );
1013             if( b_close_italics )
1014                 CAT( "</i>" );
1015             if( b_close_color )
1016                 CAT( "</font>" );
1017
1018             if( color != EIA608_COLOR_DEFAULT && color != last_color)
1019             {
1020                 static const char *ppsz_color[] = {
1021                     "#ffffff",  // white
1022                     "#00ff00",  // green
1023                     "#0000ff",  // blue
1024                     "#00ffff",  // cyan
1025                     "#ff0000",  // red
1026                     "#ffff00",  // yellow
1027                     "#ff00ff",  // magenta
1028                     "#ffffff",  // user defined XXX we use white
1029                 };
1030                 CAT( "<font color=" );
1031                 CAT( ppsz_color[color] );
1032                 CAT( ">" );
1033             }
1034             if( ( b_close_italics && b_italics ) || ( b_italics && !b_last_italics ) )
1035                 CAT( "<i>" );
1036             if( ( b_close_underline && b_underline ) || ( b_underline && !b_last_underline ) )
1037                 CAT( "<u>" );
1038         }
1039
1040         /* */ 
1041         Eia608TextUtf8( utf8, p_char[x] );
1042         CAT( utf8 );
1043
1044         /* */
1045         b_last_underline = b_underline;
1046         b_last_italics = b_italics;
1047         last_color = color;
1048     }
1049     if( b_html )
1050     {
1051         if( b_last_underline )
1052             CAT( "</u>" );
1053         if( b_last_italics )
1054             CAT( "</i>" );
1055         if( last_color != EIA608_COLOR_DEFAULT )
1056             CAT( "</font>" );
1057     }
1058 #undef CAT
1059 }
1060
1061 /* */
1062 static void Eia608Init( eia608_t *h )
1063 {
1064     memset( h, 0, sizeof(*h) );
1065
1066     /* */
1067     h->i_channel = -1;
1068
1069     h->i_screen = 0;
1070     Eia608ClearScreen( h, 0 );
1071     Eia608ClearScreen( h, 1 );
1072
1073     /* Cursor for writing text */
1074     h->cursor.i_column = 0;
1075     h->cursor.i_row = 0;
1076
1077     h->last.d1 = 0x00;
1078     h->last.d2 = 0x00;
1079     h->mode = EIA608_MODE_POPUP;
1080     h->color = EIA608_COLOR_DEFAULT;
1081     h->font = EIA608_FONT_REGULAR;
1082     h->i_row_rollup = EIA608_SCREEN_ROWS-1;
1083 }
1084 static bool Eia608Parse( eia608_t *h, int i_channel_selected, const uint8_t data[2] )
1085 {
1086     const uint8_t d1 = data[0] & 0x7f; /* Removed parity bit */
1087     const uint8_t d2 = data[1] & 0x7f;
1088     bool b_screen_changed = false;
1089
1090     if( d1 == 0 && d2 == 0 )
1091         return false;   /* Ignore padding (parity check are sometimes invalid on them) */
1092
1093     Eia608ParseChannel( h, data );
1094     if( h->i_channel != i_channel_selected )
1095         return false;
1096     //fprintf( stderr, "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC %x %x\n", data[0], data[1] );
1097
1098     if( d1 >= 0x10 )
1099     {
1100         if( d1 >= 0x20 ||
1101             d1 != h->last.d1 || d2 != h->last.d2 ) /* Command codes can be repeated */
1102             b_screen_changed = Eia608ParseData( h, d1,d2 );
1103
1104         h->last.d1 = d1;
1105         h->last.d2 = d2;
1106     }
1107     else if( ( d1 >= 0x01 && d1 <= 0x0E ) || d1 == 0x0F )
1108     {
1109         /* XDS block / End of XDS block */
1110     }
1111     return b_screen_changed;
1112 }
1113
1114 static char *Eia608Text( eia608_t *h, bool b_html )
1115 {
1116     const int i_size = EIA608_SCREEN_ROWS * 3 * EIA608_SCREEN_COLUMNS+1;
1117     struct eia608_screen *screen = &h->screen[h->i_screen];
1118     bool b_first = true;
1119     char *psz;
1120     int i;
1121
1122     /* We allocate a buffer big enough for normal case */
1123     psz = malloc( i_size );
1124     if( !psz )
1125         return NULL;
1126     *psz = '\0';
1127     if( b_html )
1128         Eia608Strlcat( psz, "<text>", i_size );
1129     for( i = 0; i < EIA608_SCREEN_ROWS; i++ )
1130     {
1131         if( !screen->row_used[i] )
1132             continue;
1133
1134         if( !b_first )
1135             Eia608Strlcat( psz, b_html ? "<br />" : "\n", i_size );
1136         b_first = false;
1137
1138         Eia608TextLine( screen, psz, i_size, i, b_html );
1139     }
1140     if( b_html )
1141         Eia608Strlcat( psz, "</text>", i_size );
1142     return psz;
1143 }
1144
1145 static void Eia608Exit( eia608_t *h )
1146 {
1147 }
1148