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