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