documentation: fixed a heap o' typos
[platform/upstream/gstreamer.git] / sys / dshowvideosink / dshowvideosink.cpp
1 /* GStreamer
2  * Copyright (C) 2008 Pioneers of the Inevitable <songbird@songbirdnest.com>
3  *               2010 FLUENDO S.A. <support@fluendo.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24
25 #include "dshowvideosink.h"
26 #include "dshowvideofakesrc.h"
27
28 #include <gst/video/video.h>
29 #include <gst/video/videooverlay.h>
30 #include <gst/video/navigation.h>
31
32 #include "windows.h"
33
34 #define WM_GRAPH_NOTIFY WM_APP + 1 /* Private message */
35
36 GST_DEBUG_CATEGORY (dshowvideosink_debug);
37 #define GST_CAT_DEFAULT dshowvideosink_debug
38
39 static GstCaps * gst_directshow_media_type_to_caps (AM_MEDIA_TYPE *mediatype);
40 static gboolean gst_caps_to_directshow_media_type (GstDshowVideoSink * sink,
41   GstCaps *caps, AM_MEDIA_TYPE *mediatype);
42
43 /* TODO: Support RGB! */
44 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
45     GST_PAD_SINK,
46     GST_PAD_ALWAYS,
47     GST_STATIC_CAPS (
48         "video/x-raw,"
49         "width = (int) [ 1, MAX ],"
50         "height = (int) [ 1, MAX ],"
51         "framerate = (fraction) [ 0, MAX ]," 
52         "format = {(string)YUY2, (string)UYVY, (string)YV12 }")
53     );
54
55 static void gst_dshowvideosink_init_interfaces (GType type);
56
57 static void gst_dshowvideosink_videooverlay_init (GstVideoOverlayInterface *iface);
58 static void
59 gst_dshowvideosink_navigation_interface_init (GstNavigationInterface * iface);
60
61 #define gst_dshowvideosink_parent_class parent_class
62 G_DEFINE_TYPE_WITH_CODE (GstDshowVideoSink, gst_dshowvideosink,
63                          GST_TYPE_VIDEO_SINK,
64                          G_IMPLEMENT_INTERFACE (GST_TYPE_VIDEO_OVERLAY, gst_dshowvideosink_videooverlay_init);
65                          G_IMPLEMENT_INTERFACE (GST_TYPE_NAVIGATION, gst_dshowvideosink_navigation_interface_init))
66
67 enum
68 {
69   PROP_0,
70   PROP_KEEP_ASPECT_RATIO,
71   PROP_FULL_SCREEN,
72   PROP_RENDERER
73 };
74
75 /* GObject methods */
76 static void gst_dshowvideosink_finalize (GObject * gobject);
77 static void gst_dshowvideosink_set_property (GObject * object, guint prop_id,
78     const GValue * value, GParamSpec * pspec);
79 static void gst_dshowvideosink_get_property (GObject * object, guint prop_id,
80     GValue * value, GParamSpec * pspec);
81
82 /* GstElement methods */
83 static GstStateChangeReturn gst_dshowvideosink_change_state (GstElement * element, GstStateChange transition);
84
85 /* GstBaseSink methods */
86 static gboolean gst_dshowvideosink_start (GstBaseSink * bsink);
87 static gboolean gst_dshowvideosink_stop (GstBaseSink * bsink);
88 static gboolean gst_dshowvideosink_unlock (GstBaseSink * bsink);
89 static gboolean gst_dshowvideosink_unlock_stop (GstBaseSink * bsink);
90 static gboolean gst_dshowvideosink_set_caps (GstBaseSink * bsink, GstCaps * caps);
91 static GstCaps *gst_dshowvideosink_get_caps (GstBaseSink * bsink, GstCaps * filter);
92 static GstFlowReturn gst_dshowvideosink_show_frame (GstVideoSink *sink, GstBuffer *buffer);
93 static void gst_dshowvideosink_set_window_for_renderer (GstDshowVideoSink *sink);
94
95 /* COM initialization/uninitialization thread */
96 static void gst_dshowvideosink_com_thread (GstDshowVideoSink * sink);
97 /* TODO: event, preroll, buffer_alloc? 
98  * buffer_alloc won't generally be all that useful because the renderers require a 
99  * different stride to GStreamer's implicit values. 
100  */
101
102 static void
103 gst_dshowvideosink_set_window_handle (GstVideoOverlay * overlay, guintptr window_id)
104
105 {
106   GstDshowVideoSink *sink = GST_DSHOWVIDEOSINK (overlay);
107   HWND previous_window = sink->window_id;
108   HWND videowindow = (HWND)window_id;
109
110   if (videowindow == sink->window_id) {
111     GST_DEBUG_OBJECT (sink, "Window already set");
112     return;
113   }
114
115   sink->window_id = videowindow;
116
117   /* Update window if we're already playing. */
118   if (sink->connected && sink->filter_media_event) {
119     HRESULT hres;
120
121     if (sink->is_new_window) {
122       /* If we created a new window */
123       SendMessage (previous_window, WM_CLOSE, NULL, NULL);
124       sink->is_new_window = FALSE;
125       sink->window_closed = FALSE;
126     } else {
127       /* Return control of application window */
128       SetWindowLongPtr (previous_window, GWLP_WNDPROC, (LONG_PTR)sink->prevWndProc);
129       SetWindowPos (previous_window, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
130     }
131
132     gst_dshowvideosink_set_window_for_renderer (sink);
133
134     hres = sink->filter_media_event->SetNotifyWindow ((OAHWND)sink->window_id, WM_GRAPH_NOTIFY, 0);
135     GST_DEBUG_OBJECT (sink, "SetNotifyWindow(%p) returned %x", sink->window_id, hres);
136   }
137 }
138
139 static void
140 gst_dshowvideosink_expose (GstVideoOverlay * overlay)
141 {
142   GstDshowVideoSink *sink = GST_DSHOWVIDEOSINK (overlay);
143
144   if (sink->renderersupport) {
145     sink->renderersupport->PaintWindow ();
146   }
147 }
148
149 static void
150 gst_dshowvideosink_videooverlay_init (GstVideoOverlayInterface * iface)
151 {
152   iface->set_window_handle = gst_dshowvideosink_set_window_handle;
153   iface->expose = gst_dshowvideosink_expose;
154 }
155
156 static void
157 gst_dshowvideosink_navigation_send_event (GstNavigation * navigation,
158     GstStructure * structure)
159 {
160   GstDshowVideoSink *sink = GST_DSHOWVIDEOSINK (navigation);
161   GstEvent *event = NULL;
162   GstPad *pad = NULL;
163
164   event = gst_event_new_navigation (structure);
165
166   /* FXIME: handle aspect ratio. */
167
168   pad = gst_pad_get_peer (GST_VIDEO_SINK_PAD (sink));
169
170   if (GST_IS_PAD (pad) && GST_IS_EVENT (event)) {
171     gst_pad_send_event (pad, event);
172
173     gst_object_unref (pad);
174   }
175 }
176
177 static void
178 gst_dshowvideosink_navigation_interface_init (GstNavigationInterface * iface)
179 {
180   /* FIXME: navigation interface partially implemented.
181    * Need to call gst_navigation_send_mouse_event and
182    * gst_navigation_send_key_event like in directdrawsink.
183    */
184   iface->send_event = gst_dshowvideosink_navigation_send_event;
185 }
186
187 static void
188 gst_dshowvideosink_class_init (GstDshowVideoSinkClass * klass)
189 {
190   GObjectClass *o_class;
191   GstElementClass *e_class;
192   GstBaseSinkClass *bs_class;
193   GstVideoSinkClass *vs_class;
194
195   o_class = (GObjectClass *) klass;
196   e_class = (GstElementClass *) klass;
197   bs_class = (GstBaseSinkClass *) klass;
198   vs_class = (GstVideoSinkClass *) klass;
199
200   o_class->finalize = gst_dshowvideosink_finalize;
201   o_class->set_property = gst_dshowvideosink_set_property;
202   o_class->get_property = gst_dshowvideosink_get_property;
203
204   gst_element_class_set_static_metadata (e_class, "DirectShow video sink",
205       "Sink/Video", "Display data using a DirectShow video renderer",
206       "Pioneers of the Inevitable <songbird@songbirdnest.com>, " \
207       "FLUENDO S.A. <support@fluendo.com>");
208
209   gst_element_class_add_static_pad_template (e_class, &sink_template);
210
211   e_class->change_state = GST_DEBUG_FUNCPTR (gst_dshowvideosink_change_state);
212
213   bs_class->get_caps = GST_DEBUG_FUNCPTR (gst_dshowvideosink_get_caps);
214   bs_class->set_caps = GST_DEBUG_FUNCPTR (gst_dshowvideosink_set_caps);
215   bs_class->start = GST_DEBUG_FUNCPTR (gst_dshowvideosink_start);
216   bs_class->stop = GST_DEBUG_FUNCPTR (gst_dshowvideosink_stop);
217   bs_class->unlock = GST_DEBUG_FUNCPTR (gst_dshowvideosink_unlock);
218   bs_class->unlock_stop =
219       GST_DEBUG_FUNCPTR (gst_dshowvideosink_unlock_stop);
220
221   vs_class->show_frame = GST_DEBUG_FUNCPTR (gst_dshowvideosink_show_frame);
222
223   /* Add properties */
224   g_object_class_install_property (G_OBJECT_CLASS (klass),
225       PROP_KEEP_ASPECT_RATIO, g_param_spec_boolean ("force-aspect-ratio",
226           "Force aspect ratio",
227           "When enabled, scaling will respect original aspect ratio", TRUE,
228           (GParamFlags)G_PARAM_READWRITE));
229   g_object_class_install_property (G_OBJECT_CLASS (klass),
230       PROP_FULL_SCREEN, g_param_spec_boolean ("fullscreen",
231           "Full screen mode",
232           "Use full-screen mode (not available when using XOverlay)", FALSE,
233           (GParamFlags)G_PARAM_READWRITE));
234
235   g_object_class_install_property (G_OBJECT_CLASS (klass),
236       PROP_RENDERER, g_param_spec_string ("renderer", "Renderer", 
237       "Force usage of specific DirectShow renderer (EVR, VMR9 or VMR7)",
238       NULL, (GParamFlags)G_PARAM_READWRITE));
239 }
240
241 static void
242 gst_dshowvideosink_clear (GstDshowVideoSink *sink)
243 {
244   sink->renderersupport = NULL;
245   sink->fakesrc = NULL;
246   sink->filter_graph = NULL;
247   sink->filter_media_event = NULL;
248
249   sink->keep_aspect_ratio = FALSE;
250   sink->full_screen = FALSE;
251
252   sink->window_closed = FALSE;
253   sink->window_id = NULL;
254   sink->is_new_window = FALSE;
255
256   sink->connected = FALSE;
257   sink->graph_running = FALSE;
258 }
259
260 static void
261 gst_dshowvideosink_init (GstDshowVideoSink * sink)
262 {
263   gst_dshowvideosink_clear (sink);
264
265   g_mutex_init (&sink->graph_lock);
266   g_mutex_init (&sink->com_init_lock);
267   g_mutex_init (&sink->com_deinit_lock);
268   g_cond_init (&sink->com_initialized);
269   g_cond_init (&sink->com_uninitialize);
270   g_cond_init (&sink->com_uninitialized);
271
272   g_mutex_lock (&sink->com_init_lock);
273
274   /* create the COM initialization thread */
275   g_thread_new ("gstdshowvideosinkcomthread", (GThreadFunc)gst_dshowvideosink_com_thread, sink);
276
277   /* wait until the COM thread signals that COM has been initialized */
278   g_cond_wait (&sink->com_initialized, &sink->com_init_lock);
279   g_mutex_unlock (&sink->com_init_lock);
280 }
281
282 static void
283 gst_dshowvideosink_finalize (GObject * gobject)
284 {
285   GstDshowVideoSink *sink = GST_DSHOWVIDEOSINK (gobject);
286
287   g_free (sink->preferredrenderer);
288
289   /* signal the COM thread that it sould uninitialize COM */
290   if (sink->comInitialized) {
291     g_mutex_lock (&sink->com_deinit_lock);
292     g_cond_signal (&sink->com_uninitialize);
293     g_cond_wait (&sink->com_uninitialized, &sink->com_deinit_lock);
294     g_mutex_unlock (&sink->com_deinit_lock);
295   }
296
297   g_mutex_clear (&sink->com_init_lock);
298   g_mutex_clear (&sink->com_deinit_lock);
299   g_cond_clear (&sink->com_initialized);
300   g_cond_clear (&sink->com_uninitialize);
301   g_cond_clear (&sink->com_uninitialized);
302
303   g_mutex_clear (&sink->graph_lock);
304
305   G_OBJECT_CLASS (parent_class)->finalize (gobject);
306 }
307
308 static void
309 gst_dshowvideosink_set_property (GObject * object, guint prop_id,
310     const GValue * value, GParamSpec * pspec)
311 {
312   GstDshowVideoSink *sink = GST_DSHOWVIDEOSINK (object);
313
314   switch (prop_id) {
315     case PROP_RENDERER:
316       g_free (sink->preferredrenderer);
317       sink->preferredrenderer = g_value_dup_string (value);
318       break;
319     case PROP_KEEP_ASPECT_RATIO:
320       sink->keep_aspect_ratio = g_value_get_boolean (value);
321       if (sink->renderersupport)
322         sink->renderersupport->SetAspectRatioMode();
323       break;
324     case PROP_FULL_SCREEN:
325       sink->full_screen = g_value_get_boolean (value);
326       break;
327     default:
328       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
329       break;
330   }
331 }
332
333 static void
334 gst_dshowvideosink_get_property (GObject * object, guint prop_id,
335     GValue * value, GParamSpec * pspec)
336 {
337   GstDshowVideoSink *sink = GST_DSHOWVIDEOSINK (object);
338
339   switch (prop_id) {
340     case PROP_RENDERER:
341       g_value_take_string (value, sink->preferredrenderer);
342       break;
343     case PROP_KEEP_ASPECT_RATIO:
344       g_value_set_boolean (value, sink->keep_aspect_ratio);
345       break;
346     case PROP_FULL_SCREEN:
347       g_value_set_boolean (value, sink->full_screen);
348       break;
349     default:
350       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
351       break;
352   }
353 }
354
355 static void
356 gst_dshowvideosink_com_thread (GstDshowVideoSink * sink)
357 {
358   HRESULT res;
359
360   g_mutex_lock (&sink->com_init_lock);
361
362   /* Initialize COM with a MTA for this process. This thread will
363    * be the first one to enter the apartement and the last one to leave
364    * it, unitializing COM properly */
365
366   res = CoInitializeEx (0, COINIT_MULTITHREADED);
367   if (res == S_FALSE)
368     GST_WARNING_OBJECT (sink, "COM has been already initialized in the same process");
369   else if (res == RPC_E_CHANGED_MODE)
370     GST_WARNING_OBJECT (sink, "The concurrency model of COM has changed.");
371   else
372     GST_INFO_OBJECT (sink, "COM initialized successfully");
373
374   sink->comInitialized = TRUE;
375
376   /* Signal other threads waiting on this condition that COM was initialized */
377   g_cond_signal (&sink->com_initialized);
378
379   g_mutex_unlock (&sink->com_init_lock);
380
381   /* Wait until the uninitialize condition is met to leave the COM apartement */
382   g_mutex_lock (&sink->com_deinit_lock);
383   g_cond_wait (&sink->com_uninitialize, &sink->com_deinit_lock);
384
385   CoUninitialize ();
386   GST_INFO_OBJECT (sink, "COM uninitialized successfully");
387   sink->comInitialized = FALSE;
388   g_cond_signal (&sink->com_uninitialized);
389   g_mutex_unlock (&sink->com_deinit_lock);
390 }
391
392 static GstCaps *
393 gst_dshowvideosink_get_caps (GstBaseSink * basesink, GstCaps * filter)
394 {
395   GstDshowVideoSink *sink = GST_DSHOWVIDEOSINK (basesink);
396   GstCaps *ret = NULL;
397
398   return ret;
399 }
400
401 static void dump_available_media_types (IPin *pin)
402 {
403   /* Enumerate all media types on this pin, output info about them */
404   IEnumMediaTypes *enumerator = NULL;
405   AM_MEDIA_TYPE *type;
406   GstCaps *caps;
407   int i = 0;
408
409   GST_INFO ("Enumerating media types on pin %p", pin);
410
411   pin->EnumMediaTypes (&enumerator);
412
413   while (enumerator->Next (1, &type, NULL) == S_OK) {
414     i++;
415     caps = gst_directshow_media_type_to_caps (type);
416
417     if (caps) {
418       gchar *str = gst_caps_to_string (caps);
419       GST_INFO ("Type %d: converted to caps \"%s\"", i, str);
420       g_free (str);
421
422       gst_caps_unref (caps);
423     }
424     else
425       GST_INFO ("Failed to convert type to GstCaps");
426
427     DeleteMediaType (type);
428   }
429   GST_INFO ("Enumeration complete");
430
431   enumerator->Release();
432 }
433
434 static void
435 dump_all_pin_media_types (IBaseFilter *filter)
436 {
437   IEnumPins *enumpins = NULL;
438   IPin *pin = NULL;
439   HRESULT hres; 
440
441   hres = filter->EnumPins (&enumpins);
442   if (FAILED(hres)) {
443     GST_WARNING ("Cannot enumerate pins on filter");
444     return;
445   }
446
447   GST_INFO ("Enumerating pins on filter %p", filter);
448   while (enumpins->Next (1, &pin, NULL) == S_OK)
449   {
450     IMemInputPin *meminputpin;
451     PIN_DIRECTION pindir;
452     hres = pin->QueryDirection (&pindir);
453
454     GST_INFO ("Found a pin with direction: %s", (pindir == PINDIR_INPUT)? "input": "output");
455     dump_available_media_types (pin);
456
457     hres = pin->QueryInterface (
458             IID_IMemInputPin, (void **) &meminputpin);
459     if (hres == S_OK) {
460       GST_INFO ("Pin is a MemInputPin (push mode): %p", meminputpin);
461       meminputpin->Release();
462     }
463     else
464       GST_INFO ("Pin is not a MemInputPin (pull mode?): %p", pin);
465
466     pin->Release();
467   }
468   enumpins->Release();
469 }
470
471 gboolean 
472 gst_dshow_get_pin_from_filter (IBaseFilter *filter, PIN_DIRECTION pindir, IPin **pin)
473 {
474   gboolean ret = FALSE;
475   IEnumPins *enumpins = NULL;
476   IPin *pintmp = NULL;
477   HRESULT hres; 
478   *pin = NULL;
479
480   hres = filter->EnumPins (&enumpins);
481   if (FAILED(hres)) {
482     return ret;
483   }
484
485   while (enumpins->Next (1, &pintmp, NULL) == S_OK)
486   {
487     PIN_DIRECTION pindirtmp;
488     hres = pintmp->QueryDirection (&pindirtmp);
489     if (hres == S_OK && pindir == pindirtmp) {
490       *pin = pintmp;
491       ret = TRUE;
492       break;
493     }
494     pintmp->Release ();
495   }
496   enumpins->Release ();
497
498   return ret;
499 }
500
501 static void 
502 gst_dshowvideosink_handle_event (GstDshowVideoSink *sink)
503 {
504   if (sink->filter_media_event) {
505     long evCode;
506     LONG_PTR param1, param2;
507     while (SUCCEEDED (sink->filter_media_event->GetEvent(&evCode, &param1, &param2, 0)))
508     {
509       GST_INFO_OBJECT (sink, "Received DirectShow graph event code 0x%x", evCode);
510       sink->filter_media_event->FreeEventParams(evCode, param1, param2);
511     }
512   }
513 }
514
515 /* WNDPROC for application-supplied windows */
516 LRESULT APIENTRY WndProcHook (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
517 {
518   /* Handle certain actions specially on the window passed to us.
519    * Then forward back to the original window.
520    */
521   GstDshowVideoSink *sink = (GstDshowVideoSink *)GetProp (hWnd, (LPCSTR)"GstDShowVideoSink");
522   g_assert (sink != NULL);
523
524   switch (message) {
525     case WM_GRAPH_NOTIFY:
526       gst_dshowvideosink_handle_event (sink);
527       return 0;
528     case WM_PAINT:
529       sink->renderersupport->PaintWindow ();
530       break;
531     case WM_MOVE:
532     case WM_SIZE:
533       sink->renderersupport->MoveWindow ();
534       break;
535     case WM_DISPLAYCHANGE:
536       sink->renderersupport->DisplayModeChanged();
537       break;
538     case WM_ERASEBKGND:
539       /* DirectShow docs recommend ignoring this message to avoid flicker */
540       return TRUE;
541     case WM_CLOSE:
542       sink->window_closed = TRUE;
543   }
544   return CallWindowProc (sink->prevWndProc, hWnd, message, wParam, lParam);
545 }
546
547 /* WndProc for our default window, if the application didn't supply one */
548 LRESULT APIENTRY 
549 WndProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
550 {
551   GstDshowVideoSink *sink = (GstDshowVideoSink *)GetWindowLongPtr (hWnd, GWLP_USERDATA);
552
553   if (!sink) {
554     /* I think these happen before we have a chance to set our userdata pointer */
555     GST_DEBUG ("No sink!");
556     return DefWindowProc (hWnd, message, wParam, lParam);
557   }
558
559   //GST_DEBUG_OBJECT (sink, "Got a window message for %x, %x", hWnd, message);
560
561   switch (message) {
562     case WM_GRAPH_NOTIFY:
563       GST_LOG_OBJECT (sink, "GRAPH_NOTIFY WINDOW MESSAGE");
564       gst_dshowvideosink_handle_event (sink);
565       return 0;
566     case WM_PAINT:
567       sink->renderersupport->PaintWindow ();
568       break;
569     case WM_MOVE:
570     case WM_SIZE:
571       sink->renderersupport->MoveWindow ();
572       break;
573     case WM_DISPLAYCHANGE:
574       sink->renderersupport->DisplayModeChanged();
575       break;
576     case WM_ERASEBKGND:
577       /* DirectShow docs recommend ignoring this message */
578       return TRUE;
579     case WM_CLOSE:
580       sink->renderersupport->DestroyWindow ();
581       sink->window_closed = TRUE;
582       PostQuitMessage (WM_QUIT);
583       return 0;
584   }
585
586   return DefWindowProc (hWnd, message, wParam, lParam);
587 }
588
589 static gpointer
590 gst_dshowvideosink_window_thread (GstDshowVideoSink * sink)
591 {
592   WNDCLASS WndClass;
593   int width, height;
594   int offx, offy;
595   DWORD exstyle, style;
596
597   memset (&WndClass, 0, sizeof (WNDCLASS));
598   WndClass.style = CS_HREDRAW | CS_VREDRAW;
599   WndClass.hInstance = GetModuleHandle (NULL);
600   WndClass.lpszClassName = (LPCSTR)"GST-DShowSink";
601   WndClass.hbrBackground = (HBRUSH) GetStockObject (BLACK_BRUSH);
602   WndClass.cbClsExtra = 0;
603   WndClass.cbWndExtra = 0;
604   WndClass.lpfnWndProc = WndProc;
605   WndClass.hCursor = LoadCursor (NULL, IDC_ARROW);
606   RegisterClass (&WndClass);
607
608   if (sink->full_screen) {
609     /* This doesn't seem to work, it returns the wrong values! But when we
610      * later use ShowWindow to show it maximized, it goes to full-screen
611      * anyway. TODO: Figure out why. */
612     width = GetSystemMetrics (SM_CXFULLSCREEN);
613     height = GetSystemMetrics (SM_CYFULLSCREEN);
614     offx = 0;
615     offy = 0;
616
617     style = WS_POPUP; /* No window decorations */
618     exstyle = 0;
619   }
620   else {
621     /* By default, create a normal top-level window, the size 
622      * of the video.
623      */
624     RECT rect;
625     AM_MEDIA_TYPE pmt = (AM_MEDIA_TYPE)sink->mediatype;
626     VIDEOINFOHEADER *vi = (VIDEOINFOHEADER *)pmt.pbFormat;
627
628     if (vi == NULL)
629     {
630         GST_ELEMENT_ERROR (sink, RESOURCE, NOT_FOUND, ("Unknown media format"), (NULL));
631         return NULL;
632     }
633
634     /* rcTarget is the aspect-ratio-corrected size of the video. */
635     width = vi->rcTarget.right + GetSystemMetrics (SM_CXSIZEFRAME) * 2;
636     height = vi->rcTarget.bottom + GetSystemMetrics (SM_CYCAPTION) +
637         (GetSystemMetrics (SM_CYSIZEFRAME) * 2);
638
639     SystemParametersInfo (SPI_GETWORKAREA, NULL, &rect, 0);
640     int screenwidth = rect.right - rect.left;
641     int screenheight = rect.bottom - rect.top;
642     offx = rect.left;
643     offy = rect.top;
644
645     /* Make it fit into the screen without changing the
646      * aspect ratio. */
647     if (width > screenwidth) {
648       double ratio = (double)screenwidth/(double)width;
649       width = screenwidth;
650       height = (int)(height * ratio);
651     }
652     if (height > screenheight) {
653       double ratio = (double)screenheight/(double)height;
654       height = screenheight;
655       width = (int)(width * ratio);
656     }
657
658     style = WS_OVERLAPPEDWINDOW; /* Normal top-level window */
659     exstyle = 0;
660   }
661
662   HWND video_window = CreateWindowEx (exstyle, (LPCSTR)"GST-DShowSink",
663       (LPCSTR)"GStreamer DirectShow sink default window",
664       style, offx, offy, width, height, NULL, NULL,
665       WndClass.hInstance, NULL);
666   if (video_window == NULL) {
667     GST_ERROR_OBJECT (sink, "Failed to create window!");
668     return NULL;
669   }
670
671   sink->is_new_window = TRUE;
672
673   SetWindowLongPtr (video_window, GWLP_USERDATA, (LONG_PTR)sink);
674
675   sink->window_id = video_window;
676
677   /* signal application we created a window */
678   gst_video_overlay_got_window_handle (GST_VIDEO_OVERLAY (sink),
679       (gulong)video_window);
680
681   /* Set the renderer's clipping window */
682   if (!sink->renderersupport->SetRendererWindow (video_window)) {
683     GST_WARNING_OBJECT (sink, "Failed to set video clipping window on filter %p", sink->renderersupport);
684   }
685
686   /* Now show the window, as appropriate */
687   if (sink->full_screen) {
688     ShowWindow (video_window, SW_SHOWMAXIMIZED);
689     ShowCursor (FALSE);
690   }
691   else
692     ShowWindow (video_window, SW_SHOWNORMAL);
693
694   /* Trigger the initial paint of the window */
695   UpdateWindow (video_window);
696
697   ReleaseSemaphore (sink->window_created_signal, 1, NULL);
698
699   /* start message loop processing our default window messages */
700   while (1) {
701     MSG msg;
702
703     if (GetMessage (&msg, video_window, 0, 0) <= 0) {
704       GST_LOG_OBJECT (sink, "our window received WM_QUIT or error.");
705       break;
706     }
707     DispatchMessage (&msg);
708   }
709
710   return NULL;
711 }
712
713 static gboolean
714 gst_dshowvideosink_create_default_window (GstDshowVideoSink * sink)
715 {
716   sink->window_created_signal = CreateSemaphore (NULL, 0, 1, NULL);
717   if (sink->window_created_signal == NULL)
718     goto failed;
719
720   sink -> window_thread = g_thread_new ("windowthread",
721                                         (GThreadFunc) gst_dshowvideosink_window_thread,
722                                         sink);
723
724   /* wait maximum 10 seconds for window to be created */
725   if (WaitForSingleObject (sink->window_created_signal,
726           10000) != WAIT_OBJECT_0)
727     goto failed;
728
729   CloseHandle (sink->window_created_signal);
730   return TRUE;
731
732 failed:
733   CloseHandle (sink->window_created_signal);
734   GST_ELEMENT_ERROR (sink, RESOURCE, WRITE,
735       ("Error creating our default window"), (NULL));
736
737   return FALSE;
738 }
739
740 static void gst_dshowvideosink_set_window_for_renderer (GstDshowVideoSink *sink)
741 {
742   WNDPROC prevWndProc = (WNDPROC)GetWindowLongPtr (sink->window_id, GWLP_WNDPROC);
743   if (prevWndProc == WndProcHook) {
744     /* The WndProc already points to our hook. Something has gone wrong
745      * somewhere else and this safety net prevents an infinite recursion */
746     return;
747   }
748
749   /* Application has requested a specific window ID */
750   sink->prevWndProc = (WNDPROC) SetWindowLongPtr (sink->window_id, GWLP_WNDPROC, (LONG_PTR)WndProcHook);
751   GST_DEBUG_OBJECT (sink, "Set wndproc to %p from %p", WndProcHook, sink->prevWndProc);
752   SetProp (sink->window_id, (LPCSTR)"GstDShowVideoSink", sink);
753   /* This causes the new WNDPROC to become active */
754   SetWindowPos (sink->window_id, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
755
756   if (!sink->renderersupport->SetRendererWindow (sink->window_id)) {
757     GST_WARNING_OBJECT (sink, "Failed to set HWND %x on renderer", sink->window_id);
758     return;
759   }
760   sink->is_new_window = FALSE;
761
762   /* This tells the renderer where the window is located, needed to 
763    * start drawing in the right place.  */
764   sink->renderersupport->MoveWindow();
765   GST_INFO_OBJECT (sink, "Set renderer window to %x", sink->window_id);
766 }
767
768 static void
769 gst_dshowvideosink_prepare_window (GstDshowVideoSink *sink)
770 {
771   HRESULT hres;
772
773   /* Give the app a last chance to supply a window id */
774   if (!sink->window_id) {
775     gst_video_overlay_prepare_window_handle (GST_VIDEO_OVERLAY (sink));
776   }
777
778   /* If the app supplied one, use it. Otherwise, go ahead
779    * and create (and use) our own window */
780   if (sink->window_id) {
781     gst_dshowvideosink_set_window_for_renderer (sink);
782   }
783   else {
784     gst_dshowvideosink_create_default_window (sink);
785   }
786
787   if (sink->filter_media_event) {
788     sink->filter_media_event->Release();
789     sink->filter_media_event = NULL;
790   }
791
792   hres = sink->filter_graph->QueryInterface(
793           IID_IMediaEventEx, (void **) &sink->filter_media_event);
794
795   if (FAILED (hres)) {
796     GST_WARNING_OBJECT (sink, "Failed to get IMediaEventEx");
797   }
798   else {
799     hres = sink->filter_media_event->SetNotifyWindow ((OAHWND)sink->window_id,
800             WM_GRAPH_NOTIFY, 0);
801     GST_DEBUG_OBJECT (sink, "SetNotifyWindow(%p) returned %x", sink->window_id, hres);
802   }
803 }
804
805 static gboolean
806 gst_dshowvideosink_connect_graph (GstDshowVideoSink *sink)
807 {
808   HRESULT hres;
809   IPin *srcpin;
810   IPin *sinkpin;
811
812   GST_INFO_OBJECT (sink, "Connecting DirectShow pins");
813
814   srcpin = sink->fakesrc->GetOutputPin();
815
816   gst_dshow_get_pin_from_filter (sink->renderersupport->GetFilter(), PINDIR_INPUT, 
817       &sinkpin);
818   if (!sinkpin) {
819     GST_WARNING_OBJECT (sink, "Cannot get input pin from Renderer");
820     return FALSE;
821   }
822
823   /* Be warned that this call WILL deadlock unless you call it from
824    * the main thread. Thus, we call this from the state change, not from
825    * setcaps (which happens in a streaming thread).
826    */
827   hres = sink->filter_graph->ConnectDirect (
828            srcpin, sinkpin, NULL);
829   if (FAILED (hres)) {
830     GST_WARNING_OBJECT (sink, "Could not connect pins: %x", hres);
831     sinkpin->Release();
832     return FALSE;
833   }
834   sinkpin->Release();
835   return TRUE;
836 }
837
838 static GstStateChangeReturn
839 gst_dshowvideosink_start_graph (GstDshowVideoSink *sink)
840 {
841   IMediaControl *control = NULL;
842   HRESULT hres;
843   GstStateChangeReturn ret;
844
845   GST_DEBUG_OBJECT (sink, "Connecting and starting DirectShow graph");
846
847   hres = sink->filter_graph->QueryInterface(
848           IID_IMediaControl, (void **) &control);
849
850   if (FAILED (hres)) {
851     GST_WARNING_OBJECT (sink, "Failed to get IMediaControl interface");
852     ret = GST_STATE_CHANGE_FAILURE;
853     goto done;
854   }
855
856   GST_INFO_OBJECT (sink, "Running DirectShow graph");
857   hres = control->Run();
858   if (FAILED (hres)) {
859     GST_ERROR_OBJECT (sink,
860         "Failed to run the directshow graph (error=%x)", hres);
861     ret = GST_STATE_CHANGE_FAILURE;
862     goto done;
863   }
864   
865   GST_DEBUG_OBJECT (sink, "DirectShow graph is now running");
866   ret = GST_STATE_CHANGE_SUCCESS;
867
868 done:
869   if (control)
870     control->Release();
871
872   return ret;
873 }
874 static GstStateChangeReturn
875 gst_dshowvideosink_pause_graph (GstDshowVideoSink *sink)
876 {
877   IMediaControl *control = NULL;
878   GstStateChangeReturn ret;
879   HRESULT hres;
880
881   hres = sink->filter_graph->QueryInterface(
882           IID_IMediaControl, (void **) &control);
883   if (FAILED (hres)) {
884     GST_WARNING_OBJECT (sink, "Failed to get IMediaControl interface");
885     ret = GST_STATE_CHANGE_FAILURE;
886     goto done;
887   }
888
889   GST_INFO_OBJECT (sink, "Pausing DirectShow graph");
890   hres = control->Pause();
891   if (FAILED (hres)) {
892     GST_WARNING_OBJECT (sink,
893         "Can't pause the directshow graph (error=%x)", hres);
894     ret = GST_STATE_CHANGE_FAILURE;
895     goto done;
896   }
897
898   ret = GST_STATE_CHANGE_SUCCESS;
899
900 done:
901   if (control)
902     control->Release();
903
904   return ret;
905 }
906
907 static GstStateChangeReturn
908 gst_dshowvideosink_stop_graph (GstDshowVideoSink *sink)
909 {
910   IMediaControl *control = NULL;
911   GstStateChangeReturn ret;
912   HRESULT hres;
913   IPin *sinkpin;
914
915   hres = sink->filter_graph->QueryInterface(
916           IID_IMediaControl, (void **) &control);
917   if (FAILED (hres)) {
918     GST_WARNING_OBJECT (sink, "Failed to get IMediaControl interface");
919     ret = GST_STATE_CHANGE_FAILURE;
920     goto done;
921   }
922
923   GST_INFO_OBJECT (sink, "Stopping DirectShow graph");
924   hres = control->Stop();
925   if (FAILED (hres)) {
926     GST_WARNING_OBJECT (sink,
927         "Can't stop the directshow graph (error=%x)", hres);
928     ret = GST_STATE_CHANGE_FAILURE;
929     goto done;
930   }
931
932   sink->filter_graph->Disconnect(sink->fakesrc->GetOutputPin());
933
934   gst_dshow_get_pin_from_filter (sink->renderersupport->GetFilter(), PINDIR_INPUT, 
935       &sinkpin);
936   sink->filter_graph->Disconnect(sinkpin);
937   sinkpin->Release();
938
939   GST_DEBUG_OBJECT (sink, "DirectShow graph has stopped");
940
941   if (sink->window_id) {
942     /* Return control of application window */
943     SetWindowLongPtr (sink->window_id, GWLP_WNDPROC, (LONG_PTR)sink->prevWndProc);
944     RemoveProp (sink->window_id, (LPCSTR)"GstDShowVideoSink");
945     SetWindowPos (sink->window_id, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
946     sink->prevWndProc = NULL;
947   }
948   sink->connected = FALSE;
949
950   ret = GST_STATE_CHANGE_SUCCESS;
951
952 done:
953   if (control)
954     control->Release();
955
956   return ret;
957 }
958
959 static GstStateChangeReturn
960 gst_dshowvideosink_change_state (GstElement * element, GstStateChange transition)
961 {
962   GstDshowVideoSink *sink = GST_DSHOWVIDEOSINK (element);
963   GstStateChangeReturn ret, rettmp;
964
965   switch (transition) {
966     case GST_STATE_CHANGE_NULL_TO_READY:
967       break;
968     case GST_STATE_CHANGE_READY_TO_PAUSED:
969       break;
970     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
971       ret = gst_dshowvideosink_start_graph (sink);
972       if (ret == GST_STATE_CHANGE_FAILURE)
973         return ret;
974       sink->graph_running = TRUE;
975       break;
976   }
977
978   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
979
980   switch (transition) {
981     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
982       GST_DSHOWVIDEOSINK_GRAPH_LOCK(sink);
983       rettmp = gst_dshowvideosink_pause_graph (sink);
984       if (rettmp == GST_STATE_CHANGE_FAILURE)
985         ret = rettmp;
986       sink->graph_running = FALSE;
987       GST_DSHOWVIDEOSINK_GRAPH_UNLOCK(sink);
988       break;
989     case GST_STATE_CHANGE_PAUSED_TO_READY:
990       GST_DSHOWVIDEOSINK_GRAPH_LOCK(sink);
991       rettmp = gst_dshowvideosink_stop_graph (sink);
992       if (rettmp == GST_STATE_CHANGE_FAILURE)
993         ret = rettmp;
994       sink->graph_running = FALSE;
995       GST_DSHOWVIDEOSINK_GRAPH_UNLOCK(sink);
996       break;
997     case GST_STATE_CHANGE_READY_TO_NULL:
998       gst_dshowvideosink_clear (sink);
999       break;
1000   }
1001
1002   return ret;
1003 }
1004
1005 class EVRSupport : public RendererSupport
1006 {
1007 private:
1008   GstDshowVideoSink *sink;
1009   IBaseFilter *filter;
1010   IMFGetService *service;
1011   IMFVideoDisplayControl *control;
1012   HWND video_window;
1013
1014 public:
1015   EVRSupport (GstDshowVideoSink *sink) : 
1016       sink(sink),
1017       filter(NULL),
1018       service(NULL),
1019       control(NULL)
1020   {
1021   }
1022
1023   ~EVRSupport() {
1024     if (control)
1025       control->Release();
1026     if (service)
1027       service->Release();
1028     if (filter)
1029       filter->Release();
1030   }
1031
1032   const char *GetName() {
1033     return "EnhancedVideoRenderer";
1034   }
1035
1036   IBaseFilter *GetFilter() {
1037     return filter;
1038   }
1039
1040   gboolean CheckOS () {
1041     OSVERSIONINFO info;
1042     info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
1043     GetVersionEx (&info);
1044
1045     if (info.dwMajorVersion < 6) {
1046       return false;
1047     }
1048     else {
1049       return true;
1050     }
1051   }
1052
1053   gboolean Configure() {
1054     HRESULT hres;
1055
1056     if (!this->CheckOS ()) {
1057       GST_DEBUG_OBJECT (sink, "Windows Vista is required at least for EVR to work");
1058       return FALSE;
1059     }
1060
1061     hres = CoCreateInstance (CLSID_EnhancedVideoRenderer, NULL, CLSCTX_INPROC,
1062         IID_IBaseFilter, (LPVOID *) &filter);
1063     GST_DEBUG_OBJECT (sink, "cocreateinstance returned %d", hres);
1064     if (FAILED (hres)) {
1065       GST_ERROR_OBJECT (sink, 
1066           "Can't create an instance of renderer (error=%x)",
1067           hres);
1068       return FALSE;
1069     }
1070
1071     hres = filter->QueryInterface (IID_IMFGetService,
1072           (void **) &service);
1073     if (FAILED (hres)) {
1074       GST_WARNING_OBJECT (sink, "EVR service interface missing: %x", hres);
1075       return FALSE;
1076     }
1077
1078     hres = service->GetService (MR_VIDEO_RENDER_SERVICE, 
1079           IID_IMFVideoDisplayControl, (void **) &control);
1080     if (FAILED (hres)) {
1081       GST_WARNING_OBJECT (sink, "EVR control service missing: %x", hres);
1082       return FALSE;
1083     }
1084
1085     SetAspectRatioMode();
1086     return TRUE;
1087   }
1088
1089   void SetAspectRatioMode() {
1090     if (sink->keep_aspect_ratio) {
1091       control->SetAspectRatioMode(MFVideoARMode_PreservePicture);
1092     }
1093     else {
1094       control->SetAspectRatioMode(MFVideoARMode_None);
1095     }
1096   }
1097
1098   gboolean SetRendererWindow(HWND window) {
1099     video_window = window;
1100     HRESULT hres = control->SetVideoWindow (video_window);
1101     if (FAILED (hres)) {
1102       GST_WARNING_OBJECT (sink, "Failed to set video clipping window on filter %p: %x", filter, hres);
1103       return FALSE;
1104     }
1105     return TRUE;
1106   }
1107
1108   void PaintWindow()
1109   {
1110     HRESULT hr;
1111     PAINTSTRUCT ps;
1112     HDC         hdc;
1113     RECT        rcClient;
1114
1115     GetClientRect(video_window, &rcClient);
1116     hdc = BeginPaint(video_window, &ps);
1117
1118     hr = control->RepaintVideo();
1119
1120     EndPaint(video_window, &ps);
1121   }
1122
1123   void MoveWindow()
1124   {
1125     HRESULT hr;
1126     RECT rect;
1127
1128     // Track the movement of the container window and resize as needed
1129     GetClientRect(video_window, &rect);
1130     hr = control->SetVideoPosition(NULL, &rect);
1131   }
1132
1133   void DisplayModeChanged() {
1134   }
1135
1136   void DestroyWindow() {
1137     ::DestroyWindow (video_window);
1138   }
1139 };
1140
1141 class VMR9Support : public RendererSupport
1142 {
1143 private:
1144   GstDshowVideoSink *sink;
1145   IBaseFilter *filter;
1146   IVMRWindowlessControl9 *control;
1147   IVMRFilterConfig9 *config;
1148   HWND video_window;
1149
1150 public:
1151   VMR9Support (GstDshowVideoSink *sink) : 
1152       sink(sink), 
1153       filter(NULL),
1154       control(NULL),
1155       config(NULL)
1156   {
1157   }
1158
1159   ~VMR9Support() {
1160     if (control)
1161       control->Release();
1162     if (config)
1163       config->Release();
1164     if (filter)
1165       filter->Release();
1166   }
1167
1168   const char *GetName() {
1169     return "VideoMixingRenderer9";
1170   }
1171
1172   IBaseFilter *GetFilter() {
1173     return filter;
1174   }
1175
1176   gboolean Configure() {
1177     HRESULT hres;
1178
1179     hres = CoCreateInstance (CLSID_VideoMixingRenderer9, NULL, CLSCTX_INPROC,
1180         IID_IBaseFilter, (LPVOID *) &filter);
1181     if (FAILED (hres)) {
1182       GST_ERROR_OBJECT (sink, 
1183           "Can't create an instance of renderer (error=%x)",
1184           hres);
1185       return FALSE;
1186     }
1187
1188     hres = filter->QueryInterface (
1189           IID_IVMRFilterConfig9, (void **) &config);
1190     if (FAILED (hres)) {
1191       GST_WARNING_OBJECT (sink, "VMR9 filter config interface missing: %x", hres);
1192       return FALSE;
1193     }
1194
1195     hres = config->SetRenderingMode (VMR9Mode_Windowless);
1196     if (FAILED (hres)) {
1197       GST_WARNING_OBJECT (sink, "VMR9 couldn't be set to windowless mode: %x", hres);
1198       return FALSE;
1199     }
1200     else {
1201       GST_DEBUG_OBJECT (sink, "Set VMR9 (%p) to windowless mode!", filter);
1202     }
1203
1204     /* We can't QI to this until _after_ we've been set to windowless mode. 
1205      * Apparently this is against the rules in COM, but that's how it is... */
1206     hres = filter->QueryInterface (
1207           IID_IVMRWindowlessControl9, (void **) &control);
1208     if (FAILED (hres)) {
1209       GST_WARNING_OBJECT (sink, "VMR9 windowless control interface missing: %x", hres);
1210       return FALSE;
1211     }
1212
1213     SetAspectRatioMode();
1214     return TRUE;
1215   }
1216
1217   void SetAspectRatioMode() {
1218     if (sink->keep_aspect_ratio) {
1219       control->SetAspectRatioMode(VMR9ARMode_LetterBox);
1220     }
1221     else {
1222       control->SetAspectRatioMode(VMR9ARMode_None);
1223     }
1224   }
1225
1226   gboolean SetRendererWindow(HWND window) {
1227     video_window = window;
1228     HRESULT hres = control->SetVideoClippingWindow (video_window);
1229     if (FAILED (hres)) {
1230       GST_WARNING_OBJECT (sink, "Failed to set video clipping window on filter %p: %x", filter, hres);
1231       return FALSE;
1232     }
1233     return TRUE;
1234   }
1235
1236   void PaintWindow()
1237   {
1238     HRESULT hr;
1239     PAINTSTRUCT ps;
1240     HDC         hdc;
1241     RECT        rcClient;
1242
1243     GetClientRect(video_window, &rcClient);
1244     hdc = BeginPaint(video_window, &ps);
1245
1246     hr = control->RepaintVideo(video_window, hdc);
1247
1248     EndPaint(video_window, &ps);
1249   }
1250
1251   void MoveWindow()
1252   {
1253     HRESULT hr;
1254     RECT rect;
1255
1256     // Track the movement of the container window and resize as needed
1257     GetClientRect(video_window, &rect);
1258     hr = control->SetVideoPosition(NULL, &rect);
1259   }
1260
1261   void DisplayModeChanged() {
1262     control->DisplayModeChanged();
1263   }
1264
1265   void DestroyWindow() {
1266     ::DestroyWindow (video_window);
1267   }
1268 };
1269
1270 class VMR7Support : public RendererSupport
1271 {
1272 private:
1273   GstDshowVideoSink *sink;
1274   IBaseFilter *filter;
1275   IVMRWindowlessControl *control;
1276   IVMRFilterConfig *config;
1277   HWND video_window;
1278
1279 public:
1280   VMR7Support (GstDshowVideoSink *sink) : 
1281       sink(sink), 
1282       filter(NULL),
1283       control(NULL),
1284       config(NULL)
1285   {
1286   }
1287
1288   ~VMR7Support() {
1289     if (control)
1290       control->Release();
1291     if (config)
1292       config->Release();
1293     if (filter)
1294       filter->Release();
1295   }
1296
1297   const char *GetName() {
1298     return "VideoMixingRenderer";
1299   }
1300
1301   IBaseFilter *GetFilter() {
1302     return filter;
1303   }
1304
1305   gboolean Configure() {
1306     HRESULT hres;
1307
1308     hres = CoCreateInstance (CLSID_VideoMixingRenderer, NULL, CLSCTX_INPROC,
1309         IID_IBaseFilter, (LPVOID *) &filter);
1310     if (FAILED (hres)) {
1311       GST_ERROR_OBJECT (sink, 
1312           "Can't create an instance of renderer (error=%x)",
1313           hres);
1314       return FALSE;
1315     }
1316
1317     hres = filter->QueryInterface (
1318           IID_IVMRFilterConfig, (void **) &config);
1319     if (FAILED (hres)) {
1320       GST_WARNING_OBJECT (sink, "VMR filter config interface missing: %x", hres);
1321       return FALSE;
1322     }
1323
1324     hres = config->SetRenderingMode (VMRMode_Windowless);
1325     if (FAILED (hres)) {
1326       GST_WARNING_OBJECT (sink, "VMR couldn't be set to windowless mode: %x", hres);
1327       return FALSE;
1328     }
1329     else {
1330       GST_DEBUG_OBJECT (sink, "Set VMR (%p) to windowless mode!", filter);
1331     }
1332
1333     hres = filter->QueryInterface (
1334           IID_IVMRWindowlessControl, (void **) &control);
1335     if (FAILED (hres)) {
1336       GST_WARNING_OBJECT (sink, "VMR windowless control interface missing: %x", hres);
1337       return FALSE;
1338     }
1339
1340     SetAspectRatioMode();
1341     return TRUE;
1342   }
1343
1344   void SetAspectRatioMode() {
1345     if (sink->keep_aspect_ratio) {
1346       control->SetAspectRatioMode(VMR_ARMODE_LETTER_BOX);
1347     }
1348     else {
1349       control->SetAspectRatioMode(VMR_ARMODE_NONE);
1350     }
1351   }
1352
1353   gboolean SetRendererWindow(HWND window) {
1354     video_window = window;
1355     HRESULT hres = control->SetVideoClippingWindow (video_window);
1356     if (FAILED (hres)) {
1357       GST_WARNING_OBJECT (sink, "Failed to set video clipping window on filter %p: %x", filter, hres);
1358       return FALSE;
1359     }
1360     return TRUE;
1361   }
1362
1363   void PaintWindow()
1364   {
1365     HRESULT hr;
1366     PAINTSTRUCT ps;
1367     HDC         hdc;
1368     RECT        rcClient;
1369
1370     GetClientRect(video_window, &rcClient);
1371     hdc = BeginPaint(video_window, &ps);
1372
1373     hr = control->RepaintVideo(video_window, hdc);
1374
1375     EndPaint(video_window, &ps);
1376   }
1377
1378   void MoveWindow()
1379   {
1380     HRESULT hr;
1381     RECT rect;
1382
1383     // Track the movement of the container window and resize as needed
1384     GetClientRect(video_window, &rect);
1385     hr = control->SetVideoPosition(NULL, &rect);
1386   }
1387
1388   void DisplayModeChanged() {
1389     control->DisplayModeChanged();
1390   }
1391
1392   void DestroyWindow() {
1393     ::DestroyWindow (video_window);
1394   }
1395 };
1396
1397 static gboolean 
1398 gst_dshowvideosink_create_renderer (GstDshowVideoSink *sink) 
1399 {
1400   GST_DEBUG_OBJECT (sink, "Trying to create renderer '%s'", "EVR");
1401
1402   RendererSupport *support = NULL;
1403
1404   if (sink->preferredrenderer) {
1405     if (!strcmp (sink->preferredrenderer, "EVR")) {
1406       GST_INFO_OBJECT (sink, "Forcing use of EVR");
1407       support = new EVRSupport (sink);
1408     }
1409     else if (!strcmp (sink->preferredrenderer, "VMR9")) {
1410       GST_INFO_OBJECT (sink, "Forcing use of VMR9");
1411       support = new VMR9Support (sink);
1412     }
1413     else if (!strcmp (sink->preferredrenderer, "VMR")) {
1414       GST_INFO_OBJECT (sink, "Forcing use of VMR");
1415       support = new VMR7Support (sink);
1416     }
1417     else {
1418       GST_ERROR_OBJECT (sink, "Unknown sink type '%s'", sink->preferredrenderer);
1419       return FALSE;
1420     }
1421
1422     if (!support->Configure()) {
1423       GST_ERROR_OBJECT (sink, "Couldn't configure selected renderer");
1424       delete support;
1425       return FALSE;
1426     }
1427     goto done;
1428   }
1429
1430   support = new EVRSupport (sink);
1431   if (!support->Configure ()) {
1432     GST_INFO_OBJECT (sink, "Failed to configure EVR, trying VMR9");
1433     delete support;
1434     support = new VMR9Support (sink);
1435     if (!support->Configure()) {
1436       GST_INFO_OBJECT (sink, "Failed to configure VMR9, trying VMR7");
1437       delete support;
1438       support = new VMR7Support (sink);
1439       if (!support->Configure()) {
1440         GST_ERROR_OBJECT (sink, "Failed to configure VMR9 or VMR7");
1441         delete support;
1442         return FALSE;
1443       }
1444     }
1445   }
1446
1447 done:
1448   sink->renderersupport = support;
1449   return TRUE;
1450 }
1451
1452 static gboolean
1453 gst_dshowvideosink_build_filtergraph (GstDshowVideoSink *sink)
1454 {
1455   HRESULT hres;
1456
1457   /* Build our DirectShow FilterGraph, looking like: 
1458    *
1459    *    [ fakesrc ] -> [ sink filter ]
1460    *
1461    * so we can feed data in through the fakesrc.
1462    *
1463    * The sink filter can be one of our supported filters: VMR9 (VMR7?, EMR?)
1464    */
1465
1466   hres = CoCreateInstance (CLSID_FilterGraph, NULL, CLSCTX_INPROC,
1467       IID_IFilterGraph, (LPVOID *) & sink->filter_graph);
1468   if (FAILED (hres)) {
1469     GST_ERROR_OBJECT (sink, 
1470           "Can't create an instance of the dshow graph manager (error=%x)", hres);
1471     goto error;
1472   }
1473
1474   sink->fakesrc = new VideoFakeSrc();
1475
1476   IBaseFilter *filter;
1477   hres = sink->fakesrc->QueryInterface (
1478           IID_IBaseFilter, (void **) &filter);
1479   if (FAILED (hres)) {
1480     GST_ERROR_OBJECT (sink, "Could not QI fakesrc to IBaseFilter");
1481     goto error;
1482   }
1483
1484   hres = sink->filter_graph->AddFilter (filter, L"fakesrc");
1485   if (FAILED (hres)) {
1486     GST_ERROR_OBJECT (sink,
1487         "Can't add our fakesrc filter to the graph (error=%x)", hres);
1488     goto error;
1489   }
1490
1491   if (!gst_dshowvideosink_create_renderer (sink)) {
1492     GST_ERROR_OBJECT (sink, "Could not create a video renderer");
1493     goto error;
1494   }
1495
1496   /* dump_all_pin_media_types (sink->renderer); */
1497
1498   hres =
1499       sink->filter_graph->AddFilter (sink->renderersupport->GetFilter(),
1500       L"renderer");
1501   if (FAILED (hres)) {
1502     GST_ERROR_OBJECT (sink, 
1503           "Can't add renderer to the graph (error=%x)", hres);
1504     goto error;
1505   }
1506
1507   return TRUE;
1508
1509 error:
1510   if (sink->fakesrc) {
1511     sink->fakesrc->Release();
1512     sink->fakesrc = NULL;
1513   }
1514
1515   if (sink->filter_graph) {
1516     sink->filter_graph->Release();
1517     sink->filter_graph = NULL;
1518   }
1519
1520   if (sink->filter_media_event) {
1521     sink->filter_media_event->Release();
1522     sink->filter_media_event = NULL;
1523   }
1524
1525   return FALSE;
1526 }
1527
1528 static gboolean
1529 gst_dshowvideosink_start (GstBaseSink * bsink)
1530 {
1531   HRESULT hres = S_FALSE;
1532   GstDshowVideoSink *sink = GST_DSHOWVIDEOSINK (bsink);
1533
1534   /* Just build the filtergraph; we don't link or otherwise configure it yet */
1535   return gst_dshowvideosink_build_filtergraph (sink);
1536 }
1537
1538 static gboolean
1539 gst_dshowvideosink_set_caps (GstBaseSink * bsink, GstCaps * caps)
1540 {
1541   GstDshowVideoSink *sink = GST_DSHOWVIDEOSINK (bsink);
1542
1543   if (sink->connected) {
1544       IPin *sinkpin;
1545       sink->filter_graph->Disconnect(sink->fakesrc->GetOutputPin());
1546       gst_dshow_get_pin_from_filter (sink->renderersupport->GetFilter(), PINDIR_INPUT, 
1547           &sinkpin);
1548       sink->filter_graph->Disconnect(sinkpin);
1549       sinkpin->Release();
1550   }
1551
1552   if (!gst_caps_to_directshow_media_type (sink, caps, &sink->mediatype)) {
1553     GST_WARNING_OBJECT (sink, "Cannot convert caps to AM_MEDIA_TYPE, rejecting");
1554     return FALSE;
1555   }
1556
1557   GST_DEBUG_OBJECT (sink, "Configuring output pin media type");
1558   /* Now we have an AM_MEDIA_TYPE describing what we're going to send.
1559    * We set this on our DirectShow fakesrc's output pin. 
1560    */
1561   sink->fakesrc->GetOutputPin()->SetMediaType (&sink->mediatype);
1562   GST_DEBUG_OBJECT (sink, "Configured output pin media type");
1563
1564   /* We have configured the output pin media type.
1565   * So, create a window (or start using an application-supplied
1566   * one, then connect the graph */
1567   gst_dshowvideosink_prepare_window (sink);
1568   if (!gst_dshowvideosink_connect_graph (sink)) {
1569     GST_ELEMENT_ERROR (sink, CORE, NEGOTIATION,
1570           ("Failed to initialize DirectShow graph with the input caps"), (NULL));
1571     return FALSE;
1572   }
1573   sink->connected = TRUE;
1574
1575   return TRUE;
1576 }
1577
1578 static gboolean
1579 gst_dshowvideosink_stop (GstBaseSink * bsink)
1580 {
1581   IPin *input_pin = NULL, *output_pin = NULL;
1582   HRESULT hres = S_FALSE;
1583   GstDshowVideoSink *sink = GST_DSHOWVIDEOSINK (bsink);
1584
1585   if (!sink->filter_graph) {
1586     GST_WARNING_OBJECT (sink, "Cannot destroy filter graph; it doesn't exist");
1587     return TRUE;
1588   }
1589   
1590   /* If we created a new window, send the close message and wait until 
1591    * it's closed in the window thread */
1592   if (sink->is_new_window) {
1593     SendMessage (sink->window_id, WM_CLOSE, NULL, NULL);
1594     while (!sink->window_closed);
1595     sink->is_new_window = FALSE;
1596   }
1597
1598   /* Release the renderer */
1599   if (sink->renderersupport) {
1600     delete sink->renderersupport;
1601     sink->renderersupport = NULL;
1602   }
1603
1604   /* Release our dshow fakesrc */
1605   if (sink->fakesrc) {
1606     sink->fakesrc->Release();
1607     sink->fakesrc = NULL;
1608   }
1609
1610   /* Release the filter graph manager */
1611   if (sink->filter_graph) {
1612     sink->filter_graph->Release();
1613     sink->filter_graph = NULL;
1614   }
1615
1616   if (sink->filter_media_event) {
1617     sink->filter_media_event->Release();
1618     sink->filter_media_event = NULL;
1619   }
1620
1621   return TRUE;
1622 }
1623
1624 static GstFlowReturn
1625 gst_dshowvideosink_show_frame (GstVideoSink *vsink, GstBuffer *buffer)
1626 {
1627   GstDshowVideoSink *sink = GST_DSHOWVIDEOSINK (vsink);
1628   GstFlowReturn ret;
1629   GstStateChangeReturn retst;
1630
1631   if (sink->window_closed) {
1632     GST_ELEMENT_ERROR (sink, RESOURCE, NOT_FOUND, ("Output window was closed"), (NULL));
1633     return GST_FLOW_ERROR;
1634   }
1635
1636   GST_DEBUG_OBJECT (sink, "Pushing buffer through fakesrc->renderer");
1637   GST_DSHOWVIDEOSINK_GRAPH_LOCK(sink);
1638   if (!sink->graph_running){
1639     retst = gst_dshowvideosink_start_graph(sink);
1640     if (retst == GST_STATE_CHANGE_FAILURE)
1641       return GST_FLOW_FLUSHING;
1642   }
1643   ret = sink->fakesrc->GetOutputPin()->PushBuffer (buffer);
1644   if (!sink->graph_running){
1645     retst = gst_dshowvideosink_pause_graph(sink);
1646     if (retst == GST_STATE_CHANGE_FAILURE)
1647       return GST_FLOW_FLUSHING;
1648   }
1649   GST_DSHOWVIDEOSINK_GRAPH_UNLOCK(sink);
1650   GST_DEBUG_OBJECT (sink, "Done pushing buffer through fakesrc->renderer: %s", gst_flow_get_name(ret));
1651
1652   return ret;
1653 }
1654
1655 /* TODO: How can we implement these? Figure that out... */
1656 static gboolean
1657 gst_dshowvideosink_unlock (GstBaseSink * bsink)
1658 {
1659   GstDshowVideoSink *sink = GST_DSHOWVIDEOSINK (bsink);
1660
1661   return TRUE;
1662 }
1663
1664 static gboolean
1665 gst_dshowvideosink_unlock_stop (GstBaseSink * bsink)
1666 {
1667   GstDshowVideoSink *sink = GST_DSHOWVIDEOSINK (bsink);
1668
1669   return TRUE;
1670 }
1671
1672 /* TODO: Move all of this into generic code? */
1673
1674 /* Helpers to format GUIDs the same way we find them in the source */
1675 #define GUID_FORMAT "{%.8x, %.4x, %.4x, { %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x, %.2x }}"
1676 #define GUID_ARGS(guid) \
1677     guid.Data1, guid.Data2, guid.Data3, \
1678     guid.Data4[0], guid.Data4[1], guid.Data4[3], guid.Data4[4], \
1679     guid.Data4[5], guid.Data4[6], guid.Data4[7], guid.Data4[8]
1680
1681 static GstCaps *
1682 audio_media_type_to_caps (AM_MEDIA_TYPE *mediatype)
1683 {
1684   return NULL;
1685 }
1686
1687 static GstCaps *
1688 video_media_type_to_caps (AM_MEDIA_TYPE *mediatype)
1689 {
1690   GstCaps *caps = NULL;
1691
1692   /* TODO: Add  RGB types. */
1693   if (IsEqualGUID (mediatype->subtype, MEDIASUBTYPE_YUY2))
1694     caps = gst_caps_new_simple ("video/x-raw",
1695             "format", GST_TYPE_VIDEO_FORMAT, GST_VIDEO_FORMAT_YUY2, NULL);
1696   else if (IsEqualGUID (mediatype->subtype, MEDIASUBTYPE_UYVY))
1697     caps = gst_caps_new_simple ("video/x-raw",
1698             "format", GST_TYPE_VIDEO_FORMAT, GST_VIDEO_FORMAT_UYVY, NULL);
1699   else if (IsEqualGUID (mediatype->subtype, MEDIASUBTYPE_YV12))
1700     caps = gst_caps_new_simple ("video/x-raw",
1701             "format", GST_TYPE_VIDEO_FORMAT, GST_VIDEO_FORMAT_YV12, NULL);
1702
1703   if (!caps) {
1704     GST_DEBUG ("No subtype known; cannot continue");
1705     return NULL;
1706   }
1707
1708   if (IsEqualGUID (mediatype->formattype, FORMAT_VideoInfo) &&
1709           mediatype->cbFormat >= sizeof(VIDEOINFOHEADER))
1710   {
1711     VIDEOINFOHEADER *vh = (VIDEOINFOHEADER *)mediatype->pbFormat;
1712
1713         /* TODO: Set PAR here. Based on difference between source and target RECTs? 
1714      *       Do we want framerate? Based on AvgTimePerFrame? */
1715     gst_caps_set_simple (caps, 
1716             "width", G_TYPE_INT, vh->bmiHeader.biWidth,
1717             "height", G_TYPE_INT, vh->bmiHeader.biHeight,
1718                         NULL);
1719   }
1720
1721   return caps;
1722 }
1723
1724
1725 /* Create a GstCaps object representing the same media type as
1726  * this AM_MEDIA_TYPE.
1727  *
1728  * Returns NULL if no corresponding GStreamer type is known.
1729  *
1730  * May modify mediatype.
1731  */
1732 static GstCaps *
1733 gst_directshow_media_type_to_caps (AM_MEDIA_TYPE *mediatype)
1734 {
1735   GstCaps *caps = NULL;
1736
1737   if (IsEqualGUID (mediatype->majortype, MEDIATYPE_Video))
1738     caps = video_media_type_to_caps (mediatype);
1739   else if (IsEqualGUID (mediatype->majortype, MEDIATYPE_Audio))
1740     caps = audio_media_type_to_caps (mediatype);
1741   else {
1742     GST_DEBUG ("Non audio/video media types not yet " \
1743         "recognised, please add me: " GUID_FORMAT,
1744         GUID_ARGS(mediatype->majortype));
1745   }
1746
1747   if (caps) {
1748     gchar *capsstring = gst_caps_to_string (caps);
1749     GST_DEBUG ("Converted AM_MEDIA_TYPE to \"%s\"", capsstring);
1750     g_free (capsstring);
1751   }
1752   else {
1753     GST_WARNING ("Failed to convert AM_MEDIA_TYPE to caps");
1754   }
1755
1756   return caps;
1757 }
1758
1759 /* Fill in a DirectShow AM_MEDIA_TYPE structure representing the same media
1760  * type as this GstCaps object.
1761  *
1762  * Returns FALSE if no corresponding type is known.
1763  *
1764  * Only operates on simple (single structure) caps.
1765  */
1766 static gboolean
1767 gst_caps_to_directshow_media_type (GstDshowVideoSink * sink, GstCaps *caps,
1768     AM_MEDIA_TYPE *mediatype)
1769 {
1770   GstVideoInfo info;
1771   int width, height;
1772   int bpp;
1773
1774   gst_video_info_init (&info);
1775   if (!gst_video_info_from_caps (&info, caps))
1776   {
1777     GST_WARNING_OBJECT (sink, "Couldn't parse caps");
1778       return FALSE;
1779   }
1780   memset (mediatype, 0, sizeof (AM_MEDIA_TYPE));
1781
1782   if (GST_VIDEO_FORMAT_INFO_IS_YUV (info.finfo))
1783   {
1784     guint32 fourcc;
1785     GST_VIDEO_SINK_WIDTH (sink) = info.width;
1786     GST_VIDEO_SINK_HEIGHT (sink) = info.height;
1787     width = info.width;
1788     height = info.height;
1789     mediatype->majortype = MEDIATYPE_Video;
1790
1791     switch (GST_VIDEO_INFO_FORMAT (&info))
1792     {
1793         case GST_VIDEO_FORMAT_YUY2:
1794           mediatype->subtype = MEDIASUBTYPE_YUY2;
1795           fourcc = GST_MAKE_FOURCC ('Y', 'U', 'Y', '2');
1796           bpp = 16;
1797           break;
1798         case GST_VIDEO_FORMAT_UYVY:
1799           mediatype->subtype = MEDIASUBTYPE_UYVY;
1800           fourcc = GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y');
1801           bpp = 16;
1802           break;
1803         case GST_VIDEO_FORMAT_YV12:
1804           mediatype->subtype = MEDIASUBTYPE_YV12;
1805           fourcc = GST_MAKE_FOURCC ('Y', 'V', '1', '2');
1806           bpp = 12;
1807           break;
1808         default:
1809           GST_WARNING_OBJECT (sink, "Couldn't parse caps");
1810           return FALSE;
1811     }
1812
1813     mediatype->bFixedSizeSamples = TRUE; /* Always true for raw video */
1814     mediatype->bTemporalCompression = FALSE; /* Likewise, always false */
1815
1816     {
1817       int par_n, par_d;
1818       VIDEOINFOHEADER *vi = (VIDEOINFOHEADER *)CoTaskMemAlloc (sizeof (VIDEOINFOHEADER));
1819       memset (vi, 0, sizeof (VIDEOINFOHEADER));
1820
1821       mediatype->formattype = FORMAT_VideoInfo;
1822       mediatype->cbFormat = sizeof (VIDEOINFOHEADER);
1823       mediatype->pbFormat = (BYTE *)vi;
1824
1825       mediatype->lSampleSize = width * height * bpp / 8;
1826
1827       GST_INFO_OBJECT (sink, "Set mediatype format: size %d, sample size %d",
1828           mediatype->cbFormat, mediatype->lSampleSize);
1829
1830       vi->rcSource.top = 0;
1831       vi->rcSource.left = 0;
1832       vi->rcSource.bottom = height;
1833       vi->rcSource.right = width;
1834
1835       vi->rcTarget.top = 0;
1836       vi->rcTarget.left = 0;
1837       if (sink->keep_aspect_ratio) {
1838         par_n = GST_VIDEO_INFO_PAR_N (&info);
1839         par_d = GST_VIDEO_INFO_PAR_D (&info);
1840         /* To handle non-square pixels, we set the target rectangle to a 
1841          * different size than the source rectangle.
1842          * There might be a better way, but this seems to work. */
1843         vi->rcTarget.bottom = height;
1844         vi->rcTarget.right = width * par_n / par_d;
1845         GST_DEBUG_OBJECT (sink, "Got PAR: set target right to %d from width %d",
1846             vi->rcTarget.right, width);
1847       }
1848       else {
1849         vi->rcTarget.bottom = height;
1850         vi->rcTarget.right = width;
1851       }
1852
1853       vi->bmiHeader.biSize = sizeof (BITMAPINFOHEADER);
1854       vi->bmiHeader.biWidth = width;
1855       vi->bmiHeader.biHeight = -height; /* Required to be negative. */
1856       vi->bmiHeader.biPlanes = 1; /* Required to be 1 */
1857       vi->bmiHeader.biBitCount = bpp;
1858       vi->bmiHeader.biCompression = fourcc;
1859       vi->bmiHeader.biSizeImage = width * height * bpp / 8;
1860
1861       /* We can safely zero these; they don't matter for our uses */
1862       vi->bmiHeader.biXPelsPerMeter = 0;
1863       vi->bmiHeader.biYPelsPerMeter = 0;
1864       vi->bmiHeader.biClrUsed = 0;
1865       vi->bmiHeader.biClrImportant = 0;
1866     }
1867
1868     GST_DEBUG_OBJECT (sink, "Successfully built AM_MEDIA_TYPE from caps");
1869     return TRUE;
1870   }
1871
1872   GST_WARNING_OBJECT (sink, "Failed to convert caps, not a known caps type");
1873   /* Only YUV supported so far */
1874
1875   return FALSE;
1876 }
1877
1878 /* Plugin entry point */
1879 extern "C" static gboolean
1880 plugin_init (GstPlugin * plugin)
1881 {
1882   /* PRIMARY: this is the best videosink to use on windows */
1883   if (!gst_element_register (plugin, "dshowvideosink",
1884           GST_RANK_SECONDARY, GST_TYPE_DSHOWVIDEOSINK))
1885     return FALSE;
1886
1887   return TRUE;
1888 }
1889
1890 extern "C" GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1891     GST_VERSION_MINOR,
1892     dshowsinkwrapper,
1893     "DirectShow sink wrapper plugin",
1894     plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)