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