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