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