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