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