vout: remove redundant test
[vlc.git] / src / video_output / video_output.c
1 /*****************************************************************************
2  * video_output.c : video output thread
3  *
4  * This module describes the programming interface for video output threads.
5  * It includes functions allowing to open a new thread, send pictures to a
6  * thread, and destroy a previously oppened video output thread.
7  *****************************************************************************
8  * Copyright (C) 2000-2007 VLC authors and VideoLAN
9  * $Id$
10  *
11  * Authors: Vincent Seguin <seguin@via.ecp.fr>
12  *          Gildas Bazin <gbazin@videolan.org>
13  *          Laurent Aimar <fenrir _AT_ videolan _DOT_ org>
14  *
15  * This program is free software; you can redistribute it and/or modify it
16  * under the terms of the GNU Lesser General Public License as published by
17  * the Free Software Foundation; either version 2.1 of the License, or
18  * (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23  * GNU Lesser General Public License for more details.
24  *
25  * You should have received a copy of the GNU Lesser General Public License
26  * along with this program; if not, write to the Free Software Foundation,
27  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
28  *****************************************************************************/
29
30 /*****************************************************************************
31  * Preamble
32  *****************************************************************************/
33 #ifdef HAVE_CONFIG_H
34 # include "config.h"
35 #endif
36
37 #include <vlc_common.h>
38
39 #include <stdlib.h>                                                /* free() */
40 #include <string.h>
41 #include <assert.h>
42
43 #include <vlc_vout.h>
44
45 #include <vlc_filter.h>
46 #include <vlc_spu.h>
47 #include <vlc_vout_osd.h>
48 #include <vlc_image.h>
49 #include <vlc_plugin.h>
50
51 #include <libvlc.h>
52 #include "vout_internal.h"
53 #include "interlacing.h"
54 #include "display.h"
55 #include "window.h"
56 #include "../misc/variables.h"
57
58 /*****************************************************************************
59  * Local prototypes
60  *****************************************************************************/
61 static void *Thread(void *);
62 static void VoutDestructor(vlc_object_t *);
63
64 /* Maximum delay between 2 displayed pictures.
65  * XXX it is needed for now but should be removed in the long term.
66  */
67 #define VOUT_REDISPLAY_DELAY (INT64_C(80000))
68
69 /**
70  * Late pictures having a delay higher than this value are thrashed.
71  */
72 #define VOUT_DISPLAY_LATE_THRESHOLD (INT64_C(20000))
73
74 /* Better be in advance when awakening than late... */
75 #define VOUT_MWAIT_TOLERANCE (INT64_C(4000))
76
77 /* */
78 static int VoutValidateFormat(video_format_t *dst,
79                               const video_format_t *src)
80 {
81     if (src->i_width == 0  || src->i_width  > 8192 ||
82         src->i_height == 0 || src->i_height > 8192)
83         return VLC_EGENERIC;
84     if (src->i_sar_num <= 0 || src->i_sar_den <= 0)
85         return VLC_EGENERIC;
86
87     /* */
88     video_format_Copy(dst, src);
89     dst->i_chroma = vlc_fourcc_GetCodec(VIDEO_ES, src->i_chroma);
90     vlc_ureduce( &dst->i_sar_num, &dst->i_sar_den,
91                  src->i_sar_num,  src->i_sar_den, 50000 );
92     if (dst->i_sar_num <= 0 || dst->i_sar_den <= 0) {
93         dst->i_sar_num = 1;
94         dst->i_sar_den = 1;
95     }
96     video_format_FixRgb(dst);
97     return VLC_SUCCESS;
98 }
99 static void VideoFormatCopyCropAr(video_format_t *dst,
100                                   const video_format_t *src)
101 {
102     video_format_CopyCrop(dst, src);
103     dst->i_sar_num = src->i_sar_num;
104     dst->i_sar_den = src->i_sar_den;
105 }
106 static bool VideoFormatIsCropArEqual(video_format_t *dst,
107                                      const video_format_t *src)
108 {
109     return dst->i_sar_num * src->i_sar_den == dst->i_sar_den * src->i_sar_num &&
110            dst->i_x_offset       == src->i_x_offset &&
111            dst->i_y_offset       == src->i_y_offset &&
112            dst->i_visible_width  == src->i_visible_width &&
113            dst->i_visible_height == src->i_visible_height;
114 }
115
116 static vout_thread_t *VoutCreate(vlc_object_t *object,
117                                  const vout_configuration_t *cfg)
118 {
119     video_format_t original;
120     if (VoutValidateFormat(&original, cfg->fmt))
121         return NULL;
122
123     /* Allocate descriptor */
124     vout_thread_t *vout = vlc_custom_create(object,
125                                             sizeof(*vout) + sizeof(*vout->p),
126                                             "video output");
127     if (!vout) {
128         video_format_Clean(&original);
129         return NULL;
130     }
131
132     /* */
133     vout->p = (vout_thread_sys_t*)&vout[1];
134
135     vout->p->original = original;
136     vout->p->dpb_size = cfg->dpb_size;
137
138     vout_control_Init(&vout->p->control);
139     vout_control_PushVoid(&vout->p->control, VOUT_CONTROL_INIT);
140
141     vout_statistic_Init(&vout->p->statistic);
142
143     vout_snapshot_Init(&vout->p->snapshot);
144
145     /* Initialize locks */
146     vlc_mutex_init(&vout->p->filter.lock);
147     vlc_mutex_init(&vout->p->spu_lock);
148
149     /* Take care of some "interface/control" related initialisations */
150     vout_IntfInit(vout);
151
152     /* Initialize subpicture unit */
153     vout->p->spu = spu_Create(vout, vout);
154
155     vout->p->title.show     = var_InheritBool(vout, "video-title-show");
156     vout->p->title.timeout  = var_InheritInteger(vout, "video-title-timeout");
157     vout->p->title.position = var_InheritInteger(vout, "video-title-position");
158
159     /* Get splitter name if present */
160     vout->p->splitter_name = var_InheritString(vout, "video-splitter");
161
162     /* */
163     vout_InitInterlacingSupport(vout, vout->p->displayed.is_interlaced);
164
165     /* Window */
166     if (vout->p->splitter_name == NULL) {
167         vout_window_cfg_t wcfg = {
168             .is_standalone = !var_InheritBool(vout, "embedded-video"),
169             .is_fullscreen = var_GetBool(vout, "fullscreen"),
170             .type = VOUT_WINDOW_TYPE_INVALID,
171             // TODO: take pixel A/R, crop and zoom into account
172 #ifdef __APPLE__
173             .x = var_InheritInteger(vout, "video-x"),
174             .y = var_InheritInteger(vout, "video-y"),
175 #endif
176             .width = cfg->fmt->i_visible_width,
177             .height = cfg->fmt->i_visible_height,
178         };
179
180         vout_window_t *window = vout_display_window_New(vout, &wcfg);
181         if (window != NULL)
182         {
183             if (var_InheritBool(vout, "video-wallpaper"))
184                 vout_window_SetState(window, VOUT_WINDOW_STATE_BELOW);
185             else if (var_InheritBool(vout, "video-on-top"))
186                 vout_window_SetState(window, VOUT_WINDOW_STATE_ABOVE);
187         }
188         vout->p->window = window;
189     } else
190         vout->p->window = NULL;
191
192     /* */
193     vlc_object_set_destructor(vout, VoutDestructor);
194
195     /* */
196     if (vlc_clone(&vout->p->thread, Thread, vout,
197                   VLC_THREAD_PRIORITY_OUTPUT)) {
198         if (vout->p->window != NULL)
199             vout_display_window_Delete(vout->p->window);
200         spu_Destroy(vout->p->spu);
201         vlc_object_release(vout);
202         return NULL;
203     }
204
205     vout_control_WaitEmpty(&vout->p->control);
206
207     if (vout->p->dead) {
208         msg_Err(vout, "video output creation failed");
209         vout_CloseAndRelease(vout);
210         return NULL;
211     }
212
213     vout->p->input = cfg->input;
214     if (vout->p->input)
215         spu_Attach(vout->p->spu, vout->p->input, true);
216
217     return vout;
218 }
219
220 #undef vout_Request
221 vout_thread_t *vout_Request(vlc_object_t *object,
222                               const vout_configuration_t *cfg)
223 {
224     vout_thread_t *vout = cfg->vout;
225     if (cfg->change_fmt && !cfg->fmt) {
226         if (vout)
227             vout_CloseAndRelease(vout);
228         return NULL;
229     }
230
231     /* If a vout is provided, try reusing it */
232     if (vout) {
233         if (vout->p->input != cfg->input) {
234             if (vout->p->input)
235                 spu_Attach(vout->p->spu, vout->p->input, false);
236             vout->p->input = cfg->input;
237             if (vout->p->input)
238                 spu_Attach(vout->p->spu, vout->p->input, true);
239         }
240
241         if (cfg->change_fmt) {
242             vout_control_cmd_t cmd;
243             vout_control_cmd_Init(&cmd, VOUT_CONTROL_REINIT);
244             cmd.u.cfg = cfg;
245
246             vout_control_Push(&vout->p->control, &cmd);
247             vout_control_WaitEmpty(&vout->p->control);
248             vout_IntfReinit(vout);
249         }
250
251         if (!vout->p->dead) {
252             msg_Dbg(object, "reusing provided vout");
253             return vout;
254         }
255         vout_CloseAndRelease(vout);
256
257         msg_Warn(object, "cannot reuse provided vout");
258     }
259     return VoutCreate(object, cfg);
260 }
261
262 void vout_Close(vout_thread_t *vout)
263 {
264     assert(vout);
265
266     if (vout->p->input)
267         spu_Attach(vout->p->spu, vout->p->input, false);
268
269     vout_snapshot_End(&vout->p->snapshot);
270
271     vout_control_PushVoid(&vout->p->control, VOUT_CONTROL_CLEAN);
272     vlc_join(vout->p->thread, NULL);
273
274     if (vout->p->window != NULL)
275         vout_display_window_Delete(vout->p->window);
276
277     vlc_mutex_lock(&vout->p->spu_lock);
278     spu_Destroy(vout->p->spu);
279     vout->p->spu = NULL;
280     vlc_mutex_unlock(&vout->p->spu_lock);
281 }
282
283 /* */
284 static void VoutDestructor(vlc_object_t *object)
285 {
286     vout_thread_t *vout = (vout_thread_t *)object;
287
288     /* Make sure the vout was stopped first */
289     //assert(!vout->p_module);
290
291     free(vout->p->splitter_name);
292
293     /* Destroy the locks */
294     vlc_mutex_destroy(&vout->p->spu_lock);
295     vlc_mutex_destroy(&vout->p->filter.lock);
296     vout_control_Clean(&vout->p->control);
297
298     /* */
299     vout_statistic_Clean(&vout->p->statistic);
300
301     /* */
302     vout_snapshot_Clean(&vout->p->snapshot);
303
304     video_format_Clean(&vout->p->original);
305 }
306
307 /* */
308 void vout_Cancel(vout_thread_t *vout, bool canceled)
309 {
310     vout_control_PushBool(&vout->p->control, VOUT_CONTROL_CANCEL, canceled);
311     vout_control_WaitEmpty(&vout->p->control);
312 }
313
314 void vout_ChangePause(vout_thread_t *vout, bool is_paused, mtime_t date)
315 {
316     vout_control_cmd_t cmd;
317     vout_control_cmd_Init(&cmd, VOUT_CONTROL_PAUSE);
318     cmd.u.pause.is_on = is_paused;
319     cmd.u.pause.date  = date;
320     vout_control_Push(&vout->p->control, &cmd);
321
322     vout_control_WaitEmpty(&vout->p->control);
323 }
324
325 void vout_GetResetStatistic(vout_thread_t *vout, unsigned *restrict displayed,
326                             unsigned *restrict lost)
327 {
328     vout_statistic_GetReset( &vout->p->statistic, displayed, lost );
329 }
330
331 void vout_Flush(vout_thread_t *vout, mtime_t date)
332 {
333     vout_control_PushTime(&vout->p->control, VOUT_CONTROL_FLUSH, date);
334     vout_control_WaitEmpty(&vout->p->control);
335 }
336
337 bool vout_IsEmpty(vout_thread_t *vout)
338 {
339     picture_t *picture = picture_fifo_Peek(vout->p->decoder_fifo);
340     if (picture)
341         picture_Release(picture);
342
343     return !picture;
344 }
345
346 void vout_NextPicture(vout_thread_t *vout, mtime_t *duration)
347 {
348     vout_control_cmd_t cmd;
349     vout_control_cmd_Init(&cmd, VOUT_CONTROL_STEP);
350     cmd.u.time_ptr = duration;
351
352     vout_control_Push(&vout->p->control, &cmd);
353     vout_control_WaitEmpty(&vout->p->control);
354 }
355
356 void vout_DisplayTitle(vout_thread_t *vout, const char *title)
357 {
358     assert(title);
359     vout_control_PushString(&vout->p->control, VOUT_CONTROL_OSD_TITLE, title);
360 }
361
362 void vout_WindowMouseEvent(vout_thread_t *vout,
363                            const vout_window_mouse_event_t *mouse)
364 {
365     assert(mouse);
366     vout_control_cmd_t cmd;
367     vout_control_cmd_Init(&cmd, VOUT_CONTROL_WINDOW_MOUSE);
368     cmd.u.window_mouse = *mouse;
369
370     vout_control_Push(&vout->p->control, &cmd);
371 }
372
373 void vout_PutSubpicture( vout_thread_t *vout, subpicture_t *subpic )
374 {
375     vout_control_cmd_t cmd;
376     vout_control_cmd_Init(&cmd, VOUT_CONTROL_SUBPICTURE);
377     cmd.u.subpicture = subpic;
378
379     vout_control_Push(&vout->p->control, &cmd);
380 }
381 int vout_RegisterSubpictureChannel( vout_thread_t *vout )
382 {
383     int channel = VOUT_SPU_CHANNEL_AVAIL_FIRST;
384
385     vlc_mutex_lock(&vout->p->spu_lock);
386     if (vout->p->spu)
387         channel = spu_RegisterChannel(vout->p->spu);
388     vlc_mutex_unlock(&vout->p->spu_lock);
389
390     return channel;
391 }
392 void vout_FlushSubpictureChannel( vout_thread_t *vout, int channel )
393 {
394     vout_control_PushInteger(&vout->p->control, VOUT_CONTROL_FLUSH_SUBPICTURE,
395                              channel);
396 }
397
398 /**
399  * Allocates a video output picture buffer.
400  *
401  * Either vout_PutPicture() or picture_Release() must be used to return the
402  * buffer to the video output free buffer pool.
403  *
404  * You may use picture_Hold() (paired with picture_Release()) to keep a
405  * read-only reference.
406  */
407 picture_t *vout_GetPicture(vout_thread_t *vout)
408 {
409     picture_t *picture = picture_pool_Wait(vout->p->decoder_pool);
410     if (likely(picture != NULL)) {
411         picture_Reset(picture);
412         VideoFormatCopyCropAr(&picture->format, &vout->p->original);
413     }
414     return picture;
415 }
416
417 /**
418  * It gives to the vout a picture to be displayed.
419  *
420  * The given picture MUST comes from vout_GetPicture.
421  *
422  * Becareful, after vout_PutPicture is called, picture_t::p_next cannot be
423  * read/used.
424  */
425 void vout_PutPicture(vout_thread_t *vout, picture_t *picture)
426 {
427     picture->p_next = NULL;
428     picture_fifo_Push(vout->p->decoder_fifo, picture);
429
430     vout_control_Wake(&vout->p->control);
431 }
432
433 /* */
434 int vout_GetSnapshot(vout_thread_t *vout,
435                      block_t **image_dst, picture_t **picture_dst,
436                      video_format_t *fmt,
437                      const char *type, mtime_t timeout)
438 {
439     picture_t *picture = vout_snapshot_Get(&vout->p->snapshot, timeout);
440     if (!picture) {
441         msg_Err(vout, "Failed to grab a snapshot");
442         return VLC_EGENERIC;
443     }
444
445     if (image_dst) {
446         vlc_fourcc_t codec = VLC_CODEC_PNG;
447         if (type && image_Type2Fourcc(type))
448             codec = image_Type2Fourcc(type);
449
450         const int override_width  = var_InheritInteger(vout, "snapshot-width");
451         const int override_height = var_InheritInteger(vout, "snapshot-height");
452
453         if (picture_Export(VLC_OBJECT(vout), image_dst, fmt,
454                            picture, codec, override_width, override_height)) {
455             msg_Err(vout, "Failed to convert image for snapshot");
456             picture_Release(picture);
457             return VLC_EGENERIC;
458         }
459     }
460     if (picture_dst)
461         *picture_dst = picture;
462     else
463         picture_Release(picture);
464     return VLC_SUCCESS;
465 }
466
467 void vout_ChangeAspectRatio( vout_thread_t *p_vout,
468                              unsigned int i_num, unsigned int i_den )
469 {
470     vout_ControlChangeSampleAspectRatio( p_vout, i_num, i_den );
471 }
472
473 /* vout_Control* are usable by anyone at anytime */
474 void vout_ControlChangeFullscreen(vout_thread_t *vout, bool fullscreen)
475 {
476     vout_control_PushBool(&vout->p->control, VOUT_CONTROL_FULLSCREEN,
477                           fullscreen);
478 }
479 void vout_ControlChangeWindowState(vout_thread_t *vout, unsigned st)
480 {
481     vout_control_PushInteger(&vout->p->control, VOUT_CONTROL_WINDOW_STATE, st);
482 }
483 void vout_ControlChangeDisplayFilled(vout_thread_t *vout, bool is_filled)
484 {
485     vout_control_PushBool(&vout->p->control, VOUT_CONTROL_DISPLAY_FILLED,
486                           is_filled);
487 }
488 void vout_ControlChangeZoom(vout_thread_t *vout, int num, int den)
489 {
490     vout_control_PushPair(&vout->p->control, VOUT_CONTROL_ZOOM,
491                           num, den);
492 }
493 void vout_ControlChangeSampleAspectRatio(vout_thread_t *vout,
494                                          unsigned num, unsigned den)
495 {
496     vout_control_PushPair(&vout->p->control, VOUT_CONTROL_ASPECT_RATIO,
497                           num, den);
498 }
499 void vout_ControlChangeCropRatio(vout_thread_t *vout,
500                                  unsigned num, unsigned den)
501 {
502     vout_control_PushPair(&vout->p->control, VOUT_CONTROL_CROP_RATIO,
503                           num, den);
504 }
505 void vout_ControlChangeCropWindow(vout_thread_t *vout,
506                                   int x, int y, int width, int height)
507 {
508     vout_control_cmd_t cmd;
509     vout_control_cmd_Init(&cmd, VOUT_CONTROL_CROP_WINDOW);
510     cmd.u.window.x      = __MAX(x, 0);
511     cmd.u.window.y      = __MAX(y, 0);
512     cmd.u.window.width  = __MAX(width, 0);
513     cmd.u.window.height = __MAX(height, 0);
514
515     vout_control_Push(&vout->p->control, &cmd);
516 }
517 void vout_ControlChangeCropBorder(vout_thread_t *vout,
518                                   int left, int top, int right, int bottom)
519 {
520     vout_control_cmd_t cmd;
521     vout_control_cmd_Init(&cmd, VOUT_CONTROL_CROP_BORDER);
522     cmd.u.border.left   = __MAX(left, 0);
523     cmd.u.border.top    = __MAX(top, 0);
524     cmd.u.border.right  = __MAX(right, 0);
525     cmd.u.border.bottom = __MAX(bottom, 0);
526
527     vout_control_Push(&vout->p->control, &cmd);
528 }
529 void vout_ControlChangeFilters(vout_thread_t *vout, const char *filters)
530 {
531     vout_control_PushString(&vout->p->control, VOUT_CONTROL_CHANGE_FILTERS,
532                             filters);
533 }
534 void vout_ControlChangeSubSources(vout_thread_t *vout, const char *filters)
535 {
536     vout_control_PushString(&vout->p->control, VOUT_CONTROL_CHANGE_SUB_SOURCES,
537                             filters);
538 }
539 void vout_ControlChangeSubFilters(vout_thread_t *vout, const char *filters)
540 {
541     vout_control_PushString(&vout->p->control, VOUT_CONTROL_CHANGE_SUB_FILTERS,
542                             filters);
543 }
544 void vout_ControlChangeSubMargin(vout_thread_t *vout, int margin)
545 {
546     vout_control_PushInteger(&vout->p->control, VOUT_CONTROL_CHANGE_SUB_MARGIN,
547                              margin);
548 }
549
550 void vout_ControlChangeViewpoint(vout_thread_t *vout,
551                                  const vlc_viewpoint_t *p_viewpoint)
552 {
553     vout_control_cmd_t cmd;
554     vout_control_cmd_Init(&cmd, VOUT_CONTROL_VIEWPOINT);
555     cmd.u.viewpoint = *p_viewpoint;
556     vout_control_Push(&vout->p->control, &cmd);
557 }
558
559 /* */
560 static void VoutGetDisplayCfg(vout_thread_t *vout, vout_display_cfg_t *cfg, const char *title)
561 {
562     /* Load configuration */
563     cfg->is_fullscreen = var_GetBool(vout, "fullscreen")
564                          || var_GetBool(vout, "video-wallpaper");
565
566     cfg->viewpoint = vout->p->original.pose;
567
568     cfg->display.title = title;
569     const int display_width = var_GetInteger(vout, "width");
570     const int display_height = var_GetInteger(vout, "height");
571     cfg->display.width   = display_width > 0  ? display_width  : 0;
572     cfg->display.height  = display_height > 0 ? display_height : 0;
573     cfg->is_display_filled  = var_GetBool(vout, "autoscale");
574     unsigned msar_num, msar_den;
575     if (var_InheritURational(vout, &msar_num, &msar_den, "monitor-par") ||
576         msar_num <= 0 || msar_den <= 0) {
577         msar_num = 1;
578         msar_den = 1;
579     }
580     cfg->display.sar.num = msar_num;
581     cfg->display.sar.den = msar_den;
582     unsigned zoom_den = 1000;
583     unsigned zoom_num = zoom_den * var_GetFloat(vout, "zoom");
584     vlc_ureduce(&zoom_num, &zoom_den, zoom_num, zoom_den, 0);
585     cfg->zoom.num = zoom_num;
586     cfg->zoom.den = zoom_den;
587     cfg->align.vertical = VOUT_DISPLAY_ALIGN_CENTER;
588     cfg->align.horizontal = VOUT_DISPLAY_ALIGN_CENTER;
589     const int align_mask = var_GetInteger(vout, "align");
590     if (align_mask & 0x1)
591         cfg->align.horizontal = VOUT_DISPLAY_ALIGN_LEFT;
592     else if (align_mask & 0x2)
593         cfg->align.horizontal = VOUT_DISPLAY_ALIGN_RIGHT;
594     if (align_mask & 0x4)
595         cfg->align.vertical = VOUT_DISPLAY_ALIGN_TOP;
596     else if (align_mask & 0x8)
597         cfg->align.vertical = VOUT_DISPLAY_ALIGN_BOTTOM;
598 }
599
600 vout_window_t *vout_NewDisplayWindow(vout_thread_t *vout, unsigned type)
601 {
602     vout_window_t *window = vout->p->window;
603
604     assert(vout->p->splitter_name == NULL);
605
606     if (window == NULL)
607         return NULL;
608     if (type != VOUT_WINDOW_TYPE_INVALID && type != window->type)
609         return NULL;
610     return window;
611 }
612
613 void vout_DeleteDisplayWindow(vout_thread_t *vout, vout_window_t *window)
614 {
615     if (window == NULL && vout->p->window != NULL) {
616         vout_display_window_Delete(vout->p->window);
617         vout->p->window = NULL;
618     }
619     assert(vout->p->window == window);
620 }
621
622 void vout_SetDisplayWindowSize(vout_thread_t *vout,
623                                unsigned width, unsigned height)
624 {
625     vout_window_t *window = vout->p->window;
626
627     if (window != NULL)
628     /* Request a resize of the window. If it fails, there is nothing to do.
629      * If it succeeds, the window will emit a resize event later. */
630         vout_window_SetSize(window, width, height);
631     else
632     if (vout->p->display.vd != NULL)
633     /* Force a resize of window-less display. This is not allowed to fail,
634      * although the display is allowed to ignore the size anyway. */
635         /* FIXME: remove this, fix MSW and OS/2 window providers */
636         vout_display_SendEventDisplaySize(vout->p->display.vd, width, height);
637 }
638
639 int vout_HideWindowMouse(vout_thread_t *vout, bool hide)
640 {
641     vout_window_t *window = vout->p->window;
642
643     return window != NULL ? vout_window_HideMouse(window, hide) : VLC_EGENERIC;
644 }
645
646 /* */
647 static int FilterRestartCallback(vlc_object_t *p_this, char const *psz_var,
648                                  vlc_value_t oldval, vlc_value_t newval,
649                                  void *p_data)
650 {
651     (void) p_this; (void) psz_var; (void) oldval; (void) newval;
652     vout_ControlChangeFilters((vout_thread_t *)p_data, NULL);
653     return 0;
654 }
655
656 static int ThreadDelFilterCallbacks(filter_t *filter, void *opaque)
657 {
658     filter_DelProxyCallbacks((vlc_object_t *)opaque, filter,
659                              FilterRestartCallback);
660     return VLC_SUCCESS;
661 }
662
663 static void ThreadDelAllFilterCallbacks(vout_thread_t *vout)
664 {
665     assert(vout->p->filter.chain_interactive != NULL);
666     filter_chain_ForEach(vout->p->filter.chain_interactive,
667                          ThreadDelFilterCallbacks, vout);
668 }
669
670 static picture_t *VoutVideoFilterInteractiveNewPicture(filter_t *filter)
671 {
672     vout_thread_t *vout = filter->owner.sys;
673
674     picture_t *picture = picture_pool_Get(vout->p->private_pool);
675     if (picture) {
676         picture_Reset(picture);
677         VideoFormatCopyCropAr(&picture->format, &filter->fmt_out.video);
678     }
679     return picture;
680 }
681
682 static picture_t *VoutVideoFilterStaticNewPicture(filter_t *filter)
683 {
684     vout_thread_t *vout = filter->owner.sys;
685
686     vlc_assert_locked(&vout->p->filter.lock);
687     if (filter_chain_IsEmpty(vout->p->filter.chain_interactive))
688         return VoutVideoFilterInteractiveNewPicture(filter);
689
690     return picture_NewFromFormat(&filter->fmt_out.video);
691 }
692
693 static void ThreadFilterFlush(vout_thread_t *vout, bool is_locked)
694 {
695     if (vout->p->displayed.current)
696         picture_Release( vout->p->displayed.current );
697     vout->p->displayed.current = NULL;
698
699     if (vout->p->displayed.next)
700         picture_Release( vout->p->displayed.next );
701     vout->p->displayed.next = NULL;
702
703     if (!is_locked)
704         vlc_mutex_lock(&vout->p->filter.lock);
705     filter_chain_VideoFlush(vout->p->filter.chain_static);
706     filter_chain_VideoFlush(vout->p->filter.chain_interactive);
707     if (!is_locked)
708         vlc_mutex_unlock(&vout->p->filter.lock);
709 }
710
711 typedef struct {
712     char           *name;
713     config_chain_t *cfg;
714 } vout_filter_t;
715
716 static void ThreadChangeFilters(vout_thread_t *vout,
717                                 const video_format_t *source,
718                                 const char *filters,
719                                 int deinterlace,
720                                 bool is_locked)
721 {
722     ThreadFilterFlush(vout, is_locked);
723     ThreadDelAllFilterCallbacks(vout);
724
725     vlc_array_t array_static;
726     vlc_array_t array_interactive;
727
728     vlc_array_init(&array_static);
729     vlc_array_init(&array_interactive);
730
731     if ((vout->p->filter.has_deint =
732          deinterlace == 1 || (deinterlace == -1 && vout->p->filter.has_deint)))
733     {
734         vout_filter_t *e = malloc(sizeof(*e));
735
736         if (likely(e))
737         {
738             free(config_ChainCreate(&e->name, &e->cfg, "deinterlace"));
739             vlc_array_append(&array_static, e);
740         }
741     }
742
743     char *current = filters ? strdup(filters) : NULL;
744     while (current) {
745         config_chain_t *cfg;
746         char *name;
747         char *next = config_ChainCreate(&name, &cfg, current);
748
749         if (name && *name) {
750             vout_filter_t *e = malloc(sizeof(*e));
751
752             if (likely(e)) {
753                 e->name = name;
754                 e->cfg  = cfg;
755                 if (!strcmp(e->name, "postproc"))
756                     vlc_array_append(&array_static, e);
757                 else
758                     vlc_array_append(&array_interactive, e);
759             }
760             else {
761                 if (cfg)
762                     config_ChainDestroy(cfg);
763                 free(name);
764             }
765         } else {
766             if (cfg)
767                 config_ChainDestroy(cfg);
768             free(name);
769         }
770         free(current);
771         current = next;
772     }
773
774     if (!is_locked)
775         vlc_mutex_lock(&vout->p->filter.lock);
776
777     es_format_t fmt_target;
778     es_format_InitFromVideo(&fmt_target, source ? source : &vout->p->filter.format);
779
780     const es_format_t *p_fmt_current = &fmt_target;
781
782     for (int a = 0; a < 2; a++) {
783         vlc_array_t    *array = a == 0 ? &array_static :
784                                          &array_interactive;
785         filter_chain_t *chain = a == 0 ? vout->p->filter.chain_static :
786                                          vout->p->filter.chain_interactive;
787
788         filter_chain_Reset(chain, p_fmt_current, p_fmt_current);
789         for (size_t i = 0; i < vlc_array_count(array); i++) {
790             vout_filter_t *e = vlc_array_item_at_index(array, i);
791             msg_Dbg(vout, "Adding '%s' as %s", e->name, a == 0 ? "static" : "interactive");
792             filter_t *filter = filter_chain_AppendFilter(chain, e->name, e->cfg,
793                                NULL, NULL);
794             if (!filter)
795             {
796                 msg_Err(vout, "Failed to add filter '%s'", e->name);
797                 config_ChainDestroy(e->cfg);
798             }
799             else if (a == 1) /* Add callbacks for interactive filters */
800                 filter_AddProxyCallbacks(vout, filter, FilterRestartCallback);
801
802             free(e->name);
803             free(e);
804         }
805         p_fmt_current = filter_chain_GetFmtOut(chain);
806         vlc_array_clear(array);
807     }
808
809     if (!es_format_IsSimilar(p_fmt_current, &fmt_target)) {
810         msg_Dbg(vout, "Adding a filter to compensate for format changes");
811         if (filter_chain_AppendConverter(vout->p->filter.chain_interactive,
812                                          p_fmt_current, &fmt_target) != 0) {
813             msg_Err(vout, "Failed to compensate for the format changes, removing all filters");
814             ThreadDelAllFilterCallbacks(vout);
815             filter_chain_Reset(vout->p->filter.chain_static,      &fmt_target, &fmt_target);
816             filter_chain_Reset(vout->p->filter.chain_interactive, &fmt_target, &fmt_target);
817         }
818     }
819
820     es_format_Clean(&fmt_target);
821
822     if (vout->p->filter.configuration != filters) {
823         free(vout->p->filter.configuration);
824         vout->p->filter.configuration = filters ? strdup(filters) : NULL;
825     }
826     if (source) {
827         video_format_Clean(&vout->p->filter.format);
828         video_format_Copy(&vout->p->filter.format, source);
829     }
830
831     if (!is_locked)
832         vlc_mutex_unlock(&vout->p->filter.lock);
833 }
834
835
836 /* */
837 static int ThreadDisplayPreparePicture(vout_thread_t *vout, bool reuse, bool frame_by_frame)
838 {
839     bool is_late_dropped = vout->p->is_late_dropped && !vout->p->pause.is_on && !frame_by_frame;
840
841     vlc_mutex_lock(&vout->p->filter.lock);
842
843     picture_t *picture = filter_chain_VideoFilter(vout->p->filter.chain_static, NULL);
844     assert(!reuse || !picture);
845
846     while (!picture) {
847         picture_t *decoded;
848         if (reuse && vout->p->displayed.decoded) {
849             decoded = picture_Hold(vout->p->displayed.decoded);
850         } else {
851             decoded = picture_fifo_Pop(vout->p->decoder_fifo);
852             if (decoded) {
853                 if (is_late_dropped && !decoded->b_force) {
854                     const mtime_t predicted = mdate() + 0; /* TODO improve */
855                     const mtime_t late = predicted - decoded->date;
856                     if (late > VOUT_DISPLAY_LATE_THRESHOLD) {
857                         msg_Warn(vout, "picture is too late to be displayed (missing %"PRId64" ms)", late/1000);
858                         picture_Release(decoded);
859                         vout_statistic_AddLost(&vout->p->statistic, 1);
860                         continue;
861                     } else if (late > 0) {
862                         msg_Dbg(vout, "picture might be displayed late (missing %"PRId64" ms)", late/1000);
863                     }
864                 }
865                 if (!VideoFormatIsCropArEqual(&decoded->format, &vout->p->filter.format))
866                     ThreadChangeFilters(vout, &decoded->format, vout->p->filter.configuration, -1, true);
867             }
868         }
869
870         if (!decoded)
871             break;
872         reuse = false;
873
874         if (vout->p->displayed.decoded)
875             picture_Release(vout->p->displayed.decoded);
876
877         vout->p->displayed.decoded       = picture_Hold(decoded);
878         vout->p->displayed.timestamp     = decoded->date;
879         vout->p->displayed.is_interlaced = !decoded->b_progressive;
880
881         picture = filter_chain_VideoFilter(vout->p->filter.chain_static, decoded);
882     }
883
884     vlc_mutex_unlock(&vout->p->filter.lock);
885
886     if (!picture)
887         return VLC_EGENERIC;
888
889     assert(!vout->p->displayed.next);
890     if (!vout->p->displayed.current)
891         vout->p->displayed.current = picture;
892     else
893         vout->p->displayed.next    = picture;
894     return VLC_SUCCESS;
895 }
896
897 static int ThreadDisplayRenderPicture(vout_thread_t *vout, bool is_forced)
898 {
899     vout_thread_sys_t *sys = vout->p;
900     vout_display_t *vd = vout->p->display.vd;
901
902     picture_t *torender = picture_Hold(vout->p->displayed.current);
903
904     vout_chrono_Start(&vout->p->render);
905
906     vlc_mutex_lock(&vout->p->filter.lock);
907     picture_t *filtered = filter_chain_VideoFilter(vout->p->filter.chain_interactive, torender);
908     vlc_mutex_unlock(&vout->p->filter.lock);
909
910     if (!filtered)
911         return VLC_EGENERIC;
912
913     if (filtered->date != vout->p->displayed.current->date)
914         msg_Warn(vout, "Unsupported timestamp modifications done by chain_interactive");
915
916     /*
917      * Get the subpicture to be displayed
918      */
919     const bool do_snapshot = vout_snapshot_IsRequested(&vout->p->snapshot);
920     mtime_t render_subtitle_date;
921     if (vout->p->pause.is_on)
922         render_subtitle_date = vout->p->pause.date;
923     else
924         render_subtitle_date = filtered->date > 1 ? filtered->date : mdate();
925     mtime_t render_osd_date = mdate(); /* FIXME wrong */
926
927     /*
928      * Get the subpicture to be displayed
929      */
930     const bool do_dr_spu = !do_snapshot &&
931                            vd->info.subpicture_chromas &&
932                            *vd->info.subpicture_chromas != 0;
933
934     //FIXME: Denying do_early_spu if vd->source.orientation != ORIENT_NORMAL
935     //will have the effect that snapshots miss the subpictures. We do this
936     //because there is currently no way to transform subpictures to match
937     //the source format.
938     const bool do_early_spu = !do_dr_spu &&
939                                vd->source.orientation == ORIENT_NORMAL &&
940                               (vd->info.is_slow ||
941                                sys->display.use_dr ||
942                                do_snapshot ||
943                                vd->fmt.i_width * vd->fmt.i_height <= vd->source.i_width * vd->source.i_height);
944
945     const vlc_fourcc_t *subpicture_chromas;
946     video_format_t fmt_spu;
947     if (do_dr_spu) {
948         vout_display_place_t place;
949         vout_display_PlacePicture(&place, &vd->source, vd->cfg, false);
950
951         fmt_spu = vd->source;
952         if (fmt_spu.i_width * fmt_spu.i_height < place.width * place.height) {
953             fmt_spu.i_sar_num = vd->cfg->display.sar.num;
954             fmt_spu.i_sar_den = vd->cfg->display.sar.den;
955             fmt_spu.i_width          =
956             fmt_spu.i_visible_width  = place.width;
957             fmt_spu.i_height         =
958             fmt_spu.i_visible_height = place.height;
959         }
960         subpicture_chromas = vd->info.subpicture_chromas;
961     } else {
962         if (do_early_spu) {
963             fmt_spu = vd->source;
964         } else {
965             fmt_spu = vd->fmt;
966             fmt_spu.i_sar_num = vd->cfg->display.sar.num;
967             fmt_spu.i_sar_den = vd->cfg->display.sar.den;
968         }
969         subpicture_chromas = NULL;
970
971         if (vout->p->spu_blend &&
972             vout->p->spu_blend->fmt_out.video.i_chroma != fmt_spu.i_chroma) {
973             filter_DeleteBlend(vout->p->spu_blend);
974             vout->p->spu_blend = NULL;
975             vout->p->spu_blend_chroma = 0;
976         }
977         if (!vout->p->spu_blend && vout->p->spu_blend_chroma != fmt_spu.i_chroma) {
978             vout->p->spu_blend_chroma = fmt_spu.i_chroma;
979             vout->p->spu_blend = filter_NewBlend(VLC_OBJECT(vout), &fmt_spu);
980             if (!vout->p->spu_blend)
981                 msg_Err(vout, "Failed to create blending filter, OSD/Subtitles will not work");
982         }
983     }
984
985     video_format_t fmt_spu_rot;
986     video_format_ApplyRotation(&fmt_spu_rot, &fmt_spu);
987     subpicture_t *subpic = spu_Render(vout->p->spu,
988                                       subpicture_chromas, &fmt_spu_rot,
989                                       &vd->source,
990                                       render_subtitle_date, render_osd_date,
991                                       do_snapshot);
992     /*
993      * Perform rendering
994      *
995      * We have to:
996      * - be sure to end up with a direct buffer.
997      * - blend subtitles, and in a fast access buffer
998      */
999     bool is_direct = vout->p->decoder_pool == vout->p->display_pool;
1000     picture_t *todisplay = filtered;
1001     if (do_early_spu && subpic) {
1002         if (vout->p->spu_blend) {
1003             picture_t *blent = picture_pool_Get(vout->p->private_pool);
1004             if (blent) {
1005                 VideoFormatCopyCropAr(&blent->format, &filtered->format);
1006                 picture_Copy(blent, filtered);
1007                 if (picture_BlendSubpicture(blent, vout->p->spu_blend, subpic)) {
1008                     picture_Release(todisplay);
1009                     todisplay = blent;
1010                 } else
1011                     picture_Release(blent);
1012             }
1013         }
1014         subpicture_Delete(subpic);
1015         subpic = NULL;
1016     }
1017
1018     assert(vout_IsDisplayFiltered(vd) == !sys->display.use_dr);
1019     if (sys->display.use_dr && !is_direct) {
1020         picture_t *direct = NULL;
1021         if (likely(vout->p->display_pool != NULL))
1022             direct = picture_pool_Get(vout->p->display_pool);
1023         if (!direct) {
1024             picture_Release(todisplay);
1025             if (subpic)
1026                 subpicture_Delete(subpic);
1027             return VLC_EGENERIC;
1028         }
1029
1030         /* The display uses direct rendering (no conversion), but its pool of
1031          * pictures is not usable by the decoder (too few, too slow or
1032          * subject to invalidation...). Since there are no filters, copying
1033          * pictures from the decoder to the output is unavoidable. */
1034         VideoFormatCopyCropAr(&direct->format, &todisplay->format);
1035         picture_Copy(direct, todisplay);
1036         picture_Release(todisplay);
1037         todisplay = direct;
1038     }
1039
1040     /*
1041      * Take a snapshot if requested
1042      */
1043     if (do_snapshot)
1044         vout_snapshot_Set(&vout->p->snapshot, &vd->source, todisplay);
1045
1046     /* Render the direct buffer */
1047     vout_UpdateDisplaySourceProperties(vd, &todisplay->format);
1048     if (sys->display.use_dr) {
1049         vout_display_Prepare(vd, todisplay, subpic);
1050     } else {
1051         todisplay = vout_FilterDisplay(vd, todisplay);
1052         if (todisplay == NULL)
1053         {
1054             if (subpic != NULL)
1055                 subpicture_Delete(subpic);
1056             return VLC_EGENERIC;
1057         }
1058
1059         if (!do_dr_spu && !do_early_spu && vout->p->spu_blend && subpic)
1060             picture_BlendSubpicture(todisplay, vout->p->spu_blend, subpic);
1061         vout_display_Prepare(vd, todisplay, do_dr_spu ? subpic : NULL);
1062
1063         if (!do_dr_spu && subpic)
1064         {
1065             subpicture_Delete(subpic);
1066             subpic = NULL;
1067         }
1068     }
1069
1070     vout_chrono_Stop(&vout->p->render);
1071 #if 0
1072         {
1073         static int i = 0;
1074         if (((i++)%10) == 0)
1075             msg_Info(vout, "render: avg %d ms var %d ms",
1076                      (int)(vout->p->render.avg/1000), (int)(vout->p->render.var/1000));
1077         }
1078 #endif
1079
1080     /* Wait the real date (for rendering jitter) */
1081 #if 0
1082     mtime_t delay = direct->date - mdate();
1083     if (delay < 1000)
1084         msg_Warn(vout, "picture is late (%lld ms)", delay / 1000);
1085 #endif
1086     if (!is_forced)
1087         mwait(todisplay->date);
1088
1089     /* Display the direct buffer returned by vout_RenderPicture */
1090     vout->p->displayed.date = mdate();
1091     vout_display_Display(vd, todisplay, subpic);
1092
1093     vout_statistic_AddDisplayed(&vout->p->statistic, 1);
1094
1095     return VLC_SUCCESS;
1096 }
1097
1098 static int ThreadDisplayPicture(vout_thread_t *vout, mtime_t *deadline)
1099 {
1100     bool frame_by_frame = !deadline;
1101     bool paused = vout->p->pause.is_on;
1102     bool first = !vout->p->displayed.current;
1103
1104     if (first)
1105         if (ThreadDisplayPreparePicture(vout, true, frame_by_frame)) /* FIXME not sure it is ok */
1106             return VLC_EGENERIC;
1107
1108     if (!paused || frame_by_frame)
1109         while (!vout->p->displayed.next && !ThreadDisplayPreparePicture(vout, false, frame_by_frame))
1110             ;
1111
1112     const mtime_t date = mdate();
1113     const mtime_t render_delay = vout_chrono_GetHigh(&vout->p->render) + VOUT_MWAIT_TOLERANCE;
1114
1115     bool drop_next_frame = frame_by_frame;
1116     mtime_t date_next = VLC_TS_INVALID;
1117     if (!paused && vout->p->displayed.next) {
1118         date_next = vout->p->displayed.next->date - render_delay;
1119         if (date_next /* + 0 FIXME */ <= date)
1120             drop_next_frame = true;
1121     }
1122
1123     /* FIXME/XXX we must redisplay the last decoded picture (because
1124      * of potential vout updated, or filters update or SPU update)
1125      * For now a high update period is needed but it could be removed
1126      * if and only if:
1127      * - vout module emits events from theselves.
1128      * - *and* SPU is modified to emit an event or a deadline when needed.
1129      *
1130      * So it will be done later.
1131      */
1132     bool refresh = false;
1133
1134     mtime_t date_refresh = VLC_TS_INVALID;
1135     if (vout->p->displayed.date > VLC_TS_INVALID) {
1136         date_refresh = vout->p->displayed.date + VOUT_REDISPLAY_DELAY - render_delay;
1137         refresh = date_refresh <= date;
1138     }
1139     bool force_refresh = !drop_next_frame && refresh;
1140
1141     if (!first && !refresh && !drop_next_frame) {
1142         if (!frame_by_frame) {
1143             if (date_refresh != VLC_TS_INVALID)
1144                 *deadline = date_refresh;
1145             if (date_next != VLC_TS_INVALID && date_next < *deadline)
1146                 *deadline = date_next;
1147         }
1148         return VLC_EGENERIC;
1149     }
1150
1151     if (drop_next_frame) {
1152         picture_Release(vout->p->displayed.current);
1153         vout->p->displayed.current = vout->p->displayed.next;
1154         vout->p->displayed.next    = NULL;
1155     }
1156
1157     if (!vout->p->displayed.current)
1158         return VLC_EGENERIC;
1159
1160     /* display the picture immediately */
1161     bool is_forced = frame_by_frame || force_refresh || vout->p->displayed.current->b_force;
1162     int ret = ThreadDisplayRenderPicture(vout, is_forced);
1163     return force_refresh ? VLC_EGENERIC : ret;
1164 }
1165
1166 static void ThreadDisplaySubpicture(vout_thread_t *vout,
1167                                     subpicture_t *subpicture)
1168 {
1169     spu_PutSubpicture(vout->p->spu, subpicture);
1170 }
1171
1172 static void ThreadFlushSubpicture(vout_thread_t *vout, int channel)
1173 {
1174     spu_ClearChannel(vout->p->spu, channel);
1175 }
1176
1177 static void ThreadDisplayOsdTitle(vout_thread_t *vout, const char *string)
1178 {
1179     if (!vout->p->title.show)
1180         return;
1181
1182     vout_OSDText(vout, VOUT_SPU_CHANNEL_OSD,
1183                  vout->p->title.position, INT64_C(1000) * vout->p->title.timeout,
1184                  string);
1185 }
1186
1187 static void ThreadChangeSubSources(vout_thread_t *vout, const char *filters)
1188 {
1189     spu_ChangeSources(vout->p->spu, filters);
1190 }
1191
1192 static void ThreadChangeSubFilters(vout_thread_t *vout, const char *filters)
1193 {
1194     spu_ChangeFilters(vout->p->spu, filters);
1195 }
1196
1197 static void ThreadChangeSubMargin(vout_thread_t *vout, int margin)
1198 {
1199     spu_ChangeMargin(vout->p->spu, margin);
1200 }
1201
1202 static void ThreadChangePause(vout_thread_t *vout, bool is_paused, mtime_t date)
1203 {
1204     assert(!vout->p->pause.is_on || !is_paused);
1205
1206     if (vout->p->pause.is_on) {
1207         const mtime_t duration = date - vout->p->pause.date;
1208
1209         if (vout->p->step.timestamp > VLC_TS_INVALID)
1210             vout->p->step.timestamp += duration;
1211         if (vout->p->step.last > VLC_TS_INVALID)
1212             vout->p->step.last += duration;
1213         picture_fifo_OffsetDate(vout->p->decoder_fifo, duration);
1214         if (vout->p->displayed.decoded)
1215             vout->p->displayed.decoded->date += duration;
1216         spu_OffsetSubtitleDate(vout->p->spu, duration);
1217
1218         ThreadFilterFlush(vout, false);
1219     } else {
1220         vout->p->step.timestamp = VLC_TS_INVALID;
1221         vout->p->step.last      = VLC_TS_INVALID;
1222     }
1223     vout->p->pause.is_on = is_paused;
1224     vout->p->pause.date  = date;
1225 }
1226
1227 static void ThreadFlush(vout_thread_t *vout, bool below, mtime_t date)
1228 {
1229     vout->p->step.timestamp = VLC_TS_INVALID;
1230     vout->p->step.last      = VLC_TS_INVALID;
1231
1232     ThreadFilterFlush(vout, false); /* FIXME too much */
1233
1234     picture_t *last = vout->p->displayed.decoded;
1235     if (last) {
1236         if (( below && last->date <= date) ||
1237             (!below && last->date >= date)) {
1238             picture_Release(last);
1239
1240             vout->p->displayed.decoded   = NULL;
1241             vout->p->displayed.date      = VLC_TS_INVALID;
1242             vout->p->displayed.timestamp = VLC_TS_INVALID;
1243         }
1244     }
1245
1246     picture_fifo_Flush(vout->p->decoder_fifo, date, below);
1247 }
1248
1249 static void ThreadStep(vout_thread_t *vout, mtime_t *duration)
1250 {
1251     *duration = 0;
1252
1253     if (vout->p->step.last <= VLC_TS_INVALID)
1254         vout->p->step.last = vout->p->displayed.timestamp;
1255
1256     if (ThreadDisplayPicture(vout, NULL))
1257         return;
1258
1259     vout->p->step.timestamp = vout->p->displayed.timestamp;
1260
1261     if (vout->p->step.last > VLC_TS_INVALID &&
1262         vout->p->step.timestamp > vout->p->step.last) {
1263         *duration = vout->p->step.timestamp - vout->p->step.last;
1264         vout->p->step.last = vout->p->step.timestamp;
1265         /* TODO advance subpicture by the duration ... */
1266     }
1267 }
1268
1269 static void ThreadChangeFullscreen(vout_thread_t *vout, bool fullscreen)
1270 {
1271     vout_window_t *window = vout->p->window;
1272
1273     bool window_fullscreen = false;
1274     if (window != NULL
1275      && vout_window_SetFullScreen(window, fullscreen) == VLC_SUCCESS)
1276         window_fullscreen = true;
1277     if (vout->p->display.vd != NULL)
1278         vout_display_SendEventFullscreen(vout->p->display.vd, fullscreen, window_fullscreen);
1279 }
1280
1281 static void ThreadChangeWindowState(vout_thread_t *vout, unsigned state)
1282 {
1283     vout_window_t *window = vout->p->window;
1284
1285     if (window != NULL)
1286         vout_window_SetState(window, state);
1287 #if defined(_WIN32) || defined(__OS2__)
1288     else /* FIXME: remove this event */
1289     if (vout->p->display.vd != NULL)
1290         vout_display_SendWindowState(vout->p->display.vd, state);
1291 #endif
1292 }
1293
1294 static void ThreadChangeWindowMouse(vout_thread_t *vout,
1295                                     const vout_window_mouse_event_t *mouse)
1296 {
1297     vout_display_t *vd = vout->p->display.vd;
1298     switch (mouse->type)
1299     {
1300         case VOUT_WINDOW_MOUSE_STATE:
1301         case VOUT_WINDOW_MOUSE_MOVED:
1302         {
1303             vout_display_place_t place;
1304             vout_display_PlacePicture(&place, &vd->source, vd->cfg, false);
1305
1306             if (place.width <= 0 || place.height <= 0)
1307                 return;
1308
1309             const int x = vd->source.i_x_offset +
1310                 (int64_t)(mouse->x - place.x) *
1311                 vd->source.i_visible_width / place.width;
1312             const int y = vd->source.i_y_offset +
1313                 (int64_t)(mouse->y - place.y) *
1314                 vd->source.i_visible_height/ place.height;
1315
1316             if (mouse->type == VOUT_WINDOW_MOUSE_STATE)
1317                 vout_display_SendEventMouseState(vd, x, y, mouse->button_mask);
1318             else
1319                 vout_display_SendEventMouseMoved(vd, x, y);
1320             break;
1321         }
1322         case VOUT_WINDOW_MOUSE_PRESSED:
1323             vout_display_SendEventMousePressed(vd, mouse->button_mask);
1324             break;
1325         case VOUT_WINDOW_MOUSE_RELEASED:
1326             vout_display_SendEventMouseReleased(vd, mouse->button_mask);
1327             break;
1328         case VOUT_WINDOW_MOUSE_DOUBLE_CLICK:
1329             vout_display_SendEventMouseDoubleClick(vd);
1330             break;
1331         default: vlc_assert_unreachable();
1332             break;
1333     }
1334 }
1335
1336 static void ThreadChangeDisplayFilled(vout_thread_t *vout, bool is_filled)
1337 {
1338     vout_SetDisplayFilled(vout->p->display.vd, is_filled);
1339 }
1340
1341 static void ThreadChangeZoom(vout_thread_t *vout, int num, int den)
1342 {
1343     if (num * 10 < den) {
1344         num = den;
1345         den *= 10;
1346     } else if (num > den * 10) {
1347         num = den * 10;
1348     }
1349
1350     vout_SetDisplayZoom(vout->p->display.vd, num, den);
1351 }
1352
1353 static void ThreadChangeAspectRatio(vout_thread_t *vout,
1354                                     unsigned num, unsigned den)
1355 {
1356     vout_SetDisplayAspect(vout->p->display.vd, num, den);
1357 }
1358
1359
1360 static void ThreadExecuteCropWindow(vout_thread_t *vout,
1361                                     unsigned x, unsigned y,
1362                                     unsigned width, unsigned height)
1363 {
1364     vout_SetDisplayCrop(vout->p->display.vd, 0, 0,
1365                         x, y, width, height);
1366 }
1367 static void ThreadExecuteCropBorder(vout_thread_t *vout,
1368                                     unsigned left, unsigned top,
1369                                     unsigned right, unsigned bottom)
1370 {
1371     msg_Err(vout, "ThreadExecuteCropBorder %d.%d %dx%d", left, top, right, bottom);
1372     vout_SetDisplayCrop(vout->p->display.vd, 0, 0,
1373                         left, top, -(int)right, -(int)bottom);
1374 }
1375
1376 static void ThreadExecuteCropRatio(vout_thread_t *vout,
1377                                    unsigned num, unsigned den)
1378 {
1379     vout_SetDisplayCrop(vout->p->display.vd, num, den,
1380                         0, 0, 0, 0);
1381 }
1382
1383 static void ThreadExecuteViewpoint(vout_thread_t *vout,
1384                                    const vlc_viewpoint_t *p_viewpoint)
1385 {
1386     vout_SetDisplayViewpoint(vout->p->display.vd, p_viewpoint);
1387 }
1388
1389 static int ThreadStart(vout_thread_t *vout, vout_display_state_t *state)
1390 {
1391     vlc_mouse_Init(&vout->p->mouse);
1392     vout->p->decoder_fifo = picture_fifo_New();
1393     vout->p->decoder_pool = NULL;
1394     vout->p->display_pool = NULL;
1395     vout->p->private_pool = NULL;
1396
1397     vout->p->filter.configuration = NULL;
1398     video_format_Copy(&vout->p->filter.format, &vout->p->original);
1399
1400     filter_owner_t owner = {
1401         .sys = vout,
1402         .video = {
1403             .buffer_new = VoutVideoFilterStaticNewPicture,
1404         },
1405     };
1406     vout->p->filter.chain_static =
1407         filter_chain_NewVideo( vout, true, &owner );
1408
1409     owner.video.buffer_new = VoutVideoFilterInteractiveNewPicture;
1410     vout->p->filter.chain_interactive =
1411         filter_chain_NewVideo( vout, true, &owner );
1412
1413     vout_display_state_t state_default;
1414     if (!state) {
1415         VoutGetDisplayCfg(vout, &state_default.cfg, vout->p->display.title);
1416
1417 #if defined(_WIN32) || defined(__OS2__)
1418         bool below = var_InheritBool(vout, "video-wallpaper");
1419         bool above = var_InheritBool(vout, "video-on-top");
1420
1421         state_default.wm_state = below ? VOUT_WINDOW_STATE_BELOW
1422                                : above ? VOUT_WINDOW_STATE_ABOVE
1423                                : VOUT_WINDOW_STATE_NORMAL;
1424 #endif
1425         state_default.sar.num = 0;
1426         state_default.sar.den = 0;
1427
1428         state = &state_default;
1429     }
1430
1431     if (vout_OpenWrapper(vout, vout->p->splitter_name, state))
1432         goto error;
1433     if (vout_InitWrapper(vout))
1434     {
1435         vout_CloseWrapper(vout, state);
1436         goto error;
1437     }
1438     assert(vout->p->decoder_pool && vout->p->private_pool);
1439
1440     vout->p->displayed.current       = NULL;
1441     vout->p->displayed.next          = NULL;
1442     vout->p->displayed.decoded       = NULL;
1443     vout->p->displayed.date          = VLC_TS_INVALID;
1444     vout->p->displayed.timestamp     = VLC_TS_INVALID;
1445     vout->p->displayed.is_interlaced = false;
1446
1447     vout->p->step.last               = VLC_TS_INVALID;
1448     vout->p->step.timestamp          = VLC_TS_INVALID;
1449
1450     vout->p->spu_blend_chroma        = 0;
1451     vout->p->spu_blend               = NULL;
1452
1453     video_format_Print(VLC_OBJECT(vout), "original format", &vout->p->original);
1454     return VLC_SUCCESS;
1455 error:
1456     if (vout->p->filter.chain_interactive != NULL)
1457     {
1458         ThreadDelAllFilterCallbacks(vout);
1459         filter_chain_Delete(vout->p->filter.chain_interactive);
1460     }
1461     if (vout->p->filter.chain_static != NULL)
1462         filter_chain_Delete(vout->p->filter.chain_static);
1463     video_format_Clean(&vout->p->filter.format);
1464     if (vout->p->decoder_fifo != NULL)
1465         picture_fifo_Delete(vout->p->decoder_fifo);
1466     return VLC_EGENERIC;
1467 }
1468
1469 static void ThreadStop(vout_thread_t *vout, vout_display_state_t *state)
1470 {
1471     if (vout->p->spu_blend)
1472         filter_DeleteBlend(vout->p->spu_blend);
1473
1474     /* Destroy translation tables */
1475     if (vout->p->display.vd) {
1476         if (vout->p->decoder_pool) {
1477             ThreadFlush(vout, true, INT64_MAX);
1478             vout_EndWrapper(vout);
1479         }
1480         vout_CloseWrapper(vout, state);
1481     }
1482
1483     /* Destroy the video filters */
1484     ThreadDelAllFilterCallbacks(vout);
1485     filter_chain_Delete(vout->p->filter.chain_interactive);
1486     filter_chain_Delete(vout->p->filter.chain_static);
1487     video_format_Clean(&vout->p->filter.format);
1488     free(vout->p->filter.configuration);
1489
1490     if (vout->p->decoder_fifo)
1491         picture_fifo_Delete(vout->p->decoder_fifo);
1492     assert(!vout->p->decoder_pool);
1493 }
1494
1495 static void ThreadInit(vout_thread_t *vout)
1496 {
1497     vout->p->dead            = false;
1498     vout->p->is_late_dropped = var_InheritBool(vout, "drop-late-frames");
1499     vout->p->pause.is_on     = false;
1500     vout->p->pause.date      = VLC_TS_INVALID;
1501
1502     vout_chrono_Init(&vout->p->render, 5, 10000); /* Arbitrary initial time */
1503 }
1504
1505 static void ThreadClean(vout_thread_t *vout)
1506 {
1507     vout_chrono_Clean(&vout->p->render);
1508     vout->p->dead = true;
1509     vout_control_Dead(&vout->p->control);
1510 }
1511
1512 static int ThreadReinit(vout_thread_t *vout,
1513                         const vout_configuration_t *cfg)
1514 {
1515     video_format_t original;
1516
1517     vout->p->pause.is_on = false;
1518     vout->p->pause.date  = VLC_TS_INVALID;
1519
1520     if (VoutValidateFormat(&original, cfg->fmt)) {
1521         ThreadStop(vout, NULL);
1522         ThreadClean(vout);
1523         return VLC_EGENERIC;
1524     }
1525     /* We ignore crop/ar changes at this point, they are dynamically supported */
1526     VideoFormatCopyCropAr(&vout->p->original, &original);
1527     if (video_format_IsSimilar(&original, &vout->p->original)) {
1528         if (cfg->dpb_size <= vout->p->dpb_size) {
1529             video_format_Clean(&original);
1530             return VLC_SUCCESS;
1531         }
1532         msg_Warn(vout, "DPB need to be increased");
1533     }
1534
1535     vout_display_state_t state;
1536     memset(&state, 0, sizeof(state));
1537
1538     ThreadStop(vout, &state);
1539
1540     vout_ReinitInterlacingSupport(vout);
1541
1542     if (!state.cfg.is_fullscreen) {
1543         state.cfg.display.width  = 0;
1544         state.cfg.display.height = 0;
1545     }
1546     state.sar.num = 0;
1547     state.sar.den = 0;
1548
1549     /* FIXME current vout "variables" are not in sync here anymore
1550      * and I am not sure what to do */
1551     if (state.cfg.display.sar.num <= 0 || state.cfg.display.sar.den <= 0) {
1552         state.cfg.display.sar.num = 1;
1553         state.cfg.display.sar.den = 1;
1554     }
1555     if (state.cfg.zoom.num <= 0 || state.cfg.zoom.den <= 0) {
1556         state.cfg.zoom.num = 1;
1557         state.cfg.zoom.den = 1;
1558     }
1559
1560     vout->p->original = original;
1561     vout->p->dpb_size = cfg->dpb_size;
1562     if (ThreadStart(vout, &state)) {
1563         ThreadClean(vout);
1564         return VLC_EGENERIC;
1565     }
1566     return VLC_SUCCESS;
1567 }
1568
1569 static void ThreadCancel(vout_thread_t *vout, bool canceled)
1570 {
1571     picture_pool_Cancel(vout->p->decoder_pool, canceled);
1572 }
1573
1574 static int ThreadControl(vout_thread_t *vout, vout_control_cmd_t cmd)
1575 {
1576     switch(cmd.type) {
1577     case VOUT_CONTROL_INIT:
1578         ThreadInit(vout);
1579         if (ThreadStart(vout, NULL))
1580         {
1581             ThreadClean(vout);
1582             return 1;
1583         }
1584         break;
1585     case VOUT_CONTROL_CLEAN:
1586         ThreadStop(vout, NULL);
1587         ThreadClean(vout);
1588         return 1;
1589     case VOUT_CONTROL_REINIT:
1590         if (ThreadReinit(vout, cmd.u.cfg))
1591             return 1;
1592         break;
1593     case VOUT_CONTROL_CANCEL:
1594         ThreadCancel(vout, cmd.u.boolean);
1595         break;
1596     case VOUT_CONTROL_SUBPICTURE:
1597         ThreadDisplaySubpicture(vout, cmd.u.subpicture);
1598         cmd.u.subpicture = NULL;
1599         break;
1600     case VOUT_CONTROL_FLUSH_SUBPICTURE:
1601         ThreadFlushSubpicture(vout, cmd.u.integer);
1602         break;
1603     case VOUT_CONTROL_OSD_TITLE:
1604         ThreadDisplayOsdTitle(vout, cmd.u.string);
1605         break;
1606     case VOUT_CONTROL_CHANGE_FILTERS:
1607         ThreadChangeFilters(vout, NULL,
1608                             cmd.u.string != NULL ?
1609                             cmd.u.string : vout->p->filter.configuration,
1610                             -1, false);
1611         break;
1612     case VOUT_CONTROL_CHANGE_INTERLACE:
1613         ThreadChangeFilters(vout, NULL, vout->p->filter.configuration,
1614                             cmd.u.boolean ? 1 : 0, false);
1615         break;
1616     case VOUT_CONTROL_CHANGE_SUB_SOURCES:
1617         ThreadChangeSubSources(vout, cmd.u.string);
1618         break;
1619     case VOUT_CONTROL_CHANGE_SUB_FILTERS:
1620         ThreadChangeSubFilters(vout, cmd.u.string);
1621         break;
1622     case VOUT_CONTROL_CHANGE_SUB_MARGIN:
1623         ThreadChangeSubMargin(vout, cmd.u.integer);
1624         break;
1625     case VOUT_CONTROL_PAUSE:
1626         ThreadChangePause(vout, cmd.u.pause.is_on, cmd.u.pause.date);
1627         break;
1628     case VOUT_CONTROL_FLUSH:
1629         ThreadFlush(vout, false, cmd.u.time);
1630         break;
1631     case VOUT_CONTROL_STEP:
1632         ThreadStep(vout, cmd.u.time_ptr);
1633         break;
1634     case VOUT_CONTROL_FULLSCREEN:
1635         ThreadChangeFullscreen(vout, cmd.u.boolean);
1636         break;
1637     case VOUT_CONTROL_WINDOW_STATE:
1638         ThreadChangeWindowState(vout, cmd.u.integer);
1639         break;
1640     case VOUT_CONTROL_WINDOW_MOUSE:
1641         ThreadChangeWindowMouse(vout, &cmd.u.window_mouse);
1642         break;
1643     case VOUT_CONTROL_DISPLAY_FILLED:
1644         ThreadChangeDisplayFilled(vout, cmd.u.boolean);
1645         break;
1646     case VOUT_CONTROL_ZOOM:
1647         ThreadChangeZoom(vout, cmd.u.pair.a, cmd.u.pair.b);
1648         break;
1649     case VOUT_CONTROL_ASPECT_RATIO:
1650         ThreadChangeAspectRatio(vout, cmd.u.pair.a, cmd.u.pair.b);
1651         break;
1652     case VOUT_CONTROL_CROP_RATIO:
1653         ThreadExecuteCropRatio(vout, cmd.u.pair.a, cmd.u.pair.b);
1654         break;
1655     case VOUT_CONTROL_CROP_WINDOW:
1656         ThreadExecuteCropWindow(vout,
1657                 cmd.u.window.x, cmd.u.window.y,
1658                 cmd.u.window.width, cmd.u.window.height);
1659         break;
1660     case VOUT_CONTROL_CROP_BORDER:
1661         ThreadExecuteCropBorder(vout,
1662                 cmd.u.border.left,  cmd.u.border.top,
1663                 cmd.u.border.right, cmd.u.border.bottom);
1664         break;
1665     case VOUT_CONTROL_VIEWPOINT:
1666         ThreadExecuteViewpoint(vout, &cmd.u.viewpoint);
1667         break;
1668     default:
1669         break;
1670     }
1671     vout_control_cmd_Clean(&cmd);
1672     return 0;
1673 }
1674
1675 /*****************************************************************************
1676  * Thread: video output thread
1677  *****************************************************************************
1678  * Video output thread. This function does only returns when the thread is
1679  * terminated. It handles the pictures arriving in the video heap and the
1680  * display device events.
1681  *****************************************************************************/
1682 static void *Thread(void *object)
1683 {
1684     vout_thread_t *vout = object;
1685     vout_thread_sys_t *sys = vout->p;
1686
1687     mtime_t deadline = VLC_TS_INVALID;
1688     bool wait = false;
1689     for (;;) {
1690         vout_control_cmd_t cmd;
1691
1692         if (wait)
1693         {
1694             const mtime_t max_deadline = mdate() + 100000;
1695             deadline = deadline <= VLC_TS_INVALID ? max_deadline : __MIN(deadline, max_deadline);
1696         } else {
1697             deadline = VLC_TS_INVALID;
1698         }
1699         while (!vout_control_Pop(&sys->control, &cmd, deadline))
1700             if (ThreadControl(vout, cmd))
1701                 return NULL;
1702
1703         deadline = VLC_TS_INVALID;
1704         wait = ThreadDisplayPicture(vout, &deadline) != VLC_SUCCESS;
1705
1706         const bool picture_interlaced = sys->displayed.is_interlaced;
1707
1708         vout_SetInterlacingState(vout, picture_interlaced);
1709         vout_ManageWrapper(vout);
1710     }
1711 }