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