]> git.sesse.net Git - vlc/blob - src/video_output/vout_subpictures.c
lower case the module_* functions
[vlc] / src / video_output / vout_subpictures.c
1 /*****************************************************************************
2  * vout_subpictures.c : subpicture management functions
3  *****************************************************************************
4  * Copyright (C) 2000-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Vincent Seguin <seguin@via.ecp.fr>
8  *          Samuel Hocevar <sam@zoy.org>
9  *          Gildas Bazin <gbazin@videolan.org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_vout.h>
35 #include <vlc_block.h>
36 #include <vlc_filter.h>
37 #include <vlc_osd.h>
38 #include "../libvlc.h"
39
40 #include <assert.h>
41 #include <limits.h>
42
43 /*****************************************************************************
44  * Local prototypes
45  *****************************************************************************/
46 struct spu_private_t
47 {
48     vlc_mutex_t  subpicture_lock;                  /**< subpicture heap lock */
49     subpicture_t p_subpicture[VOUT_MAX_SUBPICTURES];        /**< subpictures */
50     int i_channel;             /**< number of subpicture channels registered */
51     int64_t i_subpicture_order; /**< number of created subpicture since spu creation */
52
53     filter_t *p_blend;                            /**< alpha blending module */
54     filter_t *p_text;                              /**< text renderer module */
55     filter_t *p_scale_yuvp;                     /**< scaling module for YUVP */
56     filter_t *p_scale;                    /**< scaling module (all but YUVP) */
57     bool b_force_crop;                     /**< force cropping of subpicture */
58     int i_crop_x, i_crop_y, i_crop_width, i_crop_height;       /**< cropping */
59
60     int i_margin;                        /**< force position of a subpicture */
61     bool b_force_palette;             /**< force palette of subpicture */
62     uint8_t palette[4][4];                               /**< forced palette */
63
64     /* Supciture filters */
65     filter_chain_t *p_chain;
66 };
67
68 static void UpdateSPU   ( spu_t *, vlc_object_t * );
69 static int  CropCallback( vlc_object_t *, char const *,
70                           vlc_value_t, vlc_value_t, void * );
71
72 static int SpuControl( spu_t *, int, va_list );
73
74 static subpicture_t *sub_new_buffer( filter_t * );
75 static void sub_del_buffer( filter_t *, subpicture_t * );
76 static subpicture_t *spu_new_buffer( filter_t * );
77 static void spu_del_buffer( filter_t *, subpicture_t * );
78 static picture_t *spu_new_video_buffer( filter_t * );
79 static void spu_del_video_buffer( filter_t *, picture_t * );
80
81 static int spu_ParseChain( spu_t * );
82 static int SubFilterCallback( vlc_object_t *, char const *,
83                               vlc_value_t, vlc_value_t, void * );
84
85 static int SubFilterAllocationInit( filter_t *, void * );
86 static void SubFilterAllocationClean( filter_t * );
87 struct filter_owner_sys_t
88 {
89     spu_t *p_spu;
90     int i_channel;
91 };
92
93 #define SCALE_UNIT (1000)
94
95 #define VLC_FOURCC_YUVP VLC_FOURCC('Y','U','V','P')
96 #define VLC_FOURCC_YUVA VLC_FOURCC('Y','U','V','A')
97 #define VLC_FOURCC_RGBA VLC_FOURCC('R','G','B','A')
98 #define VLC_FOURCC_TEXT VLC_FOURCC('T','E','X','T')
99
100 /* */
101 struct subpicture_region_private_t
102 {
103     video_format_t fmt;
104     picture_t      *p_picture;
105 };
106
107 static subpicture_region_private_t *SpuRegionPrivateCreate( video_format_t *p_fmt )
108 {
109     subpicture_region_private_t *p_private = malloc( sizeof(*p_private) );
110
111     if( !p_private )
112         return NULL;
113
114     p_private->fmt = *p_fmt;
115     if( p_fmt->p_palette )
116     {
117         p_private->fmt.p_palette = malloc( sizeof(*p_private->fmt.p_palette) );
118         if( p_private->fmt.p_palette )
119             *p_private->fmt.p_palette = *p_fmt->p_palette;
120     }
121     p_private->p_picture = NULL;
122
123     return p_private;
124 }
125 static void SpuRegionPrivateDestroy( subpicture_region_private_t *p_private )
126 {
127     if( p_private->p_picture )
128         picture_Release( p_private->p_picture );
129     free( p_private->fmt.p_palette );
130     free( p_private );
131 }
132
133 /* */
134 static void SpuRenderCreateAndLoadText( spu_t *p_spu );
135 static void SpuRenderCreateAndLoadScale( spu_t *p_spu );
136 static void FilterRelease( filter_t *p_filter );
137
138 /**
139  * Creates the subpicture unit
140  *
141  * \param p_this the parent object which creates the subpicture unit
142  */
143 spu_t *__spu_Create( vlc_object_t *p_this )
144 {
145     int i_index;
146
147     spu_t *p_spu;
148     spu_private_t *p_sys;
149     
150     p_spu = vlc_custom_create( p_this, sizeof(spu_t) + sizeof(spu_private_t),
151                                VLC_OBJECT_GENERIC, "subpicture" );
152
153     if( !p_spu )
154         return NULL;
155
156     /* Initialize spu fields */
157     p_spu->pf_control = SpuControl;
158     p_spu->p = p_sys = (spu_private_t*)&p_spu[1];
159
160     /* Initialize private fields */
161     p_sys->i_subpicture_order = 1;
162     for( i_index = 0; i_index < VOUT_MAX_SUBPICTURES; i_index++)
163     {
164         p_sys->p_subpicture[i_index].i_status = FREE_SUBPICTURE;
165     }
166
167     p_sys->p_blend = NULL;
168     p_sys->p_text = NULL;
169     p_sys->p_scale = NULL;
170     p_sys->p_scale_yuvp = NULL;
171
172     /* Register the default subpicture channel */
173     p_sys->i_channel = 2;
174
175     vlc_mutex_init( &p_sys->subpicture_lock );
176
177     vlc_object_attach( p_spu, p_this );
178
179     p_sys->p_chain = filter_chain_New( p_spu, "sub filter", false,
180                                        SubFilterAllocationInit,
181                                        SubFilterAllocationClean,
182                                        p_spu );
183
184     /* Load text and scale module */
185     SpuRenderCreateAndLoadText( p_spu );
186     SpuRenderCreateAndLoadScale( p_spu );
187
188     return p_spu;
189 }
190
191 /**
192  * Initialise the subpicture unit
193  *
194  * \param p_spu the subpicture unit object
195  */
196 int spu_Init( spu_t *p_spu )
197 {
198     spu_private_t *p_sys = p_spu->p;
199
200     /* If the user requested a sub margin, we force the position. */
201     p_sys->i_margin = var_CreateGetInteger( p_spu, "sub-margin" );
202
203     var_Create( p_spu, "sub-filter", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
204     var_AddCallback( p_spu, "sub-filter", SubFilterCallback, p_spu );
205
206     spu_ParseChain( p_spu );
207
208     return VLC_SUCCESS;
209 }
210
211 int spu_ParseChain( spu_t *p_spu )
212 {
213     char *psz_parser = var_GetString( p_spu, "sub-filter" );
214     int i_ret;
215
216     if( !psz_parser )
217         return VLC_EGENERIC;
218
219     i_ret = filter_chain_AppendFromString( p_spu->p->p_chain, psz_parser );
220
221     free( psz_parser );
222
223     return i_ret;
224 }
225
226 /**
227  * Destroy the subpicture unit
228  *
229  * \param p_this the parent object which destroys the subpicture unit
230  */
231 void spu_Destroy( spu_t *p_spu )
232 {
233     spu_private_t *p_sys = p_spu->p;
234     int i_index;
235
236     /* Destroy all remaining subpictures */
237     for( i_index = 0; i_index < VOUT_MAX_SUBPICTURES; i_index++ )
238     {
239         if( p_sys->p_subpicture[i_index].i_status != FREE_SUBPICTURE )
240         {
241             spu_DestroySubpicture( p_spu, &p_sys->p_subpicture[i_index] );
242         }
243     }
244
245     if( p_sys->p_blend )
246         FilterRelease( p_sys->p_blend );
247
248     if( p_sys->p_text )
249         FilterRelease( p_sys->p_text );
250
251     if( p_sys->p_scale_yuvp )
252         FilterRelease( p_sys->p_scale_yuvp );
253
254     if( p_sys->p_scale )
255         FilterRelease( p_sys->p_scale );
256
257     filter_chain_Delete( p_sys->p_chain );
258
259     vlc_mutex_destroy( &p_sys->subpicture_lock );
260
261     vlc_object_release( p_spu );
262 }
263
264 /**
265  * Attach/Detach the SPU from any input
266  *
267  * \param p_this the object in which to destroy the subpicture unit
268  * \param b_attach to select attach or detach
269  */
270 void spu_Attach( spu_t *p_spu, vlc_object_t *p_this, bool b_attach )
271 {
272     vlc_object_t *p_input;
273
274     p_input = vlc_object_find( p_this, VLC_OBJECT_INPUT, FIND_PARENT );
275     if( !p_input ) return;
276
277     if( b_attach )
278     {
279         UpdateSPU( p_spu, VLC_OBJECT(p_input) );
280         var_AddCallback( p_input, "highlight", CropCallback, p_spu );
281         vlc_object_release( p_input );
282     }
283     else
284     {
285         /* Delete callback */
286         var_DelCallback( p_input, "highlight", CropCallback, p_spu );
287         vlc_object_release( p_input );
288     }
289 }
290
291 /* */
292 subpicture_region_t *subpicture_region_New( const video_format_t *p_fmt )
293 {
294     subpicture_region_t *p_region = calloc( 1, sizeof(*p_region ) );
295     if( !p_region )
296         return NULL;
297
298     p_region->fmt = *p_fmt;
299     p_region->fmt.p_palette = NULL;
300     if( p_fmt->i_chroma == VLC_FOURCC_YUVP )
301     {
302         p_region->fmt.p_palette = calloc( 1, sizeof(*p_region->fmt.p_palette) );
303         if( p_fmt->p_palette )
304             *p_region->fmt.p_palette = *p_fmt->p_palette;
305     }
306     p_region->i_alpha = 0xff;
307     p_region->p_next = NULL;
308     p_region->p_private = NULL;
309     p_region->psz_text = NULL;
310     p_region->p_style = NULL;
311     p_region->p_picture = NULL;
312
313     if( p_fmt->i_chroma == VLC_FOURCC_TEXT )
314         return p_region;
315
316     p_region->p_picture = picture_New( p_fmt->i_chroma, p_fmt->i_width, p_fmt->i_height,
317                                        p_fmt->i_aspect );
318     if( !p_region->p_picture )
319     {
320         free( p_fmt->p_palette );
321         free( p_region );
322         return NULL;
323     }
324
325     return p_region;
326 }
327
328 /* */
329 void subpicture_region_Delete( subpicture_region_t *p_region )
330 {
331     if( !p_region )
332         return;
333
334     if( p_region->p_private )
335         SpuRegionPrivateDestroy( p_region->p_private );
336
337     if( p_region->p_picture )
338         picture_Release( p_region->p_picture );
339
340     free( p_region->fmt.p_palette );
341
342     free( p_region->psz_text );
343     free( p_region->psz_html );
344     //free( p_region->p_style ); FIXME --fenrir plugin does not allocate the memory for it. I think it might lead to segfault, video renderer can live longer than the decoder
345     free( p_region );
346 }
347
348 /* */
349 void subpicture_region_ChainDelete( subpicture_region_t *p_head )
350 {
351     while( p_head )
352     {
353         subpicture_region_t *p_next = p_head->p_next;
354
355         subpicture_region_Delete( p_head );
356
357         p_head = p_next;
358     }
359 }
360
361 /**
362  * Display a subpicture
363  *
364  * Remove the reservation flag of a subpicture, which will cause it to be
365  * ready for display.
366  * \param p_spu the subpicture unit object
367  * \param p_subpic the subpicture to display
368  */
369 void spu_DisplaySubpicture( spu_t *p_spu, subpicture_t *p_subpic )
370 {
371     /* Check if status is valid */
372     if( p_subpic->i_status != RESERVED_SUBPICTURE )
373     {
374         msg_Err( p_spu, "subpicture %p has invalid status #%d",
375                  p_subpic, p_subpic->i_status );
376     }
377
378     if( p_subpic->i_channel == DEFAULT_CHAN )
379     {
380         p_subpic->i_channel = 0xFFFF;
381         spu_Control( p_spu, SPU_CHANNEL_CLEAR, DEFAULT_CHAN );
382         p_subpic->i_channel = DEFAULT_CHAN;
383     }
384
385     /* Remove reservation flag */
386     p_subpic->i_status = READY_SUBPICTURE;
387 }
388
389 /**
390  * Allocate a subpicture in the spu heap.
391  *
392  * This function create a reserved subpicture in the spu heap.
393  * A null pointer is returned if the function fails. This method provides an
394  * already allocated zone of memory in the spu data fields. It needs locking
395  * since several pictures can be created by several producers threads.
396  * \param p_spu the subpicture unit in which to create the subpicture
397  * \return NULL on error, a reserved subpicture otherwise
398  */
399 subpicture_t *spu_CreateSubpicture( spu_t *p_spu )
400 {
401     spu_private_t *p_sys = p_spu->p;
402     int                 i_subpic;                        /* subpicture index */
403     subpicture_t *      p_subpic = NULL;            /* first free subpicture */
404
405     /* Get lock */
406     vlc_mutex_lock( &p_sys->subpicture_lock );
407
408     /*
409      * Look for an empty place
410      */
411     p_subpic = NULL;
412     for( i_subpic = 0; i_subpic < VOUT_MAX_SUBPICTURES; i_subpic++ )
413     {
414         if( p_sys->p_subpicture[i_subpic].i_status == FREE_SUBPICTURE )
415         {
416             /* Subpicture is empty and ready for allocation */
417             p_subpic = &p_sys->p_subpicture[i_subpic];
418             p_sys->p_subpicture[i_subpic].i_status = RESERVED_SUBPICTURE;
419             break;
420         }
421     }
422
423     /* If no free subpicture could be found */
424     if( p_subpic == NULL )
425     {
426         msg_Err( p_spu, "subpicture heap is full" );
427         vlc_mutex_unlock( &p_sys->subpicture_lock );
428         return NULL;
429     }
430
431     /* Copy subpicture information, set some default values */
432     memset( p_subpic, 0, sizeof(subpicture_t) );
433     p_subpic->i_order    = p_sys->i_subpicture_order++;
434     p_subpic->i_status   = RESERVED_SUBPICTURE;
435     p_subpic->b_absolute = true;
436     p_subpic->b_fade     = false;
437     p_subpic->b_subtitle = false;
438     p_subpic->i_alpha    = 0xFF;
439     p_subpic->p_region   = NULL;
440     p_subpic->pf_render  = NULL;
441     p_subpic->pf_destroy = NULL;
442     p_subpic->p_sys      = NULL;
443     vlc_mutex_unlock( &p_sys->subpicture_lock );
444
445     return p_subpic;
446 }
447
448 /**
449  * Remove a subpicture from the heap
450  *
451  * This function frees a previously reserved subpicture.
452  * It is meant to be used when the construction of a picture aborted.
453  * This function does not need locking since reserved subpictures are ignored
454  * by the spu.
455  */
456 void spu_DestroySubpicture( spu_t *p_spu, subpicture_t *p_subpic )
457 {
458     spu_private_t *p_sys = p_spu->p;
459
460     /* Get lock */
461     vlc_mutex_lock( &p_sys->subpicture_lock );
462
463     /* There can be race conditions so we need to check the status */
464     if( p_subpic->i_status == FREE_SUBPICTURE )
465     {
466         vlc_mutex_unlock( &p_sys->subpicture_lock );
467         return;
468     }
469
470     /* Check if status is valid */
471     if( ( p_subpic->i_status != RESERVED_SUBPICTURE )
472            && ( p_subpic->i_status != READY_SUBPICTURE ) )
473     {
474         msg_Err( p_spu, "subpicture %p has invalid status %d",
475                          p_subpic, p_subpic->i_status );
476     }
477
478     subpicture_region_ChainDelete( p_subpic->p_region );
479     p_subpic->p_region = NULL;
480
481     if( p_subpic->pf_destroy )
482     {
483         p_subpic->pf_destroy( p_subpic );
484     }
485
486     p_subpic->i_status = FREE_SUBPICTURE;
487
488     vlc_mutex_unlock( &p_sys->subpicture_lock );
489 }
490
491 static void FilterRelease( filter_t *p_filter )
492 {
493     if( p_filter->p_module )
494         module_unneed( p_filter, p_filter->p_module );
495
496     vlc_object_detach( p_filter );
497     vlc_object_release( p_filter );
498 }
499
500 static void SpuRenderCreateBlend( spu_t *p_spu, vlc_fourcc_t i_chroma, int i_aspect )
501 {
502     filter_t *p_blend;
503
504     assert( !p_spu->p->p_blend );
505
506     p_spu->p->p_blend =
507     p_blend        = vlc_custom_create( p_spu, sizeof(filter_t),
508                                         VLC_OBJECT_GENERIC, "blend" );
509     if( !p_blend )
510         return;
511
512     es_format_Init( &p_blend->fmt_in, VIDEO_ES, 0 );
513
514     es_format_Init( &p_blend->fmt_out, VIDEO_ES, 0 );
515     p_blend->fmt_out.video.i_x_offset = 0;
516     p_blend->fmt_out.video.i_y_offset = 0;
517     p_blend->fmt_out.video.i_chroma = i_chroma;
518     p_blend->fmt_out.video.i_aspect = i_aspect;
519
520     /* The blend module will be loaded when needed with the real
521     * input format */
522     p_blend->p_module = NULL;
523
524     /* */
525     vlc_object_attach( p_blend, p_spu );
526 }
527 static void SpuRenderUpdateBlend( spu_t *p_spu, int i_out_width, int i_out_height,
528                                   const video_format_t *p_in_fmt )
529 {
530     filter_t *p_blend = p_spu->p->p_blend;
531
532     assert( p_blend );
533
534     /* */
535     if( p_blend->p_module && p_blend->fmt_in.video.i_chroma != p_in_fmt->i_chroma )
536     {
537         /* The chroma is not the same, we need to reload the blend module
538          * XXX to match the old behaviour just test !p_blend->fmt_in.video.i_chroma */
539         module_unneed( p_blend, p_blend->p_module );
540         p_blend->p_module = NULL;
541     }
542
543     /* */
544     p_blend->fmt_in.video = *p_in_fmt;
545
546     /* */
547     p_blend->fmt_out.video.i_width =
548     p_blend->fmt_out.video.i_visible_width = i_out_width;
549     p_blend->fmt_out.video.i_height =
550     p_blend->fmt_out.video.i_visible_height = i_out_height;
551
552     /* */
553     if( !p_blend->p_module )
554         p_blend->p_module = module_need( p_blend, "video blending", 0, 0 );
555 }
556 static void SpuRenderCreateAndLoadText( spu_t *p_spu )
557 {
558     filter_t *p_text;
559
560     assert( !p_spu->p->p_text );
561
562     p_spu->p->p_text =
563     p_text        = vlc_custom_create( p_spu, sizeof(filter_t),
564                                        VLC_OBJECT_GENERIC, "spu text" );
565     if( !p_text )
566         return;
567
568     es_format_Init( &p_text->fmt_in, VIDEO_ES, 0 );
569
570     es_format_Init( &p_text->fmt_out, VIDEO_ES, 0 );
571     p_text->fmt_out.video.i_width =
572     p_text->fmt_out.video.i_visible_width = 32;
573     p_text->fmt_out.video.i_height =
574     p_text->fmt_out.video.i_visible_height = 32;
575
576     p_text->pf_sub_buffer_new = spu_new_buffer;
577     p_text->pf_sub_buffer_del = spu_del_buffer;
578
579     vlc_object_attach( p_text, p_spu );
580
581     /* FIXME TOCHECK shouldn't module_need( , , psz_modulename, false ) do the
582      * same than these 2 calls ? */
583     char *psz_modulename = var_CreateGetString( p_spu, "text-renderer" );
584     if( psz_modulename && *psz_modulename )
585     {
586         p_text->p_module = module_need( p_text, "text renderer",
587                                         psz_modulename, true );
588     }
589     free( psz_modulename );
590
591     if( !p_text->p_module )
592         p_text->p_module = module_need( p_text, "text renderer", NULL, false );
593 }
594
595 static filter_t *CreateAndLoadScale( vlc_object_t *p_obj,
596                                      vlc_fourcc_t i_src_chroma, vlc_fourcc_t i_dst_chroma,
597                                      bool b_resize )
598 {
599     filter_t *p_scale;
600
601     p_scale = vlc_custom_create( p_obj, sizeof(filter_t),
602                                  VLC_OBJECT_GENERIC, "scale" );
603     if( !p_scale )
604         return NULL;
605
606     es_format_Init( &p_scale->fmt_in, VIDEO_ES, 0 );
607     p_scale->fmt_in.video.i_chroma = i_src_chroma;
608     p_scale->fmt_in.video.i_width =
609     p_scale->fmt_in.video.i_height = 32;
610
611     es_format_Init( &p_scale->fmt_out, VIDEO_ES, 0 );
612     p_scale->fmt_out.video.i_chroma = i_dst_chroma;
613     p_scale->fmt_out.video.i_width =
614     p_scale->fmt_out.video.i_height = b_resize ? 16 : 32;
615
616     p_scale->pf_vout_buffer_new = spu_new_video_buffer;
617     p_scale->pf_vout_buffer_del = spu_del_video_buffer;
618
619     vlc_object_attach( p_scale, p_obj );
620     p_scale->p_module = module_need( p_scale, "video filter2", 0, 0 );
621
622     return p_scale;
623 }
624 static void SpuRenderCreateAndLoadScale( spu_t *p_spu )
625 {
626     assert( !p_spu->p->p_scale );
627     assert( !p_spu->p->p_scale_yuvp );
628     /* XXX p_spu->p_scale is used for all conversion/scaling except yuvp to
629      * yuva/rgba */
630     p_spu->p->p_scale = CreateAndLoadScale( VLC_OBJECT(p_spu),
631                                             VLC_FOURCC_YUVA, VLC_FOURCC_YUVA, true );
632     /* This one is used for YUVP to YUVA/RGBA without scaling
633      * FIXME rename it */
634     p_spu->p->p_scale_yuvp = CreateAndLoadScale( VLC_OBJECT(p_spu),
635                                                  VLC_FOURCC_YUVP, VLC_FOURCC_YUVA, false );
636 }
637
638 static void SpuRenderText( spu_t *p_spu, bool *pb_rerender_text,
639                            subpicture_t *p_subpic, subpicture_region_t *p_region,
640                            int i_min_scale_ratio )
641 {
642     filter_t *p_text = p_spu->p->p_text;
643
644     assert( p_region->fmt.i_chroma == VLC_FOURCC_TEXT );
645
646     if( !p_text || !p_text->p_module )
647         goto exit;
648
649     /* Setup 3 variables which can be used to render
650      * time-dependent text (and effects). The first indicates
651      * the total amount of time the text will be on screen,
652      * the second the amount of time it has already been on
653      * screen (can be a negative value as text is layed out
654      * before it is rendered) and the third is a feedback
655      * variable from the renderer - if the renderer sets it
656      * then this particular text is time-dependent, eg. the
657      * visual progress bar inside the text in karaoke and the
658      * text needs to be rendered multiple times in order for
659      * the effect to work - we therefore need to return the
660      * region to its original state at the end of the loop,
661      * instead of leaving it in YUVA or YUVP.
662      * Any renderer which is unaware of how to render
663      * time-dependent text can happily ignore the variables
664      * and render the text the same as usual - it should at
665      * least show up on screen, but the effect won't change
666      * the text over time.
667      */
668
669     /* FIXME why these variables are recreated every time and not
670      * when text renderer module was created ? */
671     var_Create( p_text, "spu-duration", VLC_VAR_TIME );
672     var_Create( p_text, "spu-elapsed", VLC_VAR_TIME );
673     var_Create( p_text, "text-rerender", VLC_VAR_BOOL );
674     var_Create( p_text, "scale", VLC_VAR_INTEGER );
675
676     var_SetTime( p_text, "spu-duration", p_subpic->i_stop - p_subpic->i_start );
677     var_SetTime( p_text, "spu-elapsed", mdate() - p_subpic->i_start );
678     var_SetBool( p_text, "text-rerender", false );
679     var_SetInteger( p_text, "scale", i_min_scale_ratio );
680
681     if( p_text->pf_render_html && p_region->psz_html )
682     {
683         p_text->pf_render_html( p_text, p_region, p_region );
684     }
685     else if( p_text->pf_render_text )
686     {
687         p_text->pf_render_text( p_text, p_region, p_region );
688     }
689     *pb_rerender_text = var_GetBool( p_text, "text-rerender" );
690
691     var_Destroy( p_text, "spu-duration" );
692     var_Destroy( p_text, "spu-elapsed" );
693     var_Destroy( p_text, "text-rerender" );
694     var_Destroy( p_text, "scale" );
695
696 exit:
697     p_region->i_align |= SUBPICTURE_RENDERED;
698 }
699
700 /**
701  * A few scale functions helpers.
702  */
703 typedef struct
704 {
705     int w;
706     int h;
707 } spu_scale_t;
708
709 static spu_scale_t spu_scale_create( int w, int h )
710 {
711     spu_scale_t s = { .w = w, .h = h };
712     if( s.w <= 0 )
713         s.w = SCALE_UNIT;
714     if( s.h <= 0 )
715         s.h = SCALE_UNIT;
716     return s;
717 }
718 static spu_scale_t spu_scale_unit(void )
719 {
720     return spu_scale_create( SCALE_UNIT, SCALE_UNIT );
721 }
722 static spu_scale_t spu_scale_createq( int wn, int wd, int hn, int hd )
723 {
724     return spu_scale_create( wn * SCALE_UNIT / wd,
725                              hn * SCALE_UNIT / hd );
726 }
727 static int spu_scale_w( int v, const spu_scale_t s )
728 {
729     return v * s.w / SCALE_UNIT;
730 }
731 static int spu_scale_h( int v, const spu_scale_t s )
732 {
733     return v * s.h / SCALE_UNIT;
734 }
735 static int spu_invscale_w( int v, const spu_scale_t s )
736 {
737     return v * SCALE_UNIT / s.w;
738 }
739 static int spu_invscale_h( int v, const spu_scale_t s )
740 {
741     return v * SCALE_UNIT / s.h;
742 }
743
744 /**
745  * A few area functions helpers
746  */
747
748 typedef struct
749 {
750     int i_x;
751     int i_y;
752     int i_width;
753     int i_height;
754
755     spu_scale_t scale;
756 } spu_area_t;
757
758 static spu_area_t spu_area_create( int x, int y, int w, int h, spu_scale_t s )
759 {
760     spu_area_t a = { .i_x = x, .i_y = y, .i_width = w, .i_height = h, .scale = s };
761     return a;
762 }
763 static spu_area_t spu_area_scaled( spu_area_t a )
764 {
765     if( a.scale.w == SCALE_UNIT && a.scale.h == SCALE_UNIT )
766         return a;
767
768     a.i_x = spu_scale_w( a.i_x, a.scale );
769     a.i_y = spu_scale_h( a.i_y, a.scale );
770
771     a.i_width  = spu_scale_w( a.i_width,  a.scale );
772     a.i_height = spu_scale_h( a.i_height, a.scale );
773
774     a.scale = spu_scale_unit();
775     return a;
776 }
777 static spu_area_t spu_area_unscaled( spu_area_t a, spu_scale_t s )
778 {
779     if( a.scale.w == s.w && a.scale.h == s.h )
780         return a;
781
782     a = spu_area_scaled( a );
783
784     a.i_x = spu_invscale_w( a.i_x, s );
785     a.i_y = spu_invscale_h( a.i_y, s );
786
787     a.i_width  = spu_invscale_w( a.i_width, s );
788     a.i_height = spu_invscale_h( a.i_height, s );
789
790     a.scale = s;
791     return a;
792 }
793 static bool spu_area_overlap( spu_area_t a, spu_area_t b )
794 {
795     const int i_dx = 0;
796     const int i_dy = 0;
797
798     a = spu_area_scaled( a );
799     b = spu_area_scaled( b );
800
801     return  __MAX( a.i_x-i_dx, b.i_x ) < __MIN( a.i_x+a.i_width +i_dx, b.i_x+b.i_width  ) &&
802             __MAX( a.i_y-i_dy, b.i_y ) < __MIN( a.i_y+a.i_height+i_dy, b.i_y+b.i_height );
803 }
804
805 /**
806  * Avoid area overlapping
807  */
808 static void SpuAreaFixOverlap( spu_area_t *p_dst,
809                                const spu_area_t *p_master,
810                                const spu_area_t *p_sub, int i_sub, int i_align )
811 {
812     spu_area_t a = spu_area_scaled( *p_dst );
813     bool b_moved = false;
814     bool b_ok;
815
816     assert( p_master->i_x == 0 && p_master->i_y == 0 );
817
818     /* Check for overlap
819      * XXX It is not fast O(n^2) but we should not have a lot of region */
820     do
821     {
822         b_ok = true;
823         for( int i = 0; i < i_sub; i++ )
824         {
825             spu_area_t sub = spu_area_scaled( p_sub[i] );
826
827             if( !spu_area_overlap( a, sub ) )
828                 continue;
829
830             if( i_align & SUBPICTURE_ALIGN_TOP )
831             {
832                 /* We go down */
833                 int i_y = sub.i_y + sub.i_height;
834                 if( i_y + a.i_height > p_master->i_height )
835                     break;
836                 a.i_y = i_y;
837                 b_moved = true;
838             }
839             else if( i_align & SUBPICTURE_ALIGN_BOTTOM )
840             {
841                 /* We go up */
842                 int i_y = sub.i_y - a.i_height;
843                 if( i_y < 0 )
844                     break;
845                 a.i_y = i_y;
846                 b_moved = true;
847             }
848             else
849             {
850                 /* TODO what to do in this case? */
851                 //fprintf( stderr, "Overlap with unsupported alignment\n" );
852                 break;
853             }
854
855             b_ok = false;
856             break;
857         }
858     } while( !b_ok );
859
860     if( b_moved )
861         *p_dst = spu_area_unscaled( a, p_dst->scale );
862 }
863
864
865 /**
866  * Place a region
867  */
868 static void SpuRegionPlace( int *pi_x, int *pi_y,
869                             const subpicture_t *p_subpic,
870                             const subpicture_region_t *p_region,
871                             int i_margin_y )
872 {
873     const int i_delta_x = p_region->i_x;
874     const int i_delta_y = p_region->i_y;
875     int i_x, i_y;
876
877     assert( p_region->i_x != INT_MAX && p_region->i_y != INT_MAX );
878     if( p_region->i_align & SUBPICTURE_ALIGN_TOP )
879     {
880         i_y = i_delta_y;
881     }
882     else if( p_region->i_align & SUBPICTURE_ALIGN_BOTTOM )
883     {
884         i_y = p_subpic->i_original_picture_height - p_region->fmt.i_height - i_delta_y;
885     }
886     else
887     {
888         i_y = p_subpic->i_original_picture_height / 2 - p_region->fmt.i_height / 2;
889     }
890
891     if( p_region->i_align & SUBPICTURE_ALIGN_LEFT )
892     {
893         i_x = i_delta_x;
894     }
895     else if( p_region->i_align & SUBPICTURE_ALIGN_RIGHT )
896     {
897         i_x = p_subpic->i_original_picture_width - p_region->fmt.i_width - i_delta_x;
898     }
899     else
900     {
901         i_x = p_subpic->i_original_picture_width / 2 - p_region->fmt.i_width / 2;
902     }
903
904     if( p_subpic->b_absolute )
905     {
906         i_x = i_delta_x;
907         i_y = i_delta_y;
908     }
909
910     /* Margin shifts all subpictures */
911     if( i_margin_y != 0 )
912         i_y -= i_margin_y;
913
914     /* Clamp offset to not go out of the screen (when possible) */
915     const int i_error_x = (i_x + p_region->fmt.i_width) - p_subpic->i_original_picture_width;
916     if( i_error_x > 0 )
917         i_x -= i_error_x;
918     if( i_x < 0 )
919         i_x = 0;
920
921     const int i_error_y = (i_y + p_region->fmt.i_height) - p_subpic->i_original_picture_height;
922     if( i_error_y > 0 )
923         i_y -= i_error_y;
924     if( i_y < 0 )
925         i_y = 0;
926
927     *pi_x = i_x;
928     *pi_y = i_y;
929 }
930
931 /**
932  * This function computes the current alpha value for a given region.
933  */
934 static int SpuRegionAlpha( subpicture_t *p_subpic, subpicture_region_t *p_region )
935 {
936     /* Compute alpha blend value */
937     int i_fade_alpha = 255;
938     if( p_subpic->b_fade )
939     {
940         mtime_t i_fade_start = ( p_subpic->i_stop +
941                                  p_subpic->i_start ) / 2;
942         mtime_t i_now = mdate();
943
944         if( i_now >= i_fade_start && p_subpic->i_stop > i_fade_start )
945         {
946             i_fade_alpha = 255 * ( p_subpic->i_stop - i_now ) /
947                            ( p_subpic->i_stop - i_fade_start );
948         }
949     }
950     return i_fade_alpha * p_subpic->i_alpha * p_region->i_alpha / 65025;
951 }
952
953 /**
954  * It will render the provided region onto p_pic_dst.
955  */
956
957 static void SpuRenderRegion( spu_t *p_spu,
958                              picture_t *p_pic_dst, spu_area_t *p_area,
959                              subpicture_t *p_subpic, subpicture_region_t *p_region,
960                              const spu_scale_t scale_size,
961                              const video_format_t *p_fmt,
962                              const spu_area_t *p_subtitle_area, int i_subtitle_area )
963 {
964     spu_private_t *p_sys = p_spu->p;
965
966     video_format_t fmt_original = p_region->fmt;
967     bool b_rerender_text = false;
968     bool b_restore_format = false;
969     int i_x_offset;
970     int i_y_offset;
971
972     video_format_t region_fmt;
973     picture_t *p_region_picture;
974
975     vlc_assert_locked( &p_sys->subpicture_lock );
976
977     /* Invalidate area by default */
978     *p_area = spu_area_create( 0,0, 0,0, scale_size );
979
980     /* Render text region */
981     if( p_region->fmt.i_chroma == VLC_FOURCC_TEXT )
982     {
983         const int i_min_scale_ratio = SCALE_UNIT; /* FIXME what is the right value? (scale_size is not) */
984         SpuRenderText( p_spu, &b_rerender_text, p_subpic, p_region, i_min_scale_ratio );
985         b_restore_format = b_rerender_text;
986
987         /* Check if the rendering has failed ... */
988         if( p_region->fmt.i_chroma == VLC_FOURCC_TEXT )
989             goto exit;
990     }
991
992     /* Force palette if requested
993      * FIXME b_force_palette and b_force_crop are applied to all subpictures using palette
994      * instead of only the right one (being the dvd spu).
995      */
996     const bool b_using_palette = p_region->fmt.i_chroma == VLC_FOURCC_YUVP;
997     const bool b_force_palette = b_using_palette && p_sys->b_force_palette;
998     const bool b_force_crop    = b_force_palette && p_sys->b_force_crop;
999     bool b_changed_palette     = false;
1000
1001
1002     /* Compute the margin which is expressed in destination pixel unit
1003      * The margin is applied only to subtitle and when no forced crop is
1004      * requested (dvd menu) */
1005     int i_margin_y = 0;
1006     if( !b_force_crop && p_subpic->b_subtitle )
1007         i_margin_y = spu_invscale_h( p_sys->i_margin, scale_size );
1008
1009     /* Place the picture
1010      * We compute the position in the rendered size */
1011     SpuRegionPlace( &i_x_offset, &i_y_offset,
1012                     p_subpic, p_region, i_margin_y );
1013
1014     /* Save this position for subtitle overlap support
1015      * it is really important that there are given without scale_size applied */
1016     *p_area = spu_area_create( i_x_offset, i_y_offset,
1017                                p_region->fmt.i_width, p_region->fmt.i_height,
1018                                scale_size );
1019
1020     /* Handle overlapping subtitles when possible */
1021     if( p_subpic->b_subtitle && !p_subpic->b_absolute )
1022     {
1023         spu_area_t display = spu_area_create( 0, 0, p_fmt->i_width, p_fmt->i_height,
1024                                               spu_scale_unit() );
1025
1026         SpuAreaFixOverlap( p_area, &display, p_subtitle_area, i_subtitle_area,
1027                            p_region->i_align );
1028     }
1029
1030     /* Fix the position for the current scale_size */
1031     i_x_offset = spu_scale_w( p_area->i_x, p_area->scale );
1032     i_y_offset = spu_scale_h( p_area->i_y, p_area->scale );
1033
1034     /* */
1035     if( b_force_palette )
1036     {
1037         video_palette_t *p_palette = p_region->fmt.p_palette;
1038         video_palette_t palette;
1039
1040         /* We suppose DVD palette here */
1041         palette.i_entries = 4;
1042         for( int i = 0; i < 4; i++ )
1043             for( int j = 0; j < 4; j++ )
1044                 palette.palette[i][j] = p_sys->palette[i][j];
1045
1046         if( p_palette->i_entries == palette.i_entries )
1047         {
1048             for( int i = 0; i < p_palette->i_entries; i++ )
1049                 for( int j = 0; j < 4; j++ )
1050                     b_changed_palette |= p_palette->palette[i][j] != palette.palette[i][j];
1051         }
1052         else
1053         {
1054             b_changed_palette = true;
1055         }
1056         *p_palette = palette;
1057     }
1058
1059     /* */
1060     region_fmt = p_region->fmt;
1061     p_region_picture = p_region->p_picture;
1062
1063
1064     /* Scale from rendered size to destination size */
1065     if( p_sys->p_scale && p_sys->p_scale->p_module &&
1066         ( !b_using_palette || ( p_sys->p_scale_yuvp && p_sys->p_scale_yuvp->p_module ) ) &&
1067         ( scale_size.w != SCALE_UNIT || scale_size.h != SCALE_UNIT || b_using_palette ) )
1068     {
1069         const unsigned i_dst_width  = spu_scale_w( p_region->fmt.i_width, scale_size );
1070         const unsigned i_dst_height = spu_scale_h( p_region->fmt.i_height, scale_size );
1071
1072         /* Destroy the cache if unusable */
1073         if( p_region->p_private )
1074         {
1075             subpicture_region_private_t *p_private = p_region->p_private;
1076             bool b_changed = false;
1077
1078             /* Check resize changes */
1079             if( i_dst_width  != p_private->fmt.i_width ||
1080                 i_dst_height != p_private->fmt.i_height )
1081                 b_changed = true;
1082
1083             /* Check forced palette changes */
1084             if( b_changed_palette )
1085                 b_changed = true;
1086
1087             if( b_changed )
1088             {
1089                 SpuRegionPrivateDestroy( p_private );
1090                 p_region->p_private = NULL;
1091             }
1092         }
1093
1094         /* Scale if needed into cache */
1095         if( !p_region->p_private )
1096         {
1097             filter_t *p_scale = p_sys->p_scale;
1098
1099             picture_t *p_picture = p_region->p_picture;
1100             picture_Hold( p_picture );
1101
1102             /* Convert YUVP to YUVA/RGBA first for better scaling quality */
1103             if( b_using_palette )
1104             {
1105                 filter_t *p_scale_yuvp = p_sys->p_scale_yuvp;
1106
1107                 p_scale_yuvp->fmt_in.video = p_region->fmt;
1108
1109                 /* TODO converting to RGBA for RGB video output is better */
1110                 p_scale_yuvp->fmt_out.video = p_region->fmt;
1111                 p_scale_yuvp->fmt_out.video.i_chroma = VLC_FOURCC_YUVA;
1112
1113                 p_picture = p_scale_yuvp->pf_video_filter( p_scale_yuvp, p_picture );
1114                 if( !p_picture )
1115                 {
1116                     /* Well we will try conversion+scaling */
1117                     msg_Warn( p_spu, "%4.4s to %4.4s conversion failed",
1118                              (const char*)&p_scale_yuvp->fmt_in.video.i_chroma,
1119                              (const char*)&p_scale_yuvp->fmt_out.video.i_chroma );
1120                 }
1121             }
1122
1123             /* Conversion(except from YUVP)/Scaling */
1124             if( p_picture &&
1125                 ( p_picture->format.i_width != i_dst_width ||
1126                   p_picture->format.i_height != i_dst_height ) )
1127             {
1128                 p_scale->fmt_in.video = p_picture->format;
1129                 p_scale->fmt_out.video = p_picture->format;
1130
1131                 p_scale->fmt_out.video.i_width = i_dst_width;
1132                 p_scale->fmt_out.video.i_height = i_dst_height;
1133
1134                 p_scale->fmt_out.video.i_visible_width =
1135                     spu_scale_w( p_region->fmt.i_visible_width, scale_size );
1136                 p_scale->fmt_out.video.i_visible_height =
1137                     spu_scale_h( p_region->fmt.i_visible_height, scale_size );
1138
1139                 p_picture = p_scale->pf_video_filter( p_scale, p_picture );
1140                 if( !p_picture )
1141                     msg_Err( p_spu, "scaling failed" );
1142             }
1143
1144             /* */
1145             p_region->p_private = SpuRegionPrivateCreate( &p_picture->format );
1146             if( p_region->p_private )
1147             {
1148                 p_region->p_private->p_picture = p_picture;
1149                 if( !p_region->p_private->p_picture )
1150                 {
1151                     SpuRegionPrivateDestroy( p_region->p_private );
1152                     p_region->p_private = NULL;
1153                 }
1154             }
1155             else
1156             {
1157                 picture_Release( p_picture );
1158             }
1159         }
1160
1161         /* And use the scaled picture */
1162         if( p_region->p_private )
1163         {
1164             region_fmt = p_region->p_private->fmt;
1165             p_region_picture = p_region->p_private->p_picture;
1166         }
1167     }
1168
1169     /* Force cropping if requested */
1170     if( b_force_crop )
1171     {
1172         int i_crop_x = spu_scale_w( p_sys->i_crop_x, scale_size );
1173         int i_crop_y = spu_scale_h( p_sys->i_crop_y, scale_size );
1174         int i_crop_width = spu_scale_w( p_sys->i_crop_width, scale_size );
1175         int i_crop_height= spu_scale_h( p_sys->i_crop_height,scale_size );
1176
1177         /* Find the intersection */
1178         if( i_crop_x + i_crop_width <= i_x_offset ||
1179             i_x_offset + (int)region_fmt.i_visible_width < i_crop_x ||
1180             i_crop_y + i_crop_height <= i_y_offset ||
1181             i_y_offset + (int)region_fmt.i_visible_height < i_crop_y )
1182         {
1183             /* No intersection */
1184             region_fmt.i_visible_width =
1185             region_fmt.i_visible_height = 0;
1186         }
1187         else
1188         {
1189             int i_x, i_y, i_x_end, i_y_end;
1190             i_x = __MAX( i_crop_x, i_x_offset );
1191             i_y = __MAX( i_crop_y, i_y_offset );
1192             i_x_end = __MIN( i_crop_x + i_crop_width,
1193                            i_x_offset + (int)region_fmt.i_visible_width );
1194             i_y_end = __MIN( i_crop_y + i_crop_height,
1195                            i_y_offset + (int)region_fmt.i_visible_height );
1196
1197             region_fmt.i_x_offset = i_x - i_x_offset;
1198             region_fmt.i_y_offset = i_y - i_y_offset;
1199             region_fmt.i_visible_width = i_x_end - i_x;
1200             region_fmt.i_visible_height = i_y_end - i_y;
1201
1202             i_x_offset = __MAX( i_x, 0 );
1203             i_y_offset = __MAX( i_y, 0 );
1204         }
1205     }
1206
1207     /* Update the blender */
1208     SpuRenderUpdateBlend( p_spu, p_fmt->i_width, p_fmt->i_height, &region_fmt );
1209
1210     if( p_sys->p_blend->p_module )
1211     {
1212         const int i_alpha = SpuRegionAlpha( p_subpic, p_region );
1213
1214         p_sys->p_blend->pf_video_blend( p_sys->p_blend, p_pic_dst,
1215             p_region_picture, i_x_offset, i_y_offset, i_alpha );
1216     }
1217     else
1218     {
1219         msg_Err( p_spu, "blending %4.4s to %4.4s failed",
1220                  (char *)&p_sys->p_blend->fmt_out.video.i_chroma,
1221                  (char *)&p_sys->p_blend->fmt_out.video.i_chroma );
1222     }
1223
1224 exit:
1225     if( b_rerender_text )
1226     {
1227         /* Some forms of subtitles need to be re-rendered more than
1228          * once, eg. karaoke. We therefore restore the region to its
1229          * pre-rendered state, so the next time through everything is
1230          * calculated again.
1231          */
1232         picture_Release( p_region->p_picture );
1233         p_region->p_picture = NULL;
1234         if( p_region->p_private )
1235         {
1236             SpuRegionPrivateDestroy( p_region->p_private );
1237             p_region->p_private = NULL;
1238         }
1239         p_region->i_align &= ~SUBPICTURE_RENDERED;
1240     }
1241     if( b_restore_format )
1242         p_region->fmt = fmt_original;
1243 }
1244
1245 /**
1246  * This function compares two 64 bits integers.
1247  * It can be used by qsort.
1248  */
1249 static int IntegerCmp( int64_t i0, int64_t i1 )
1250 {
1251     return i0 < i1 ? -1 : i0 > i1 ? 1 : 0;
1252 }
1253 /**
1254  * This function compares 2 subpictures using the following properties 
1255  * (ordered by priority)
1256  * 1. absolute positionning
1257  * 2. start time
1258  * 3. creation order
1259  *
1260  * It can be used by qsort.
1261  *
1262  * XXX spu_RenderSubpictures depends heavily on this order.
1263  */
1264 static int SubpictureCmp( const void *s0, const void *s1 )
1265 {
1266     subpicture_t *p_subpic0 = *(subpicture_t**)s0;
1267     subpicture_t *p_subpic1 = *(subpicture_t**)s1;
1268     int r;
1269
1270     r = IntegerCmp( !p_subpic0->b_absolute, !p_subpic1->b_absolute );
1271     if( !r )
1272         r = IntegerCmp( p_subpic0->i_start, p_subpic1->i_start );
1273     if( !r )
1274         r = IntegerCmp( p_subpic0->i_order, p_subpic1->i_order );
1275     return r;
1276 }
1277 /**
1278  * This function renders all sub picture units in the list.
1279  */
1280 void spu_RenderSubpictures( spu_t *p_spu,
1281                             picture_t *p_pic_dst, const video_format_t *p_fmt_dst,
1282                             subpicture_t *p_subpic_list,
1283                             const video_format_t *p_fmt_src )
1284 {
1285     spu_private_t *p_sys = p_spu->p;
1286
1287     const int i_source_video_width  = p_fmt_src->i_width;
1288     const int i_source_video_height = p_fmt_src->i_height;
1289     const mtime_t i_current_date = mdate();
1290
1291     unsigned int i_subpicture;
1292     subpicture_t *pp_subpicture[VOUT_MAX_SUBPICTURES];
1293
1294     unsigned int i_subtitle_region_count;
1295     spu_area_t p_subtitle_area_buffer[VOUT_MAX_SUBPICTURES];
1296     spu_area_t *p_subtitle_area;
1297     int i_subtitle_area;
1298
1299     /* Get lock */
1300     vlc_mutex_lock( &p_sys->subpicture_lock );
1301
1302     /* Preprocess subpictures */
1303     i_subpicture = 0;
1304     i_subtitle_region_count = 0;
1305     for( subpicture_t * p_subpic = p_subpic_list;
1306             p_subpic != NULL && p_subpic->i_status != FREE_SUBPICTURE; /* Check again status (as we where unlocked) */
1307                 p_subpic = p_subpic->p_next )
1308     {
1309         /* */
1310         if( p_subpic->pf_pre_render )
1311             p_subpic->pf_pre_render( p_spu, p_subpic, p_fmt_dst );
1312
1313         if( p_subpic->pf_update_regions )
1314         {
1315             video_format_t fmt_org = *p_fmt_dst;
1316             fmt_org.i_width =
1317             fmt_org.i_visible_width = i_source_video_width;
1318             fmt_org.i_height =
1319             fmt_org.i_visible_height = i_source_video_height;
1320
1321             p_subpic->pf_update_regions( p_spu, p_subpic, &fmt_org, i_current_date );
1322         }
1323
1324         /* */
1325         if( p_subpic->b_subtitle )
1326         {
1327             for( subpicture_region_t *r = p_subpic->p_region; r != NULL; r = r->p_next )
1328                 i_subtitle_region_count++;
1329         }
1330
1331         /* */
1332         pp_subpicture[i_subpicture++] = p_subpic;
1333     }
1334
1335     /* Be sure we have at least 1 picture to process */
1336     if( i_subpicture <= 0 )
1337     {
1338         vlc_mutex_unlock( &p_sys->subpicture_lock );
1339         return;
1340     }
1341
1342     /* Now order subpicture array
1343      * XXX The order is *really* important for overlap subtitles positionning */
1344     qsort( pp_subpicture, i_subpicture, sizeof(*pp_subpicture), SubpictureCmp );
1345
1346     /* Allocate area array for subtitle overlap */
1347     i_subtitle_area = 0;
1348     p_subtitle_area = p_subtitle_area_buffer;
1349     if( i_subtitle_region_count > sizeof(p_subtitle_area_buffer)/sizeof(*p_subtitle_area_buffer) )
1350         p_subtitle_area = calloc( i_subtitle_region_count, sizeof(*p_subtitle_area) );
1351
1352     /* Create the blending module */
1353     if( !p_sys->p_blend )
1354         SpuRenderCreateBlend( p_spu, p_fmt_dst->i_chroma, p_fmt_dst->i_aspect );
1355
1356     /* Process all subpictures and regions (in the right order) */
1357     for( unsigned int i_index = 0; i_index < i_subpicture; i_index++ )
1358     {
1359         subpicture_t *p_subpic = pp_subpicture[i_index];
1360         subpicture_region_t *p_region;
1361
1362         if( !p_subpic->p_region )
1363             continue;
1364
1365         /* FIXME when possible use a better rendering size than source size
1366          * (max of display size and source size for example) FIXME */
1367         int i_render_width  = p_subpic->i_original_picture_width;
1368         int i_render_height = p_subpic->i_original_picture_height;
1369         if( !i_render_width || !i_render_height )
1370         {
1371             if( i_render_width != 0 || i_render_height != 0 )
1372                 msg_Err( p_spu, "unsupported original picture size %dx%d",
1373                          i_render_width, i_render_height );
1374
1375             p_subpic->i_original_picture_width  = i_render_width = i_source_video_width;
1376             p_subpic->i_original_picture_height = i_render_height = i_source_video_height;
1377         }
1378
1379         if( p_sys->p_text )
1380         {
1381             p_sys->p_text->fmt_out.video.i_width          =
1382             p_sys->p_text->fmt_out.video.i_visible_width  = i_render_width;
1383
1384             p_sys->p_text->fmt_out.video.i_height         =
1385             p_sys->p_text->fmt_out.video.i_visible_height = i_render_height;
1386         }
1387
1388         /* Compute scaling from picture to source size */
1389         spu_scale_t scale = spu_scale_createq( i_source_video_width,  i_render_width,
1390                                                i_source_video_height, i_render_height );
1391
1392         /* Update scaling from source size to display size(p_fmt_dst) */
1393         scale.w = scale.w * p_fmt_dst->i_width  / i_source_video_width;
1394         scale.h = scale.h * p_fmt_dst->i_height / i_source_video_height;
1395
1396         /* Set default subpicture aspect ratio
1397          * FIXME if we only handle 1 aspect ratio per picture, why is it set per
1398          * region ? */
1399         p_region = p_subpic->p_region;
1400         if( !p_region->fmt.i_sar_num || !p_region->fmt.i_sar_den )
1401         {
1402             if( p_region->fmt.i_aspect != 0 )
1403             {
1404                 p_region->fmt.i_sar_den = p_region->fmt.i_aspect;
1405                 p_region->fmt.i_sar_num = VOUT_ASPECT_FACTOR;
1406             }
1407             else
1408             {
1409                 p_region->fmt.i_sar_den = p_fmt_dst->i_sar_den;
1410                 p_region->fmt.i_sar_num = p_fmt_dst->i_sar_num;
1411             }
1412         }
1413
1414         /* Take care of the aspect ratio */
1415         if( p_region->fmt.i_sar_num * p_fmt_dst->i_sar_den !=
1416             p_region->fmt.i_sar_den * p_fmt_dst->i_sar_num )
1417         {
1418             /* FIXME FIXME what about region->i_x/i_y ? */
1419             scale.w = scale.w *
1420                 (int64_t)p_region->fmt.i_sar_num * p_fmt_dst->i_sar_den /
1421                 p_region->fmt.i_sar_den / p_fmt_dst->i_sar_num;
1422         }
1423
1424         /* Render all regions
1425          * We always transform non absolute subtitle into absolute one on the
1426          * first rendering to allow good subtitle overlap support.
1427          */
1428         for( p_region = p_subpic->p_region; p_region != NULL; p_region = p_region->p_next )
1429         {
1430             spu_area_t area;
1431
1432             /* Check scale validity */
1433             if( scale.w <= 0 || scale.h <= 0 )
1434                 continue;
1435
1436             /* */
1437             SpuRenderRegion( p_spu, p_pic_dst, &area,
1438                              p_subpic, p_region, scale, p_fmt_dst,
1439                              p_subtitle_area, i_subtitle_area );
1440
1441             if( p_subpic->b_subtitle )
1442             {
1443                 area = spu_area_unscaled( area, scale );
1444                 if( !p_subpic->b_absolute && area.i_width > 0 && area.i_height > 0 )
1445                 {
1446                     p_region->i_x = area.i_x;
1447                     p_region->i_y = area.i_y;
1448                 }
1449                 if( p_subtitle_area )
1450                     p_subtitle_area[i_subtitle_area++] = area;
1451             }
1452         }
1453         if( p_subpic->b_subtitle )
1454             p_subpic->b_absolute = true;
1455     }
1456
1457     /* */
1458     if( p_subtitle_area != p_subtitle_area_buffer )
1459         free( p_subtitle_area );
1460
1461     vlc_mutex_unlock( &p_sys->subpicture_lock );
1462 }
1463
1464 /*****************************************************************************
1465  * spu_SortSubpictures: find the subpictures to display
1466  *****************************************************************************
1467  * This function parses all subpictures and decides which ones need to be
1468  * displayed. This operation does not need lock, since only READY_SUBPICTURE
1469  * are handled. If no picture has been selected, display_date will depend on
1470  * the subpicture.
1471  * We also check for ephemer DVD subpictures (subpictures that have
1472  * to be removed if a newer one is available), which makes it a lot
1473  * more difficult to guess if a subpicture has to be rendered or not.
1474  *****************************************************************************/
1475 subpicture_t *spu_SortSubpictures( spu_t *p_spu, mtime_t display_date,
1476                                    bool b_paused, bool b_subtitle_only )
1477 {
1478     spu_private_t *p_sys = p_spu->p;
1479     int i_channel;
1480     subpicture_t *p_subpic = NULL;
1481
1482     /* Run subpicture filters */
1483     filter_chain_SubFilter( p_sys->p_chain, display_date );
1484
1485     /* We get an easily parsable chained list of subpictures which
1486      * ends with NULL since p_subpic was initialized to NULL. */
1487     for( i_channel = 0; i_channel < p_sys->i_channel; i_channel++ )
1488     {
1489         subpicture_t *p_ephemer = NULL;
1490         mtime_t      ephemer_date = 0;
1491         int i_index;
1492
1493         for( i_index = 0; i_index < VOUT_MAX_SUBPICTURES; i_index++ )
1494         {
1495             subpicture_t *p_current = &p_sys->p_subpicture[i_index];
1496
1497             if( p_current->i_channel != i_channel ||
1498                 p_current->i_status != READY_SUBPICTURE ||
1499                 ( b_subtitle_only && !p_current->b_subtitle ) )
1500             {
1501                 continue;
1502             }
1503             if( display_date &&
1504                 display_date < p_current->i_start )
1505             {
1506                 /* Too early, come back next monday */
1507                 continue;
1508             }
1509
1510             if( p_current->i_start > ephemer_date )
1511                 ephemer_date = p_current->i_start;
1512
1513             if( display_date > p_current->i_stop &&
1514                 ( !p_current->b_ephemer || p_current->i_stop > p_current->i_start ) &&
1515                 !( p_current->b_subtitle && b_paused ) ) /* XXX Assume that subtitle are pausable */
1516             {
1517                 /* Too late, destroy the subpic */
1518                 spu_DestroySubpicture( p_spu, &p_sys->p_subpicture[i_index] );
1519                 continue;
1520             }
1521
1522             /* If this is an ephemer subpic, add it to our list */
1523             if( p_current->b_ephemer )
1524             {
1525                 p_current->p_next = p_ephemer;
1526                 p_ephemer = p_current;
1527
1528                 continue;
1529             }
1530
1531             p_current->p_next = p_subpic;
1532             p_subpic = p_current;
1533         }
1534
1535         /* If we found ephemer subpictures, check if they have to be
1536          * displayed or destroyed */
1537         while( p_ephemer != NULL )
1538         {
1539             subpicture_t *p_tmp = p_ephemer;
1540             p_ephemer = p_ephemer->p_next;
1541
1542             if( p_tmp->i_start < ephemer_date )
1543             {
1544                 /* Ephemer subpicture has lived too long */
1545                 spu_DestroySubpicture( p_spu, p_tmp );
1546             }
1547             else
1548             {
1549                 /* Ephemer subpicture can still live a bit */
1550                 p_tmp->p_next = p_subpic;
1551                 p_subpic = p_tmp;
1552             }
1553         }
1554     }
1555
1556     return p_subpic;
1557 }
1558
1559 /*****************************************************************************
1560  * SpuClearChannel: clear an spu channel
1561  *****************************************************************************
1562  * This function destroys the subpictures which belong to the spu channel
1563  * corresponding to i_channel_id.
1564  *****************************************************************************/
1565 static void SpuClearChannel( spu_t *p_spu, int i_channel, bool b_locked )
1566 {
1567     spu_private_t *p_sys = p_spu->p;
1568     int          i_subpic;                               /* subpicture index */
1569     subpicture_t *p_subpic = NULL;                  /* first free subpicture */
1570
1571     if( !b_locked )
1572         vlc_mutex_lock( &p_sys->subpicture_lock );
1573
1574     for( i_subpic = 0; i_subpic < VOUT_MAX_SUBPICTURES; i_subpic++ )
1575     {
1576         p_subpic = &p_sys->p_subpicture[i_subpic];
1577         if( p_subpic->i_status == FREE_SUBPICTURE
1578             || ( p_subpic->i_status != RESERVED_SUBPICTURE
1579                  && p_subpic->i_status != READY_SUBPICTURE ) )
1580         {
1581             continue;
1582         }
1583
1584         if( p_subpic->i_channel == i_channel )
1585         {
1586             subpicture_region_ChainDelete( p_subpic->p_region );
1587             p_subpic->p_region = NULL;
1588
1589             if( p_subpic->pf_destroy ) p_subpic->pf_destroy( p_subpic );
1590             p_subpic->i_status = FREE_SUBPICTURE;
1591         }
1592     }
1593
1594     if( !b_locked )
1595         vlc_mutex_unlock( &p_sys->subpicture_lock );
1596 }
1597
1598 /*****************************************************************************
1599  * spu_ControlDefault: default methods for the subpicture unit control.
1600  *****************************************************************************/
1601 static int SpuControl( spu_t *p_spu, int i_query, va_list args )
1602 {
1603     spu_private_t *p_sys = p_spu->p;
1604     int *pi, i;
1605
1606     switch( i_query )
1607     {
1608     case SPU_CHANNEL_REGISTER:
1609         pi = (int *)va_arg( args, int * );
1610         vlc_mutex_lock( &p_sys->subpicture_lock );
1611         if( pi )
1612             *pi = p_sys->i_channel++;
1613         vlc_mutex_unlock( &p_sys->subpicture_lock );
1614         break;
1615
1616     case SPU_CHANNEL_CLEAR:
1617         i = (int)va_arg( args, int );
1618         SpuClearChannel( p_spu, i, false );
1619         break;
1620
1621     default:
1622         msg_Dbg( p_spu, "control query not supported" );
1623         return VLC_EGENERIC;
1624     }
1625
1626     return VLC_SUCCESS;
1627 }
1628
1629 /*****************************************************************************
1630  * Object variables callbacks
1631  *****************************************************************************/
1632
1633 /*****************************************************************************
1634  * UpdateSPU: update subpicture settings
1635  *****************************************************************************
1636  * This function is called from CropCallback and at initialization time, to
1637  * retrieve crop information from the input.
1638  *****************************************************************************/
1639 static void UpdateSPU( spu_t *p_spu, vlc_object_t *p_object )
1640 {
1641     spu_private_t *p_sys = p_spu->p;
1642     vlc_value_t val;
1643
1644     vlc_mutex_lock( &p_sys->subpicture_lock );
1645
1646     p_sys->b_force_palette = false;
1647     p_sys->b_force_crop = false;
1648
1649     if( var_Get( p_object, "highlight", &val ) || !val.b_bool )
1650     {
1651         vlc_mutex_unlock( &p_sys->subpicture_lock );
1652         return;
1653     }
1654
1655     p_sys->b_force_crop = true;
1656     p_sys->i_crop_x = var_GetInteger( p_object, "x-start" );
1657     p_sys->i_crop_y = var_GetInteger( p_object, "y-start" );
1658     p_sys->i_crop_width  = var_GetInteger( p_object, "x-end" ) - p_sys->i_crop_x;
1659     p_sys->i_crop_height = var_GetInteger( p_object, "y-end" ) - p_sys->i_crop_y;
1660
1661     if( var_Get( p_object, "menu-palette", &val ) == VLC_SUCCESS )
1662     {
1663         memcpy( p_sys->palette, val.p_address, 16 );
1664         p_sys->b_force_palette = true;
1665     }
1666     vlc_mutex_unlock( &p_sys->subpicture_lock );
1667
1668     msg_Dbg( p_object, "crop: %i,%i,%i,%i, palette forced: %i",
1669              p_sys->i_crop_x, p_sys->i_crop_y,
1670              p_sys->i_crop_width, p_sys->i_crop_height,
1671              p_sys->b_force_palette );
1672 }
1673
1674 /*****************************************************************************
1675  * CropCallback: called when the highlight properties are changed
1676  *****************************************************************************
1677  * This callback is called from the input thread when we need cropping
1678  *****************************************************************************/
1679 static int CropCallback( vlc_object_t *p_object, char const *psz_var,
1680                          vlc_value_t oldval, vlc_value_t newval, void *p_data )
1681 {
1682     (void)psz_var; (void)oldval; (void)newval;
1683     UpdateSPU( (spu_t *)p_data, p_object );
1684     return VLC_SUCCESS;
1685 }
1686
1687 /*****************************************************************************
1688  * Buffers allocation callbacks for the filters
1689  *****************************************************************************/
1690 static subpicture_t *sub_new_buffer( filter_t *p_filter )
1691 {
1692     filter_owner_sys_t *p_sys = p_filter->p_owner;
1693     subpicture_t *p_subpicture = spu_CreateSubpicture( p_sys->p_spu );
1694     if( p_subpicture ) p_subpicture->i_channel = p_sys->i_channel;
1695     return p_subpicture;
1696 }
1697
1698 static void sub_del_buffer( filter_t *p_filter, subpicture_t *p_subpic )
1699 {
1700     filter_owner_sys_t *p_sys = p_filter->p_owner;
1701     spu_DestroySubpicture( p_sys->p_spu, p_subpic );
1702 }
1703
1704 static subpicture_t *spu_new_buffer( filter_t *p_filter )
1705 {
1706     subpicture_t *p_subpic = calloc( 1, sizeof(subpicture_t) );
1707     if( !p_subpic )
1708         return NULL;
1709
1710     p_subpic->b_absolute = true;
1711     p_subpic->i_alpha    = 0xFF;
1712
1713     VLC_UNUSED(p_filter);
1714     return p_subpic;
1715 }
1716
1717 static void spu_del_buffer( filter_t *p_filter, subpicture_t *p_subpic )
1718 {
1719     subpicture_region_ChainDelete( p_subpic->p_region );
1720
1721     VLC_UNUSED(p_filter);
1722     free( p_subpic );
1723 }
1724
1725 static picture_t *spu_new_video_buffer( filter_t *p_filter )
1726 {
1727     const video_format_t *p_fmt = &p_filter->fmt_out.video;
1728
1729     VLC_UNUSED(p_filter);
1730     return picture_New( p_fmt->i_chroma,
1731                         p_fmt->i_width, p_fmt->i_height, p_fmt->i_aspect );
1732 }
1733
1734 static void spu_del_video_buffer( filter_t *p_filter, picture_t *p_picture )
1735 {
1736     VLC_UNUSED(p_filter);
1737     picture_Release( p_picture );
1738 }
1739
1740 static int SubFilterCallback( vlc_object_t *p_object, char const *psz_var,
1741                          vlc_value_t oldval, vlc_value_t newval, void *p_data )
1742 {
1743     spu_t *p_spu = p_data;
1744     spu_private_t *p_sys = p_spu->p;
1745
1746     VLC_UNUSED(p_object); VLC_UNUSED(oldval);
1747     VLC_UNUSED(newval); VLC_UNUSED(psz_var);
1748
1749     vlc_mutex_lock( &p_sys->subpicture_lock );
1750     filter_chain_Reset( p_sys->p_chain, NULL, NULL );
1751     spu_ParseChain( p_spu );
1752     vlc_mutex_unlock( &p_sys->subpicture_lock );
1753     return VLC_SUCCESS;
1754 }
1755
1756 static int SubFilterAllocationInit( filter_t *p_filter, void *p_data )
1757 {
1758     spu_t *p_spu = p_data;
1759
1760     filter_owner_sys_t *p_sys = malloc( sizeof(filter_owner_sys_t) );
1761     if( !p_sys )
1762         return VLC_EGENERIC;
1763
1764     p_filter->pf_sub_buffer_new = sub_new_buffer;
1765     p_filter->pf_sub_buffer_del = sub_del_buffer;
1766
1767     p_filter->p_owner = p_sys;
1768     spu_Control( p_spu, SPU_CHANNEL_REGISTER, &p_sys->i_channel );
1769     p_sys->p_spu = p_spu;
1770
1771     return VLC_SUCCESS;
1772 }
1773
1774 static void SubFilterAllocationClean( filter_t *p_filter )
1775 {
1776     filter_owner_sys_t *p_sys = p_filter->p_owner;
1777
1778     SpuClearChannel( p_sys->p_spu, p_sys->i_channel, true );
1779     free( p_filter->p_owner );
1780 }
1781