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