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