]> git.sesse.net Git - vlc/blob - src/spu_decoder/spu_decoder.c
* Added support for some terribly braindead DVD subtitles in Kenshin
[vlc] / src / spu_decoder / spu_decoder.c
1 /*****************************************************************************
2  * spu_decoder.c : spu decoder thread
3  *****************************************************************************
4  * Copyright (C) 2000 VideoLAN
5  * $Id: spu_decoder.c,v 1.42 2001/05/07 04:42:42 sam Exp $
6  *
7  * Authors: Samuel Hocevar <sam@zoy.org>
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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include "defs.h"
28
29 #include <unistd.h>                                              /* getpid() */
30 #ifdef WIN32                   /* getpid() for win32 is located in process.h */
31 #include <process.h>
32 #endif
33
34 #include <stdlib.h>                                      /* malloc(), free() */
35 #include <string.h>                                    /* memcpy(), memset() */
36
37 #include "config.h"
38 #include "common.h"
39 #include "threads.h"
40 #include "mtime.h"
41
42 #include "intf_msg.h"
43
44 #include "stream_control.h"
45 #include "input_ext-dec.h"
46
47 #include "video.h"
48 #include "video_output.h"
49
50 #include "spu_decoder.h"
51
52 /*****************************************************************************
53  * Local prototypes
54  *****************************************************************************/
55 static int  InitThread  ( spudec_thread_t * );
56 static void RunThread   ( spudec_thread_t * );
57 static void ErrorThread ( spudec_thread_t * );
58 static void EndThread   ( spudec_thread_t * );
59
60 static int  SyncPacket           ( spudec_thread_t * );
61 static void ParsePacket          ( spudec_thread_t * );
62 static int  ParseControlSequences( spudec_thread_t *, subpicture_t * );
63 static int  ParseRLE             ( u8 *,              subpicture_t * );
64
65 /*****************************************************************************
66  * spudec_CreateThread: create a spu decoder thread
67  *****************************************************************************/
68 vlc_thread_t spudec_CreateThread( vdec_config_t * p_config )
69 {
70     spudec_thread_t *     p_spudec;
71
72     /* Allocate the memory needed to store the thread's structure */
73     p_spudec = (spudec_thread_t *)malloc( sizeof(spudec_thread_t) );
74
75     if ( p_spudec == NULL )
76     {
77         intf_ErrMsg( "spudec error: not enough memory "
78                      "for spudec_CreateThread() to create the new thread" );
79         return( 0 );
80     }
81
82     /*
83      * Initialize the thread properties
84      */
85     p_spudec->p_config = p_config;
86
87     p_spudec->p_fifo = p_config->decoder_config.p_decoder_fifo;
88
89     /* Spawn a video output if there is none */
90     vlc_mutex_lock( &p_vout_bank->lock );
91
92     if( p_vout_bank->i_count == 0 )
93     {
94         intf_WarnMsg( 1, "spudec: no vout present, spawning one" );
95
96         p_spudec->p_vout = vout_CreateThread( NULL );
97
98         /* Everything failed */
99         if( p_spudec->p_vout == NULL )
100         {
101             intf_Msg( "spudec: can't open vout, aborting" );
102             vlc_mutex_unlock( &p_vout_bank->lock );
103             free( p_spudec );
104
105             return 0;
106         }
107
108         p_vout_bank->pp_vout[ p_vout_bank->i_count ] = p_spudec->p_vout;
109         p_vout_bank->i_count++;
110     }
111     else
112     {
113         /* Take the first video output FIXME: take the best one */
114         p_spudec->p_vout = p_vout_bank->pp_vout[ 0 ];
115     }
116
117     vlc_mutex_unlock( &p_vout_bank->lock );
118
119     /* Spawn the spu decoder thread */
120     if ( vlc_thread_create(&p_spudec->thread_id, "spu decoder",
121          (vlc_thread_func_t)RunThread, (void *)p_spudec) )
122     {
123         intf_ErrMsg( "spudec error: can't spawn spu decoder thread" );
124         free( p_spudec );
125         return 0;
126     }
127
128     return( p_spudec->thread_id );
129 }
130
131 /* following functions are local */
132
133 /*****************************************************************************
134  * InitThread: initialize spu decoder thread
135  *****************************************************************************
136  * This function is called from RunThread and performs the second step of the
137  * initialization. It returns 0 on success. Note that the thread's flag are not
138  * modified inside this function.
139  *****************************************************************************/
140 static int InitThread( spudec_thread_t *p_spudec )
141 {
142     p_spudec->p_config->decoder_config.pf_init_bit_stream(
143             &p_spudec->bit_stream,
144             p_spudec->p_config->decoder_config.p_decoder_fifo, NULL, NULL );
145
146     /* Mark thread as running and return */
147     return( 0 );
148 }
149
150 /*****************************************************************************
151  * RunThread: spu decoder thread
152  *****************************************************************************
153  * spu decoder thread. This function only returns when the thread is
154  * terminated.
155  *****************************************************************************/
156 static void RunThread( spudec_thread_t *p_spudec )
157 {
158     intf_WarnMsg( 3, "spudec: spu decoder thread %i spawned", getpid() );
159
160     /*
161      * Initialize thread and free configuration
162      */
163     p_spudec->p_fifo->b_error = InitThread( p_spudec );
164
165     /*
166      * Main loop - it is not executed if an error occured during
167      * initialization
168      */
169     while( (!p_spudec->p_fifo->b_die) && (!p_spudec->p_fifo->b_error) )
170     {
171         if( !SyncPacket( p_spudec ) )
172         {
173             ParsePacket( p_spudec );
174         }
175     }
176
177     /*
178      * Error loop
179      */
180     if( p_spudec->p_fifo->b_error )
181     {
182         ErrorThread( p_spudec );
183     }
184
185     /* End of thread */
186     intf_WarnMsg( 3, "spudec: destroying spu decoder thread %i", getpid() );
187     EndThread( p_spudec );
188 }
189
190 /*****************************************************************************
191  * ErrorThread: RunThread() error loop
192  *****************************************************************************
193  * This function is called when an error occured during thread main's loop. The
194  * thread can still receive feed, but must be ready to terminate as soon as
195  * possible.
196  *****************************************************************************/
197 static void ErrorThread( spudec_thread_t *p_spudec )
198 {
199     /* We take the lock, because we are going to read/write the start/end
200      * indexes of the decoder fifo */
201     vlc_mutex_lock( &p_spudec->p_fifo->data_lock );
202
203     /* Wait until a `die' order is sent */
204     while( !p_spudec->p_fifo->b_die )
205     {
206         /* Trash all received PES packets */
207         while( !DECODER_FIFO_ISEMPTY(*p_spudec->p_fifo) )
208         {
209             p_spudec->p_fifo->pf_delete_pes( p_spudec->p_fifo->p_packets_mgt,
210                     DECODER_FIFO_START(*p_spudec->p_fifo) );
211             DECODER_FIFO_INCSTART( *p_spudec->p_fifo );
212         }
213
214         /* Waiting for the input thread to put new PES packets in the fifo */
215         vlc_cond_wait( &p_spudec->p_fifo->data_wait,
216                        &p_spudec->p_fifo->data_lock );
217     }
218
219     /* We can release the lock before leaving */
220     vlc_mutex_unlock( &p_spudec->p_fifo->data_lock );
221 }
222
223 /*****************************************************************************
224  * EndThread: thread destruction
225  *****************************************************************************
226  * This function is called when the thread ends after a sucessful
227  * initialization.
228  *****************************************************************************/
229 static void EndThread( spudec_thread_t *p_spudec )
230 {
231     free( p_spudec->p_config );
232     free( p_spudec );
233 }
234
235 /*****************************************************************************
236  * SyncPacket: get in sync with the stream
237  *****************************************************************************
238  * This function makes a few sanity checks and returns 0 if it looks like we
239  * are at the beginning of a subpicture packet.
240  *****************************************************************************/
241 static int SyncPacket( spudec_thread_t *p_spudec )
242 {
243     /* Re-align the buffer on an 8-bit boundary */
244     RealignBits( &p_spudec->bit_stream );
245
246     /* The total SPU packet size, often bigger than a PS packet */
247     p_spudec->i_spu_size = GetBits( &p_spudec->bit_stream, 16 );
248
249     /* The RLE stuff size (remove 4 because we just read 32 bits) */
250     p_spudec->i_rle_size = ShowBits( &p_spudec->bit_stream, 16 ) - 4;
251
252     /* If the values we got are a bit strange, skip packet */
253     if( p_spudec->i_rle_size >= p_spudec->i_spu_size )
254     {
255         return( 1 );
256     }
257
258     RemoveBits( &p_spudec->bit_stream, 16 );
259
260     return( 0 );
261 }
262
263 /*****************************************************************************
264  * ParsePacket: parse an SPU packet and send it to the video output
265  *****************************************************************************
266  * This function parses the SPU packet and, if valid, sends it to the
267  * video output.
268  *****************************************************************************/
269 static void ParsePacket( spudec_thread_t *p_spudec )
270 {
271     subpicture_t * p_spu;
272     u8           * p_src;
273
274     intf_WarnMsg( 3, "spudec: trying to gather a 0x%.2x long subtitle",
275                   p_spudec->i_spu_size );
276
277     /* We cannot display a subpicture with no date */
278     if( DECODER_FIFO_START(*p_spudec->p_fifo)->i_pts == 0 )
279     {
280         intf_WarnMsg( 3, "spudec error: subtitle without a date" );
281         return;
282     }
283
284     /* Allocate the subpicture internal data. */
285     p_spu = vout_CreateSubPicture( p_spudec->p_vout, DVD_SUBPICTURE,
286                                    p_spudec->i_rle_size * 4 );
287     /* Rationale for the "p_spudec->i_rle_size * 4": we are going to
288      * expand the RLE stuff so that we won't need to read nibbles later
289      * on. This will speed things up a lot. Plus, we'll only need to do
290      * this stupid interlacing stuff once. */
291
292     if( p_spu == NULL )
293     {
294         return;
295     }
296
297     /* Get display time now. If we do it later, we may miss the PTS. */
298     p_spudec->i_pts = DECODER_FIFO_START(*p_spudec->p_fifo)->i_pts;
299
300     /* Allocate the temporary buffer we will parse */
301     p_src = malloc( p_spudec->i_rle_size );
302
303     if( p_src == NULL )
304     {
305         intf_ErrMsg( "spudec error: could not allocate p_src" );
306         vout_DestroySubPicture( p_spudec->p_vout, p_spu );
307         return;
308     }
309
310     /* Get RLE data */
311     GetChunk( &p_spudec->bit_stream, p_src, p_spudec->i_rle_size );
312
313 #if 0
314     /* Dump the subtitle info */
315     intf_WarnHexDump( 5, p_spu->p_data, p_spudec->i_rle_size );
316 #endif
317
318     /* Getting the control part */
319     if( ParseControlSequences( p_spudec, p_spu ) )
320     {
321         /* There was a parse error, delete the subpicture */
322         free( p_src );
323         vout_DestroySubPicture( p_spudec->p_vout, p_spu );
324         return;
325     }
326
327     if( ParseRLE( p_src, p_spu ) )
328     {
329         /* There was a parse error, delete the subpicture */
330         free( p_src );
331         vout_DestroySubPicture( p_spudec->p_vout, p_spu );
332         return;
333     }
334
335     intf_WarnMsg( 3, "spudec: valid subtitle, size: %ix%i, position: %i,%i",
336                   p_spu->i_width, p_spu->i_height, p_spu->i_x, p_spu->i_y );
337                      
338     intf_WarnMsg( 3, "spudec: total size: 0x%x, RLE offsets: 0x%x 0x%x",
339                   p_spudec->i_spu_size,
340                   p_spu->type.spu.i_offset[0], p_spu->type.spu.i_offset[1] );
341
342     /* SPU is finished - we can ask the video output to display it */
343     vout_DisplaySubPicture( p_spudec->p_vout, p_spu );
344
345     /* Clean up */
346     free( p_src );
347 }
348
349 /*****************************************************************************
350  * ParseControlSequences: parse all SPU control sequences
351  *****************************************************************************
352  * This is the most important part in SPU decoding. We get dates, palette
353  * information, coordinates, and so on. For more information on the
354  * subtitles format, see http://sam.zoy.org/doc/dvd/subtitles/index.html
355  *****************************************************************************/
356 static int ParseControlSequences( spudec_thread_t *p_spudec,
357                                   subpicture_t * p_spu )
358 {
359     /* Our current index in the SPU packet */
360     int i_index = p_spudec->i_rle_size + 4;
361
362     /* The next start-of-control-sequence index and the previous one */
363     int i_next_seq, i_cur_seq;
364
365     /* Command time and date */
366     u8  i_command;
367     int i_date;
368
369     /* Initialize the structure */
370     p_spu->i_start = p_spu->i_stop = 0;
371     p_spu->b_ephemer = 0;
372
373     do
374     {
375         /* Get the control sequence date */
376         i_date = GetBits( &p_spudec->bit_stream, 16 );
377  
378         /* Next offset */
379         i_cur_seq = i_index;
380         i_next_seq = GetBits( &p_spudec->bit_stream, 16 );
381  
382         /* Skip what we just read */
383         i_index += 4;
384  
385         do
386         {
387             i_command = GetBits( &p_spudec->bit_stream, 8 );
388             i_index++;
389  
390             switch( i_command )
391             {
392                 case SPU_CMD_FORCE_DISPLAY:
393
394                     /* 00 (force displaying) */
395                     intf_ErrMsg( "spudec: \"force display\" command" );
396                     intf_ErrMsg( "spudec: send mail to <sam@zoy.org> if you "
397                                          "want to help debugging this" );
398  
399                     break;
400  
401                 /* Convert the dates in seconds to PTS values */
402                 case SPU_CMD_START_DISPLAY:
403  
404                     /* 01 (start displaying) */
405                     p_spu->i_start = p_spudec->i_pts + ( i_date * 11000 );
406  
407                     break;
408  
409                 case SPU_CMD_STOP_DISPLAY:
410  
411                     /* 02 (stop displaying) */
412                     p_spu->i_stop = p_spudec->i_pts + ( i_date * 11000 );
413  
414                     break;
415  
416                 case SPU_CMD_SET_PALETTE:
417  
418                     /* 03xxxx (palette) - trashed */
419                     RemoveBits( &p_spudec->bit_stream, 16 );
420                     i_index += 2;
421  
422                     break;
423  
424                 case SPU_CMD_SET_ALPHACHANNEL:
425  
426                     /* 04xxxx (alpha channel) - trashed */
427                     RemoveBits( &p_spudec->bit_stream, 16 );
428                     i_index += 2;
429  
430                     break;
431  
432                 case SPU_CMD_SET_COORDINATES:
433  
434                     /* 05xxxyyyxxxyyy (coordinates) */
435                     p_spu->i_x = GetBits( &p_spudec->bit_stream, 12 );
436                     p_spu->i_width = GetBits( &p_spudec->bit_stream, 12 )
437                                       - p_spu->i_x + 1;
438  
439                     p_spu->i_y = GetBits( &p_spudec->bit_stream, 12 );
440                     p_spu->i_height = GetBits( &p_spudec->bit_stream, 12 )
441                                        - p_spu->i_y + 1;
442  
443                     i_index += 6;
444  
445                     break;
446  
447                 case SPU_CMD_SET_OFFSETS:
448  
449                     /* 06xxxxyyyy (byte offsets) */
450                     p_spu->type.spu.i_offset[0] =
451                         GetBits( &p_spudec->bit_stream, 16 ) - 4;
452  
453                     p_spu->type.spu.i_offset[1] =
454                         GetBits( &p_spudec->bit_stream, 16 ) - 4;
455  
456                     i_index += 4;
457  
458                     break;
459  
460                 case SPU_CMD_END:
461  
462                     /* ff (end) */
463                     break;
464  
465                 default:
466  
467                     /* xx (unknown command) */
468                     intf_ErrMsg( "spudec error: unknown command 0x%.2x",
469                                  i_command );
470                     return( 1 );
471             }
472
473         } while( i_command != SPU_CMD_END );
474
475     } while( i_index == i_next_seq );
476
477     /* Check that the next sequence index matches the current one */
478     if( i_next_seq != i_cur_seq )
479     {
480         intf_ErrMsg( "spudec error: index mismatch (0x%.4x != 0x%.4x)",
481                      i_next_seq, i_cur_seq );
482         return( 1 );
483     }
484
485     if( i_index > p_spudec->i_spu_size )
486     {
487         intf_ErrMsg( "spudec error: uh-oh, we went too far (0x%.4x > 0x%.4x)",
488                      i_index, p_spudec->i_spu_size );
489         return( 1 );
490     }
491
492     if( !p_spu->i_start )
493     {
494         intf_ErrMsg( "spudec error: no `start display' command" );
495     }
496
497     if( !p_spu->i_stop )
498     {
499         /* This subtitle will live for 5 seconds or until the next subtitle */
500         p_spu->i_stop = p_spu->i_start + 500 * 11000;
501         p_spu->b_ephemer = 1;
502     }
503
504     /* Get rid of padding bytes */
505     switch( p_spudec->i_spu_size - i_index )
506     {
507         case 1:
508             RemoveBits( &p_spudec->bit_stream, 8 );
509             i_index++;
510         case 0:
511             /* Zero or one padding byte, quite usual */
512             break;
513
514         default:
515
516             /* More than one padding byte - this is very strange, but
517              * we can deal with it */
518             intf_WarnMsg( 2, "spudec warning: %i padding bytes, we usually "
519                              "get 1 or none",
520                           p_spudec->i_spu_size - i_index );
521
522             while( i_index < p_spudec->i_spu_size )
523             {
524                 RemoveBits( &p_spudec->bit_stream, 8 );
525                 i_index++;
526             }
527
528             break;
529     }
530
531     /* Successfully parsed ! */
532     return( 0 );
533 }
534
535 /*****************************************************************************
536  * ParseRLE: parse the RLE part of the subtitle
537  *****************************************************************************
538  * This part parses the subtitle graphical data and stores it in a more
539  * convenient structure for later decoding. For more information on the
540  * subtitles format, see http://sam.zoy.org/doc/dvd/subtitles/index.html
541  *****************************************************************************/
542 static int ParseRLE( u8 *p_src, subpicture_t * p_spu )
543 {
544     unsigned int i_code;
545     unsigned int i_id = 0;
546
547     unsigned int i_width = p_spu->i_width;
548     unsigned int i_height = p_spu->i_height;
549     unsigned int i_x, i_y;
550
551     u16 *p_dest = (u16 *)p_spu->p_data;
552
553     /* The subtitles are interlaced, we need two offsets */
554     unsigned int  pi_table[ 2 ];
555     unsigned int *pi_offset;
556
557     pi_table[ 0 ] = p_spu->type.spu.i_offset[ 0 ] << 1;
558     pi_table[ 1 ] = p_spu->type.spu.i_offset[ 1 ] << 1;
559
560     for( i_y = 0 ; i_y < i_height ; i_y++ )
561     {
562         pi_offset = pi_table + i_id;
563
564         for( i_x = 0 ; i_x < i_width ; i_x += i_code >> 2 )
565         {
566             i_code = AddNibble( 0, p_src, pi_offset );
567
568             if( i_code < 0x04 )
569             {
570                 i_code = AddNibble( i_code, p_src, pi_offset );
571
572                 if( i_code < 0x10 )
573                 {
574                     i_code = AddNibble( i_code, p_src, pi_offset );
575
576                     if( i_code < 0x040 )
577                     {
578                         i_code = AddNibble( i_code, p_src, pi_offset );
579
580                         if( i_code < 0x0100 )
581                         {
582                             /* If the 14 first bits are set to 0, then it's a
583                              * new line. We emulate it. */
584                             if( i_code < 0x0004 )
585                             {
586                                 i_code |= ( i_width - i_x ) << 2;
587                             }
588                             else
589                             {
590                                 /* We have a boo boo ! */
591                                 intf_ErrMsg( "spudec error: unknown RLE code "
592                                              "0x%.4x", i_code );
593                                 return( 1 );
594                             }
595                         }
596                     }
597                 }
598             }
599
600             if( ( (i_code >> 2) + i_x + i_y * i_width ) > i_height * i_width )
601             {
602                 intf_ErrMsg( "spudec error: out of bounds, %i at (%i,%i) is "
603                              "out of %ix%i",
604                              i_code >> 2, i_x, i_y, i_width, i_height);
605                 return( 1 );
606             }
607
608             /* We got a valid code, store it */
609             *p_dest++ = i_code;
610         }
611
612         /* Check that we didn't go too far */
613         if( i_x > i_width )
614         {
615             intf_ErrMsg( "spudec error: i_x overflowed, %i > %i",
616                          i_x, i_width );
617             return( 1 );
618         }
619
620         /* Byte-align the stream */
621         if( *pi_offset & 0x1 )
622         {
623             (*pi_offset)++;
624         }
625
626         /* Swap fields */
627         i_id = ~i_id & 0x1;
628     }
629
630     /* FIXME: we shouldn't need these padding bytes */
631     while( i_y < i_height )
632     {
633         *p_dest++ = i_width << 2;
634         i_y++;
635     }
636
637     return( 0 );
638 }
639