]> git.sesse.net Git - vlc/blob - plugins/spudec/spu_decoder.c
5a436033a338ab00db045ce4a7bd5ff5ae2cc64a
[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.6 2001/12/30 07:09:56 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 ( probedata_t * );
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->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( probedata_t *p_data )
95 {
96     return ( p_data->i_type == DVD_SPU_ES ) ? 50 : 0;
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     int i_retry = 0;
175
176     /* Spawn a video output if there is none */
177     vlc_mutex_lock( &p_vout_bank->lock );
178
179     while( p_vout_bank->i_count == 0 )
180     {
181         vlc_mutex_unlock( &p_vout_bank->lock );
182
183         if( i_retry++ > 10 )
184         {
185             intf_WarnMsg( 1, "spudec: waited too long for vout, aborting" );
186             free( p_spudec );
187
188             return( -1 );
189         }
190
191         msleep( VOUT_OUTMEM_SLEEP );
192         vlc_mutex_lock( &p_vout_bank->lock );
193     }
194
195     /* Take the first video output FIXME: take the best one */
196     p_spudec->p_vout = p_vout_bank->pp_vout[ 0 ];
197     vlc_mutex_unlock( &p_vout_bank->lock );
198     p_spudec->p_config->pf_init_bit_stream(
199             &p_spudec->bit_stream,
200             p_spudec->p_config->p_decoder_fifo, NULL, NULL );
201
202     /* Mark thread as running and return */
203     return( 0 );
204 }
205
206 /*****************************************************************************
207  * EndThread: thread destruction
208  *****************************************************************************
209  * This function is called when the thread ends after a sucessful
210  * initialization.
211  *****************************************************************************/
212 static void EndThread( spudec_thread_t *p_spudec )
213 {
214     free( p_spudec );
215 }
216
217 /*****************************************************************************
218  * SyncPacket: get in sync with the stream
219  *****************************************************************************
220  * This function makes a few sanity checks and returns 0 if it looks like we
221  * are at the beginning of a subpicture packet.
222  *****************************************************************************/
223 static int SyncPacket( spudec_thread_t *p_spudec )
224 {
225     /* Re-align the buffer on an 8-bit boundary */
226     RealignBits( &p_spudec->bit_stream );
227
228     /* The total SPU packet size, often bigger than a PS packet */
229     p_spudec->i_spu_size = GetBits( &p_spudec->bit_stream, 16 );
230
231     /* The RLE stuff size (remove 4 because we just read 32 bits) */
232     p_spudec->i_rle_size = ShowBits( &p_spudec->bit_stream, 16 ) - 4;
233
234     /* If the values we got are a bit strange, skip packet */
235     if( !p_spudec->i_spu_size
236          || ( p_spudec->i_rle_size >= p_spudec->i_spu_size ) )
237     {
238         return( 1 );
239     }
240
241     RemoveBits( &p_spudec->bit_stream, 16 );
242
243     return( 0 );
244 }
245
246 /*****************************************************************************
247  * ParsePacket: parse an SPU packet and send it to the video output
248  *****************************************************************************
249  * This function parses the SPU packet and, if valid, sends it to the
250  * video output.
251  *****************************************************************************/
252 static void ParsePacket( spudec_thread_t *p_spudec )
253 {
254     subpicture_t * p_spu;
255     u8           * p_src;
256     unsigned int   i_offset;
257
258     intf_WarnMsg( 3, "spudec: trying to gather a 0x%.2x long subtitle",
259                   p_spudec->i_spu_size );
260
261     /* We cannot display a subpicture with no date */
262     if( p_spudec->p_fifo->p_first->i_pts == 0 )
263     {
264         intf_WarnMsg( 3, "spudec error: subtitle without a date" );
265         return;
266     }
267
268     /* Allocate the subpicture internal data. */
269     p_spu = vout_CreateSubPicture( p_spudec->p_vout, DVD_SUBPICTURE,
270                                    p_spudec->i_rle_size * 4 );
271     /* Rationale for the "p_spudec->i_rle_size * 4": we are going to
272      * expand the RLE stuff so that we won't need to read nibbles later
273      * on. This will speed things up a lot. Plus, we'll only need to do
274      * this stupid interlacing stuff once. */
275
276     if( p_spu == NULL )
277     {
278         return;
279     }
280
281     /* Get display time now. If we do it later, we may miss the PTS. */
282     p_spudec->i_pts = p_spudec->p_fifo->p_first->i_pts;
283
284     /* Allocate the temporary buffer we will parse */
285     p_src = malloc( p_spudec->i_rle_size );
286
287     if( p_src == NULL )
288     {
289         intf_ErrMsg( "spudec error: could not allocate p_src" );
290         vout_DestroySubPicture( p_spudec->p_vout, p_spu );
291         return;
292     }
293
294     /* Get RLE data */
295     for( i_offset = 0;
296          i_offset + SPU_CHUNK_SIZE < p_spudec->i_rle_size;
297          i_offset += SPU_CHUNK_SIZE )
298     {
299         GetChunk( &p_spudec->bit_stream, p_src + i_offset, SPU_CHUNK_SIZE );
300
301         /* Abort subtitle parsing if we were requested to stop */
302         if( p_spudec->p_fifo->b_die )
303         {
304             free( p_src );
305             vout_DestroySubPicture( p_spudec->p_vout, p_spu );
306             return;
307         }
308     }
309
310     GetChunk( &p_spudec->bit_stream, p_src + i_offset,
311               p_spudec->i_rle_size - i_offset );
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     /* At this point, no more GetBit() command is needed, so we have all
328      * the data we need to tell whether the subtitle is valid. Thus we
329      * try to display it and we ignore b_die. */
330
331     if( ParseRLE( p_spudec, p_spu, p_src ) )
332     {
333         /* There was a parse error, delete the subpicture */
334         free( p_src );
335         vout_DestroySubPicture( p_spudec->p_vout, p_spu );
336         return;
337     }
338
339     intf_WarnMsg( 3, "spudec: total size: 0x%x, RLE offsets: 0x%x 0x%x",
340                   p_spudec->i_spu_size,
341                   p_spu->type.spu.i_offset[0], p_spu->type.spu.i_offset[1] );
342
343     /* SPU is finished - we can ask the video output to display it */
344     vout_DisplaySubPicture( p_spudec->p_vout, p_spu );
345
346     /* Clean up */
347     free( p_src );
348 }
349
350 /*****************************************************************************
351  * ParseControlSequences: parse all SPU control sequences
352  *****************************************************************************
353  * This is the most important part in SPU decoding. We get dates, palette
354  * information, coordinates, and so on. For more information on the
355  * subtitles format, see http://sam.zoy.org/doc/dvd/subtitles/index.html
356  *****************************************************************************/
357 static int ParseControlSequences( spudec_thread_t *p_spudec,
358                                   subpicture_t * p_spu )
359 {
360     /* Our current index in the SPU packet */
361     int i_index = p_spudec->i_rle_size + 4;
362
363     /* The next start-of-control-sequence index and the previous one */
364     int i_next_seq, i_cur_seq;
365
366     /* Command time and date */
367     u8  i_command;
368     int i_date;
369
370     /* XXX: temporary variables */
371     boolean_t b_force_display = 0;
372
373     /* Initialize the structure */
374     p_spu->i_start = p_spu->i_stop = 0;
375     p_spu->b_ephemer = 0;
376
377     do
378     {
379         /* Get the control sequence date */
380         i_date = GetBits( &p_spudec->bit_stream, 16 );
381  
382         /* Next offset */
383         i_cur_seq = i_index;
384         i_next_seq = GetBits( &p_spudec->bit_stream, 16 );
385  
386         /* Skip what we just read */
387         i_index += 4;
388  
389         do
390         {
391             i_command = GetBits( &p_spudec->bit_stream, 8 );
392             i_index++;
393  
394             switch( i_command )
395             {
396                 case SPU_CMD_FORCE_DISPLAY:
397
398                     /* 00 (force displaying) */
399                     p_spu->i_start = p_spudec->i_pts + ( i_date * 11000 );
400                     b_force_display = 1;
401  
402                     break;
403  
404                 /* Convert the dates in seconds to PTS values */
405                 case SPU_CMD_START_DISPLAY:
406  
407                     /* 01 (start displaying) */
408                     p_spu->i_start = p_spudec->i_pts + ( i_date * 11000 );
409  
410                     break;
411  
412                 case SPU_CMD_STOP_DISPLAY:
413  
414                     /* 02 (stop displaying) */
415                     p_spu->i_stop = p_spudec->i_pts + ( i_date * 11000 );
416  
417                     break;
418  
419                 case SPU_CMD_SET_PALETTE:
420  
421                     /* 03xxxx (palette) - trashed */
422                     RemoveBits( &p_spudec->bit_stream, 16 );
423                     i_index += 2;
424  
425                     break;
426  
427                 case SPU_CMD_SET_ALPHACHANNEL:
428  
429                     /* 04xxxx (alpha channel) - trashed */
430                     RemoveBits( &p_spudec->bit_stream, 16 );
431                     i_index += 2;
432  
433                     break;
434  
435                 case SPU_CMD_SET_COORDINATES:
436  
437                     /* 05xxxyyyxxxyyy (coordinates) */
438                     p_spu->i_x = GetBits( &p_spudec->bit_stream, 12 );
439                     p_spu->i_width = GetBits( &p_spudec->bit_stream, 12 )
440                                       - p_spu->i_x + 1;
441  
442                     p_spu->i_y = GetBits( &p_spudec->bit_stream, 12 );
443                     p_spu->i_height = GetBits( &p_spudec->bit_stream, 12 )
444                                        - p_spu->i_y + 1;
445  
446                     i_index += 6;
447  
448                     break;
449  
450                 case SPU_CMD_SET_OFFSETS:
451  
452                     /* 06xxxxyyyy (byte offsets) */
453                     p_spu->type.spu.i_offset[0] =
454                         GetBits( &p_spudec->bit_stream, 16 ) - 4;
455  
456                     p_spu->type.spu.i_offset[1] =
457                         GetBits( &p_spudec->bit_stream, 16 ) - 4;
458  
459                     i_index += 4;
460  
461                     break;
462  
463                 case SPU_CMD_END:
464  
465                     /* ff (end) */
466                     break;
467  
468                 default:
469  
470                     /* xx (unknown command) */
471                     intf_ErrMsg( "spudec error: unknown command 0x%.2x",
472                                  i_command );
473                     return( 1 );
474             }
475
476             /* We need to check for quit commands here */
477             if( p_spudec->p_fifo->b_die )
478             {
479                 return( 1 );
480             }
481
482         } while( i_command != SPU_CMD_END );
483
484     } while( i_index == i_next_seq );
485
486     /* Check that the next sequence index matches the current one */
487     if( i_next_seq != i_cur_seq )
488     {
489         intf_ErrMsg( "spudec error: index mismatch (0x%.4x != 0x%.4x)",
490                      i_next_seq, i_cur_seq );
491         return( 1 );
492     }
493
494     if( i_index > p_spudec->i_spu_size )
495     {
496         intf_ErrMsg( "spudec error: uh-oh, we went too far (0x%.4x > 0x%.4x)",
497                      i_index, p_spudec->i_spu_size );
498         return( 1 );
499     }
500
501     if( !p_spu->i_start )
502     {
503         intf_ErrMsg( "spudec error: no `start display' command" );
504     }
505
506     if( !p_spu->i_stop )
507     {
508         /* This subtitle will live for 5 seconds or until the next subtitle */
509         p_spu->i_stop = p_spu->i_start + 500 * 11000;
510         p_spu->b_ephemer = 1;
511     }
512
513     /* Get rid of padding bytes */
514     switch( p_spudec->i_spu_size - i_index )
515     {
516         /* Zero or one padding byte, quite usual */
517         case 1:
518             RemoveBits( &p_spudec->bit_stream, 8 );
519             i_index++;
520         case 0:
521             break;
522
523         /* More than one padding byte - this is very strange, but
524          * we can deal with it */
525         default:
526             intf_WarnMsg( 2, "spudec warning: %i padding bytes, we usually "
527                              "get 0 or 1 of them",
528                           p_spudec->i_spu_size - i_index );
529
530             while( i_index < p_spudec->i_spu_size )
531             {
532                 RemoveBits( &p_spudec->bit_stream, 8 );
533                 i_index++;
534             }
535
536             break;
537     }
538
539     if( b_force_display )
540     {
541         intf_ErrMsg( "spudec: \"force display\" command" );
542         intf_ErrMsg( "spudec: send mail to <sam@zoy.org> if you "
543                      "want to help debugging this" );
544     }
545
546     /* Successfully parsed ! */
547     return( 0 );
548 }
549
550 /*****************************************************************************
551  * ParseRLE: parse the RLE part of the subtitle
552  *****************************************************************************
553  * This part parses the subtitle graphical data and stores it in a more
554  * convenient structure for later decoding. For more information on the
555  * subtitles format, see http://sam.zoy.org/doc/dvd/subtitles/index.html
556  *****************************************************************************/
557 static int ParseRLE( spudec_thread_t *p_spudec,
558                      subpicture_t * p_spu, u8 * p_src )
559 {
560     unsigned int i_code;
561
562     unsigned int i_width = p_spu->i_width;
563     unsigned int i_height = p_spu->i_height;
564     unsigned int i_x, i_y;
565
566     u16 *p_dest = (u16 *)p_spu->p_data;
567
568     /* The subtitles are interlaced, we need two offsets */
569     unsigned int  i_id = 0;                   /* Start on the even SPU layer */
570     unsigned int  pi_table[ 2 ];
571     unsigned int *pi_offset;
572
573     boolean_t b_empty_top = 1,
574               b_empty_bottom = 0;
575     unsigned int i_skipped_top = 0,
576                  i_skipped_bottom = 0;
577
578     pi_table[ 0 ] = p_spu->type.spu.i_offset[ 0 ] << 1;
579     pi_table[ 1 ] = p_spu->type.spu.i_offset[ 1 ] << 1;
580
581     for( i_y = 0 ; i_y < i_height ; i_y++ )
582     {
583         pi_offset = pi_table + i_id;
584
585         for( i_x = 0 ; i_x < i_width ; i_x += i_code >> 2 )
586         {
587             i_code = AddNibble( 0, p_src, pi_offset );
588
589             if( i_code < 0x04 )
590             {
591                 i_code = AddNibble( i_code, p_src, pi_offset );
592
593                 if( i_code < 0x10 )
594                 {
595                     i_code = AddNibble( i_code, p_src, pi_offset );
596
597                     if( i_code < 0x040 )
598                     {
599                         i_code = AddNibble( i_code, p_src, pi_offset );
600
601                         if( i_code < 0x0100 )
602                         {
603                             /* If the 14 first bits are set to 0, then it's a
604                              * new line. We emulate it. */
605                             if( i_code < 0x0004 )
606                             {
607                                 i_code |= ( i_width - i_x ) << 2;
608                             }
609                             else
610                             {
611                                 /* We have a boo boo ! */
612                                 intf_ErrMsg( "spudec error: unknown RLE code "
613                                              "0x%.4x", i_code );
614                                 return( 1 );
615                             }
616                         }
617                     }
618                 }
619             }
620
621             if( ( (i_code >> 2) + i_x + i_y * i_width ) > i_height * i_width )
622             {
623                 intf_ErrMsg( "spudec error: out of bounds, %i at (%i,%i) is "
624                              "out of %ix%i",
625                              i_code >> 2, i_x, i_y, i_width, i_height );
626                 return( 1 );
627             }
628
629             if( i_code == (i_width << 2) ) /* FIXME: we assume 0 is transp */
630             {
631                 if( b_empty_top )
632                 {
633                     /* This is a blank top line, we skip it */
634                     i_skipped_top++;
635                 }
636                 else
637                 {
638                     /* We can't be sure the current lines will be skipped,
639                      * so we store the code just in case. */
640                     *p_dest++ = i_code;
641
642                     b_empty_bottom = 1;
643                     i_skipped_bottom++;
644                 }
645             }
646             else
647             {
648                 /* We got a valid code, store it */
649                 *p_dest++ = i_code;
650
651                 /* Valid code means no blank line */
652                 b_empty_top = 0;
653                 b_empty_bottom = 0;
654                 i_skipped_bottom = 0;
655             }
656         }
657
658         /* Check that we didn't go too far */
659         if( i_x > i_width )
660         {
661             intf_ErrMsg( "spudec error: i_x overflowed, %i > %i",
662                          i_x, i_width );
663             return( 1 );
664         }
665
666         /* Byte-align the stream */
667         if( *pi_offset & 0x1 )
668         {
669             (*pi_offset)++;
670         }
671
672         /* Swap fields */
673         i_id = ~i_id & 0x1;
674     }
675
676     /* We shouldn't get any padding bytes */
677     if( i_y < i_height )
678     {
679         intf_ErrMsg( "spudec: padding bytes found in RLE sequence" );
680         intf_ErrMsg( "spudec: send mail to <sam@zoy.org> if you "
681                      "want to help debugging this" );
682
683         /* Skip them just in case */
684         while( i_y < i_height )
685         {
686             *p_dest++ = i_width << 2;
687             i_y++;
688         }
689
690         return( 1 );
691     }
692
693     intf_WarnMsg( 3, "spudec: valid subtitle, size: %ix%i, position: %i,%i",
694                   p_spu->i_width, p_spu->i_height, p_spu->i_x, p_spu->i_y );
695
696     /* Crop if necessary */
697     if( i_skipped_top || i_skipped_bottom )
698     {
699         p_spu->i_y += i_skipped_top;
700         p_spu->i_height -= i_skipped_top + i_skipped_bottom;
701
702         intf_WarnMsg( 3, "spudec: cropped to: %ix%i, position: %i,%i",
703                       p_spu->i_width, p_spu->i_height, p_spu->i_x, p_spu->i_y );
704     }
705
706     return( 0 );
707 }
708