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