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