osxvideosink.m 29.7 KB
Newer Older
1
2
3
/* GStreamer
 * OSX video sink
 * Copyright (C) 2004-6 Zaheer Abbas Merali <zaheerabbas at merali dot org>
4
 * Copyright (C) 2007,2008,2009 Pioneers of the Inevitable <songbird@songbirdnest.com>
5
 *
6
7
8
9
10
11
12
13
14
15
16
17
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
Tim-Philipp Müller's avatar
Tim-Philipp Müller committed
18
19
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
20
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
21
22
 * The development of this code was made possible due to the involvement of
 * Pioneers of the Inevitable, the creators of the Songbird Music player.
23
 *
24
25
 */

26
27
28
29
/**
 * SECTION:element-osxvideosink
 *
 * The OSXVideoSink renders video frames to a MacOSX window. The video output
30
 * must be directed to a window embedded in an existing NSApp.
31
 *
32
33
34
 * When the NSView to be embedded is created an element #GstMessage with a
 * name of 'have-ns-view' will be created and posted on the bus.
 * The pointer to the NSView to embed will be in the 'nsview' field of that
35
36
 * message. The application MUST handle this message and embed the view
 * appropriately.
37
38
 */

39
#include "config.h"
40
41
#include <gst/video/videooverlay.h>
#include <gst/video/navigation.h>
42
#include <gst/video/video.h>
43
44

#include "osxvideosink.h"
45
#include <unistd.h>
46
47
48
49
50
#import "cocoawindow.h"

GST_DEBUG_CATEGORY (gst_debug_osx_video_sink);
#define GST_CAT_DEFAULT gst_debug_osx_video_sink

51
#include <pthread.h>
52
extern void _CFRunLoopSetCurrent (CFRunLoopRef rl);
53
54
extern pthread_t _CFMainPThread;

55
56


57
58
59
60
static GstStaticPadTemplate gst_osx_video_sink_sink_template_factory =
GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
61
    GST_STATIC_CAPS ("video/x-raw, "
62
63
        "framerate = (fraction) [ 0, MAX ], "
        "width = (int) [ 1, MAX ], "
64
        "height = (int) [ 1, MAX ], "
65
#if G_BYTE_ORDER == G_BIG_ENDIAN
66
       "format = (string) YUY2")
67
#else
68
        "format = (string) UYVY")
69
#endif
70
71
72
73
74
    );

enum
{
  ARG_0,
75
  ARG_EMBED,
76
  ARG_FORCE_PAR,
77
78
};

79
static void gst_osx_video_sink_osxwindow_destroy (GstOSXVideoSink * osxvideosink);
80
81
82
83
static GMutex _run_loop_check_mutex;
static GMutex _run_loop_mutex;
static GCond _run_loop_cond;
static GstOSXVideoSinkClass *sink_class = NULL;
84
85
static GstVideoSinkClass *parent_class = NULL;

86
87
/* Helper to trigger calls from the main thread */
static void
88
89
gst_osx_video_sink_call_from_main_thread(GstOSXVideoSink *osxvideosink,
    NSObject * object, SEL function, NSObject *data, BOOL waitUntilDone)
90
{
91

92
  NSThread *thread;
93
94
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

95
96
97
98
99
100
101
  if (sink_class->ns_app_thread == NULL){
    thread = [NSThread mainThread];
  } else {
    thread = sink_class->ns_app_thread;
  }

  [object performSelector:function onThread:thread
102
103
104
105
          withObject:data waitUntilDone:waitUntilDone];
  [pool release];
}

106
107
/* Poll for cocoa events */
static void
108
run_ns_app_loop (void) {
109
110
  NSEvent *event;
  NSAutoreleasePool *pool =[[NSAutoreleasePool alloc] init];
111
112
113
114
  NSDate *pollTime = nil;

  /* when running the loop in a thread we want to sleep as long as possible */
  pollTime = [NSDate distantFuture];
115
116

  do {
117
118
      event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:pollTime
          inMode:NSDefaultRunLoopMode dequeue:YES];
119
120
121
122
123
124
      [NSApp sendEvent:event];
    }
  while (event != nil);
  [pool release];
}

125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
static void
gst_osx_videosink_check_main_run_loop (GstOSXVideoSink *sink)
{
  /* check if the main run loop is running */
  gboolean is_running;

  /* the easy way */
  is_running = [[NSRunLoop mainRunLoop] currentMode] != nil;
  if (is_running) {
    goto exit;
  } else {
    /* the previous check doesn't always work with main loops that run
     * cocoa's main run loop manually, like the gdk one, giving false
     * negatives. This check defers a call to the main thread and waits to
     * be awaken by this function. */
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    GstOSXVideoSinkObject * object = (GstOSXVideoSinkObject *) sink->osxvideosinkobject;
142
    gint64 abstime;
143

144
    g_mutex_lock (&_run_loop_mutex);
145
146
147
148
    [object performSelectorOnMainThread:
          @selector(checkMainRunLoop)
          withObject:nil waitUntilDone:NO];
    /* Wait 100 ms */
149
    abstime = g_get_monotonic_time () + 100 * 1000;
150
151
152
    is_running = g_cond_wait_until (&_run_loop_cond,
        &_run_loop_mutex, abstime);
    g_mutex_unlock (&_run_loop_mutex);
153
154
155
156
157
158
159
160

    [pool release];
  }

exit:
  {
  GST_DEBUG_OBJECT(sink, "The main runloop %s is running",
      is_running ? "" : " not ");
161
162
163
164
165
166
  if (is_running) {
    sink_class->run_loop_state = GST_OSX_VIDEO_SINK_RUN_LOOP_STATE_RUNNING;
    sink_class->ns_app_thread = [NSThread mainThread];
  } else {
    sink_class->run_loop_state = GST_OSX_VIDEO_SINK_RUN_LOOP_STATE_NOT_RUNNING;
  }
167
168
169
  }
}

170
static void
171
gst_osx_video_sink_run_cocoa_loop (GstOSXVideoSink * sink )
172
{
173
  /* Cocoa applications require a main runloop running to dispatch UI
174
175
176
   * events and process deferred calls to the main thread through
   * perfermSelectorOnMainThread.
   * Since the sink needs to create it's own Cocoa window when no
177
   * external NSView is passed to the sink through the GstVideoOverlay API,
178
   * we need to run the cocoa mainloop somehow.
179
   * This run loop can only be started once, by the first sink needing it
180
   */
181
182
183
184
185
186
187
188
189
190
191
192
193

  g_mutex_lock (&_run_loop_check_mutex);

  if (sink_class->run_loop_state == GST_OSX_VIDEO_SINK_RUN_LOOP_STATE_UNKNOWN) {
    gst_osx_videosink_check_main_run_loop (sink);
  }

  if (sink_class->run_loop_state == GST_OSX_VIDEO_SINK_RUN_LOOP_STATE_RUNNING) {
    g_mutex_unlock (&_run_loop_check_mutex);
    return;
  }

  if (sink_class->ns_app_thread == NULL) {
194
    /* run the main runloop in a separate thread */
195

196
    /* override [NSThread isMainThread] with our own implementation so that we can
197
     * make it believe our dedicated thread is the main thread
198
199
200
201
202
     */
    Method origIsMainThread = class_getClassMethod([NSThread class],
        NSSelectorFromString(@"isMainThread"));
    Method ourIsMainThread = class_getClassMethod([GstOSXVideoSinkObject class],
        NSSelectorFromString(@"isMainThread"));
203

204
    method_exchangeImplementations(origIsMainThread, ourIsMainThread);
205

206
    sink_class->ns_app_thread = [[NSThread alloc]
207
        initWithTarget:sink->osxvideosinkobject
208
        selector:@selector(nsAppThread) object:nil];
209
    [sink_class->ns_app_thread start];
210

211
212
213
    g_mutex_lock (&_run_loop_mutex);
    g_cond_wait (&_run_loop_cond, &_run_loop_mutex);
    g_mutex_unlock (&_run_loop_mutex);
214
  }
215
216

  g_mutex_unlock (&_run_loop_check_mutex);
217
218
219
}

static void
220
gst_osx_video_sink_stop_cocoa_loop (GstOSXVideoSink * osxvideosink)
221
222
223
{
}

224
/* This function handles osx window creation */
225
226
static gboolean
gst_osx_video_sink_osxwindow_create (GstOSXVideoSink * osxvideosink, gint width,
227
228
229
230
    gint height)
{
  NSRect rect;
  GstOSXWindow *osxwindow = NULL;
231
232
  GstStructure *s;
  GstMessage *msg;
233
  gboolean res = TRUE;
234
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
235

236
  g_return_val_if_fail (GST_IS_OSX_VIDEO_SINK (osxvideosink), FALSE);
237

238
239
  GST_DEBUG_OBJECT (osxvideosink, "Creating new OSX window");

240
  osxvideosink->osxwindow = osxwindow = g_new0 (GstOSXWindow, 1);
241
242
243

  osxwindow->width = width;
  osxwindow->height = height;
244
  osxwindow->closed = FALSE;
245
  osxwindow->internal = FALSE;
246
247
248
249
250
251
252
253
254
255

  /* Allocate our GstGLView for the window, and then tell the application
   * about it (hopefully it's listening...) */
  rect.origin.x = 0.0;
  rect.origin.y = 0.0;
  rect.size.width = (float) osxwindow->width;
  rect.size.height = (float) osxwindow->height;
  osxwindow->gstview =[[GstGLView alloc] initWithFrame:rect];

  s = gst_structure_new ("have-ns-view",
256
257
     "nsview", G_TYPE_POINTER, osxwindow->gstview,
     nil);
258
259
260
261

  msg = gst_message_new_element (GST_OBJECT (osxvideosink), s);
  gst_element_post_message (GST_ELEMENT (osxvideosink), msg);

262
263
  GST_INFO_OBJECT (osxvideosink, "'have-ns-view' message sent");

264
  gst_osx_video_sink_run_cocoa_loop (osxvideosink);
265
  [osxwindow->gstview setMainThread:sink_class->ns_app_thread];
266

267
268
269
270
271
272
273
  /* check if have-ns-view was handled and osxwindow->gstview was added to a
   * superview
   */
  if ([osxwindow->gstview haveSuperview] == NO) {
    /* have-ns-view wasn't handled, post prepare-xwindow-id */
    if (osxvideosink->superview == NULL) {
      GST_INFO_OBJECT (osxvideosink, "emitting prepare-xwindow-id");
274
      gst_video_overlay_prepare_window_handle (GST_VIDEO_OVERLAY (osxvideosink));
275
276
277
278
279
280
281
282
    }

    if (osxvideosink->superview != NULL) {
      /* prepare-xwindow-id was handled, we have the superview in
       * osxvideosink->superview. We now add osxwindow->gstview to the superview
       * from the main thread
       */
      GST_INFO_OBJECT (osxvideosink, "we have a superview, adding our view to it");
283
      gst_osx_video_sink_call_from_main_thread(osxvideosink, osxwindow->gstview,
284
285
          @selector(addToSuperview:), osxvideosink->superview, NO);

286
    } else {
287
288
289
290
291
292
293
      if (osxvideosink->embed) {
        /* the view wasn't added to a superview. It's possible that the
         * application handled have-ns-view, stored our view internally and is
         * going to add it to a superview later (webkit does that now).
         */
        GST_INFO_OBJECT (osxvideosink, "no superview");
      } else {
294
295
        gst_osx_video_sink_call_from_main_thread(osxvideosink,
          osxvideosink->osxvideosinkobject,
296
          @selector(createInternalWindow), nil, YES);
297
298
        GST_INFO_OBJECT (osxvideosink, "No superview, creating an internal window.");
      }
299
300
    }
  }
301
  [osxwindow->gstview setNavigation: GST_NAVIGATION(osxvideosink)];
302
  [osxvideosink->osxwindow->gstview setKeepAspectRatio: osxvideosink->keep_par];
303
304
305

  [pool release];

306
  return res;
307
308
309
}

static void
310
gst_osx_video_sink_osxwindow_destroy (GstOSXVideoSink * osxvideosink)
311
{
312
313
  NSAutoreleasePool *pool;

314
  g_return_if_fail (GST_IS_OSX_VIDEO_SINK (osxvideosink));
315
  pool = [[NSAutoreleasePool alloc] init];
316

317
  GST_OBJECT_LOCK (osxvideosink);
318
319
320
  gst_osx_video_sink_call_from_main_thread(osxvideosink,
      osxvideosink->osxvideosinkobject,
      @selector(destroy), (id) nil, YES);
321
  GST_OBJECT_UNLOCK (osxvideosink);
322
  gst_osx_video_sink_stop_cocoa_loop (osxvideosink);
323
  [pool release];
324
325
326
327
328
329
330
}

/* This function resizes a GstXWindow */
static void
gst_osx_video_sink_osxwindow_resize (GstOSXVideoSink * osxvideosink,
    GstOSXWindow * osxwindow, guint width, guint height)
{
331
332
  GstOSXVideoSinkObject *object = osxvideosink->osxvideosinkobject;

333
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
334
335
336
337
338
339
  g_return_if_fail (osxwindow != NULL);
  g_return_if_fail (GST_IS_OSX_VIDEO_SINK (osxvideosink));

  osxwindow->width = width;
  osxwindow->height = height;

340
  GST_DEBUG_OBJECT (osxvideosink, "Resizing window to (%d,%d)", width, height);
341

342
  /* Directly resize the underlying view */
343
  GST_DEBUG_OBJECT (osxvideosink, "Calling setVideoSize on %p", osxwindow->gstview);
344
  gst_osx_video_sink_call_from_main_thread (osxvideosink, object,
345
      @selector(resize), (id)nil, YES);
346

347
  [pool release];
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
}

static gboolean
gst_osx_video_sink_setcaps (GstBaseSink * bsink, GstCaps * caps)
{
  GstOSXVideoSink *osxvideosink;
  GstStructure *structure;
  gboolean res, result = FALSE;
  gint video_width, video_height;

  osxvideosink = GST_OSX_VIDEO_SINK (bsink);

  GST_DEBUG_OBJECT (osxvideosink, "caps: %" GST_PTR_FORMAT, caps);

  structure = gst_caps_get_structure (caps, 0);
  res = gst_structure_get_int (structure, "width", &video_width);
  res &= gst_structure_get_int (structure, "height", &video_height);

  if (!res) {
    goto beach;
  }

370
371
  GST_DEBUG_OBJECT (osxvideosink, "our format is: %dx%d video",
      video_width, video_height);
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389

  GST_VIDEO_SINK_WIDTH (osxvideosink) = video_width;
  GST_VIDEO_SINK_HEIGHT (osxvideosink) = video_height;

  gst_osx_video_sink_osxwindow_resize (osxvideosink, osxvideosink->osxwindow,
      video_width, video_height);
  result = TRUE;

beach:
  return result;

}

static GstStateChangeReturn
gst_osx_video_sink_change_state (GstElement * element,
    GstStateChange transition)
{
  GstOSXVideoSink *osxvideosink;
390
  GstStateChangeReturn ret;
391
392
393

  osxvideosink = GST_OSX_VIDEO_SINK (element);

394
  GST_DEBUG_OBJECT (osxvideosink, "%s => %s",
395
396
        gst_element_state_get_name(GST_STATE_TRANSITION_CURRENT (transition)),
        gst_element_state_get_name(GST_STATE_TRANSITION_NEXT (transition)));
397

398
399
  switch (transition) {
    case GST_STATE_CHANGE_NULL_TO_READY:
400
401
      break;
    case GST_STATE_CHANGE_READY_TO_PAUSED:
402
      /* Creating our window and our image */
403
404
      GST_VIDEO_SINK_WIDTH (osxvideosink) = 320;
      GST_VIDEO_SINK_HEIGHT (osxvideosink) = 240;
405
      if (!gst_osx_video_sink_osxwindow_create (osxvideosink,
406
          GST_VIDEO_SINK_WIDTH (osxvideosink),
407
408
409
410
          GST_VIDEO_SINK_HEIGHT (osxvideosink))) {
        ret = GST_STATE_CHANGE_FAILURE;
        goto done;
      }
411
      break;
412
    default:
413
      break;
414
415
416
417
418
  }

  ret = (GST_ELEMENT_CLASS (parent_class))->change_state (element, transition);

  switch (transition) {
419
420
421
    case GST_STATE_CHANGE_PAUSED_TO_READY:
      GST_VIDEO_SINK_WIDTH (osxvideosink) = 0;
      GST_VIDEO_SINK_HEIGHT (osxvideosink) = 0;
422
      gst_osx_video_sink_osxwindow_destroy (osxvideosink);
423
424
425
      break;
    case GST_STATE_CHANGE_READY_TO_NULL:
      break;
426
427
    default:
      break;
428
429
  }

430
done:
431
  return ret;
432
433
434
435
436
437
}

static GstFlowReturn
gst_osx_video_sink_show_frame (GstBaseSink * bsink, GstBuffer * buf)
{
  GstOSXVideoSink *osxvideosink;
438
  GstBufferObject* bufferobject;
439
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
440
441
442
443

  osxvideosink = GST_OSX_VIDEO_SINK (bsink);

  GST_DEBUG ("show_frame");
444
  bufferobject = [[GstBufferObject alloc] initWithBuffer:buf];
445
446
  gst_osx_video_sink_call_from_main_thread(osxvideosink,
      osxvideosink->osxvideosinkobject,
447
      @selector(showFrame:), bufferobject, NO);
448
  [pool release];
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
  return GST_FLOW_OK;
}

/* Buffer management */



/* =========================================== */
/*                                             */
/*              Init & Class init              */
/*                                             */
/* =========================================== */

static void
gst_osx_video_sink_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
{
  GstOSXVideoSink *osxvideosink;

  g_return_if_fail (GST_IS_OSX_VIDEO_SINK (object));

  osxvideosink = GST_OSX_VIDEO_SINK (object);

  switch (prop_id) {
    case ARG_EMBED:
474
      osxvideosink->embed = g_value_get_boolean(value);
475
476
477
      g_warning ("The \"embed\" property of osxvideosink is deprecated and "
          "will be removed in the near future. Use the GstVideoOverlay "
          "instead.");
478
      break;
479
480
481
482
483
484
    case ARG_FORCE_PAR:
      osxvideosink->keep_par = g_value_get_boolean(value);
      if (osxvideosink->osxwindow)
        [osxvideosink->osxwindow->gstview
            setKeepAspectRatio: osxvideosink->keep_par];
      break;
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_osx_video_sink_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec)
{
  GstOSXVideoSink *osxvideosink;

  g_return_if_fail (GST_IS_OSX_VIDEO_SINK (object));

  osxvideosink = GST_OSX_VIDEO_SINK (object);

  switch (prop_id) {
    case ARG_EMBED:
503
      g_value_set_boolean (value, osxvideosink->embed);
504
      break;
505
506
507
    case ARG_FORCE_PAR:
      g_value_set_boolean (value, osxvideosink->keep_par);
      break;
508
509
510
511
512
513
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

514
515
516
517
518
519
520
521
static gboolean
gst_osx_video_sink_propose_allocation (GstBaseSink * base_sink, GstQuery * query)
{
    gst_query_add_allocation_meta (query,
        GST_VIDEO_META_API_TYPE, NULL);

    return TRUE;
}
522

523
static void
524
gst_osx_video_sink_init (GstOSXVideoSink * sink)
525
{
526
527
528
529
  sink->osxwindow = NULL;
  sink->superview = NULL;
  sink->osxvideosinkobject = [[GstOSXVideoSinkObject alloc] initWithSink:sink];
  sink->keep_par = FALSE;
530
531
532
533
534
535
536
}

static void
gst_osx_video_sink_base_init (gpointer g_class)
{
  GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);

537
  gst_element_class_set_static_metadata (element_class, "OSX Video sink",
538
539
      "Sink/Video", "OSX native videosink",
      "Zaheer Abbas Merali <zaheerabbas at merali dot org>");
540
541
542
543
544

  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&gst_osx_video_sink_sink_template_factory));
}

545
546
547
548
549
550
551
552
static void
gst_osx_video_sink_finalize (GObject *object)
{
  GstOSXVideoSink *osxvideosink = GST_OSX_VIDEO_SINK (object);

  if (osxvideosink->superview)
    [osxvideosink->superview release];

553
554
555
  if (osxvideosink->osxvideosinkobject)
    [(GstOSXVideoSinkObject*)(osxvideosink->osxvideosinkobject) release];

556
557
558
  G_OBJECT_CLASS (parent_class)->finalize (object);
}

559
560
561
562
563
564
565
566
567
568
569
570
static void
gst_osx_video_sink_class_init (GstOSXVideoSinkClass * klass)
{
  GObjectClass *gobject_class;
  GstElementClass *gstelement_class;
  GstBaseSinkClass *gstbasesink_class;

  gobject_class = (GObjectClass *) klass;
  gstelement_class = (GstElementClass *) klass;
  gstbasesink_class = (GstBaseSinkClass *) klass;

  parent_class = g_type_class_ref (GST_TYPE_VIDEO_SINK);
571
572
573
574
  sink_class = klass;

  klass->run_loop_state = GST_OSX_VIDEO_SINK_RUN_LOOP_STATE_UNKNOWN;
  klass->ns_app_thread = NULL;
575
576
577

  gobject_class->set_property = gst_osx_video_sink_set_property;
  gobject_class->get_property = gst_osx_video_sink_get_property;
578
  gobject_class->finalize = gst_osx_video_sink_finalize;
579
580
581
582

  gstbasesink_class->set_caps = gst_osx_video_sink_setcaps;
  gstbasesink_class->preroll = gst_osx_video_sink_show_frame;
  gstbasesink_class->render = gst_osx_video_sink_show_frame;
583
  gstbasesink_class->propose_allocation = gst_osx_video_sink_propose_allocation;
584
585
  gstelement_class->change_state = gst_osx_video_sink_change_state;

586
587
588
589
590
591
592
  /**
   * GstOSXVideoSink:embed
   *
   * Set to #TRUE if you are embedding the video window in an application.
   *
   **/

593
  g_object_class_install_property (gobject_class, ARG_EMBED,
594
      g_param_spec_boolean ("embed", "embed", "For ABI compatiblity only, do not use",
595
          FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
596
597
598
599
600
601
602
603
604
605
606

  /**
   * GstOSXVideoSink:force-aspect-ratio
   *
   * When enabled, scaling will respect original aspect ratio.
   *
   **/

  g_object_class_install_property (gobject_class, ARG_FORCE_PAR,
      g_param_spec_boolean ("force-aspect-ratio", "force aspect ration",
          "When enabled, scaling will respect original aspect ration",
607
          TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
608
609
}

610
611
612
613
614
615
616
617
static void
gst_osx_video_sink_navigation_send_event (GstNavigation * navigation,
    GstStructure * structure)
{
  GstOSXVideoSink *osxvideosink = GST_OSX_VIDEO_SINK (navigation);
  GstPad *peer;
  GstEvent *event;
  GstVideoRectangle src, dst, result;
618
  NSRect bounds;
619
620
621
622
623
624
625
626
627
  gdouble x, y, xscale = 1.0, yscale = 1.0;

  peer = gst_pad_get_peer (GST_VIDEO_SINK_PAD (osxvideosink));

  if (!peer || !osxvideosink->osxwindow)
    return;

  event = gst_event_new_navigation (structure);

628
629
630
  bounds = [osxvideosink->osxwindow->gstview getDrawingBounds];

  if (osxvideosink->keep_par) {
631
632
633
634
    /* We get the frame position using the calculated geometry from _setcaps
       that respect pixel aspect ratios */
    src.w = GST_VIDEO_SINK_WIDTH (osxvideosink);
    src.h = GST_VIDEO_SINK_HEIGHT (osxvideosink);
635
636
    dst.w = bounds.size.width;
    dst.h = bounds.size.height;
637
638

    gst_video_sink_center_rect (src, dst, &result, TRUE);
639
640
    result.x += bounds.origin.x;
    result.y += bounds.origin.y;
641
  } else {
642
643
644
645
    result.x = bounds.origin.x;
    result.y = bounds.origin.y;
    result.w = bounds.size.width;
    result.h = bounds.size.height;
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
  }

  /* We calculate scaling using the original video frames geometry to include
     pixel aspect ratio scaling. */
  xscale = (gdouble) osxvideosink->osxwindow->width / result.w;
  yscale = (gdouble) osxvideosink->osxwindow->height / result.h;

  /* Converting pointer coordinates to the non scaled geometry */
  if (gst_structure_get_double (structure, "pointer_x", &x)) {
    x = MIN (x, result.x + result.w);
    x = MAX (x - result.x, 0);
    gst_structure_set (structure, "pointer_x", G_TYPE_DOUBLE,
        (gdouble) x * xscale, NULL);
  }
  if (gst_structure_get_double (structure, "pointer_y", &y)) {
    y = MIN (y, result.y + result.h);
    y = MAX (y - result.y, 0);
    gst_structure_set (structure, "pointer_y", G_TYPE_DOUBLE,
        (gdouble) y * yscale, NULL);
  }

  gst_pad_send_event (peer, event);
  gst_object_unref (peer);
}

static void
gst_osx_video_sink_navigation_init (GstNavigationInterface * iface)
{
  iface->send_event = gst_osx_video_sink_navigation_send_event;
}

677
static void
678
gst_osx_video_sink_set_window_handle (GstVideoOverlay * overlay, guintptr handle_id)
679
680
{
  GstOSXVideoSink *osxvideosink = GST_OSX_VIDEO_SINK (overlay);
681
  NSView *view = (NSView *) handle_id;
682

683
684
685
  gst_osx_video_sink_call_from_main_thread(osxvideosink,
      osxvideosink->osxvideosinkobject,
      @selector(setView:), view, YES);
686
687
688
}

static void
689
gst_osx_video_sink_xoverlay_init (GstVideoOverlayInterface * iface)
690
{
691
  iface->set_window_handle = gst_osx_video_sink_set_window_handle;
692
693
694
695
  iface->expose = NULL;
  iface->handle_events = NULL;
}

696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
/* ============================================================= */
/*                                                               */
/*                       Public Methods                          */
/*                                                               */
/* ============================================================= */

/* =========================================== */
/*                                             */
/*          Object typing & Creation           */
/*                                             */
/* =========================================== */

GType
gst_osx_video_sink_get_type (void)
{
  static GType osxvideosink_type = 0;

  if (!osxvideosink_type) {
    static const GTypeInfo osxvideosink_info = {
      sizeof (GstOSXVideoSinkClass),
      gst_osx_video_sink_base_init,
      NULL,
      (GClassInitFunc) gst_osx_video_sink_class_init,
      NULL,
      NULL,
      sizeof (GstOSXVideoSink),
      0,
      (GInstanceInitFunc) gst_osx_video_sink_init,
    };

726
727
728
729
730
731
    static const GInterfaceInfo overlay_info = {
      (GInterfaceInitFunc) gst_osx_video_sink_xoverlay_init,
      NULL,
      NULL,
    };

732
733
734
735
736
    static const GInterfaceInfo navigation_info = {
      (GInterfaceInitFunc) gst_osx_video_sink_navigation_init,
      NULL,
      NULL,
    };
737
738
739
    osxvideosink_type = g_type_register_static (GST_TYPE_VIDEO_SINK,
        "GstOSXVideoSink", &osxvideosink_info, 0);

740
    g_type_add_interface_static (osxvideosink_type, GST_TYPE_VIDEO_OVERLAY,
741
        &overlay_info);
742
743
    g_type_add_interface_static (osxvideosink_type, GST_TYPE_NAVIGATION,
        &navigation_info);
744
745
746
747
748
  }

  return osxvideosink_type;
}

749
750
751
752
753
754
755
756
757
758
759
@implementation GstWindowDelegate
- (id) initWithSink: (GstOSXVideoSink *) sink
{
  self = [super init];
  self->osxvideosink = sink;
  return self;
}

- (void)windowWillClose:(NSNotification *)notification {
  /* Only handle close events if the window was closed manually by the user
   * and not becuase of a state change state to READY */
760
761
762
  if (osxvideosink->osxwindow == NULL) {
    return;
  }
763
764
765
766
767
768
769
770
771
  if (!osxvideosink->osxwindow->closed) {
    osxvideosink->osxwindow->closed = TRUE;
    GST_ELEMENT_ERROR (osxvideosink, RESOURCE, NOT_FOUND, ("Output window was closed"), (NULL));
    gst_osx_video_sink_osxwindow_destroy(osxvideosink);
  }
}

@end

772
773
774
775
776
@ implementation GstOSXVideoSinkObject

-(id) initWithSink: (GstOSXVideoSink*) sink
{
  self = [super init];
777
  self->osxvideosink = gst_object_ref (sink);
778
779
780
  return self;
}

781
782
783
784
785
-(void) dealloc {
  gst_object_unref (osxvideosink);
  [super dealloc];
}

786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
-(void) createInternalWindow
{
  GstOSXWindow *osxwindow = osxvideosink->osxwindow;
  NSRect rect;
  unsigned int mask;

  osxwindow->internal = TRUE;

  mask =  NSTitledWindowMask             |
          NSClosableWindowMask           |
          NSResizableWindowMask          |
          NSTexturedBackgroundWindowMask |
          NSMiniaturizableWindowMask;

  rect.origin.x = 100.0;
  rect.origin.y = 100.0;
  rect.size.width = (float) osxwindow->width;
  rect.size.height = (float) osxwindow->height;

805
  osxwindow->win =[[[GstOSXVideoSinkWindow alloc]
806
807
808
809
                       initWithContentNSRect: rect
                       styleMask: mask
                       backing: NSBackingStoreBuffered
                       defer: NO
810
                       screen: nil] retain];
811
  GST_DEBUG("VideoSinkWindow created, %p", osxwindow->win);
812
  [osxwindow->win orderFrontRegardless];
813
814
815
816
817
818
  osxwindow->gstview =[osxwindow->win gstView];
  [osxwindow->win setDelegate:[[GstWindowDelegate alloc]
      initWithSink:osxvideosink]];

}

819
820
821
822
823
824
+ (BOOL) isMainThread
{
  /* FIXME: ideally we should return YES only for ->ns_app_thread here */
  return YES;
}

825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
- (void) setView: (NSView*)view
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

  if (osxvideosink->superview) {
    GST_INFO_OBJECT (osxvideosink, "old xwindow id %p", osxvideosink->superview);
    if (osxvideosink->osxwindow) {
      [osxvideosink->osxwindow->gstview removeFromSuperview];
    }
    [osxvideosink->superview release];
  }
  if (osxvideosink->osxwindow != NULL && view != NULL) {
    if (osxvideosink->osxwindow->internal) {
      GST_INFO_OBJECT (osxvideosink, "closing internal window");
      osxvideosink->osxwindow->closed = TRUE;
      [osxvideosink->osxwindow->win close];
      [osxvideosink->osxwindow->win release];
    }
  }

  GST_INFO_OBJECT (osxvideosink, "set xwindow id %p", view);
  osxvideosink->superview = [view retain];
  if (osxvideosink->osxwindow) {
    [osxvideosink->osxwindow->gstview addToSuperview: osxvideosink->superview];
    if (view) {
      osxvideosink->osxwindow->internal = FALSE;
    }
  }

  [pool release];
}

857
858
859
860
861
862
863
- (void) resize
{
  GstOSXWindow *osxwindow = osxvideosink->osxwindow;

  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

  GST_INFO_OBJECT (osxvideosink, "resizing");
864
  NSSize size = {osxwindow->width, osxwindow->height};
865
866
867
868
869
870
  if (osxwindow->internal) {
    [osxwindow->win setContentSize:size];
  }
  if (osxwindow->gstview) {
      [osxwindow->gstview setVideoSize :(int)osxwindow->width :(int)osxwindow->height];
  }
871
872
873
874
875
876
877
  GST_INFO_OBJECT (osxvideosink, "done");

  [pool release];
}

- (void) showFrame: (GstBufferObject *) object
{
878
  GstMapInfo info;
879
880
881
882
  GstVideoMeta *vmeta;
  guint8 *data, *readp, *writep;
  gint i, active_width, stride;
  guint8 *texture_buffer;
883
884
885
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  GstBuffer *buf = object->buf;

886
  GST_OBJECT_LOCK (osxvideosink);
887
888
  if (osxvideosink->osxwindow == NULL)
      goto no_window;
889

890
891
892
  texture_buffer = (guint8 *) [osxvideosink->osxwindow->gstview getTextureBuffer];
  if (G_UNLIKELY (texture_buffer == NULL))
      goto no_texture_buffer;
893

894
895
896
897
898
899
900
901
902
  vmeta = (GstVideoMeta *) gst_buffer_get_meta (buf, GST_VIDEO_META_API_TYPE);
  gst_video_meta_map (vmeta, 0, &info, (gpointer *) &data, &stride, GST_MAP_READ);
  readp = data;
  writep = texture_buffer;
  active_width = GST_VIDEO_SINK_WIDTH (osxvideosink) * sizeof (short);
  for (i = 0; i < GST_VIDEO_SINK_HEIGHT (osxvideosink); i++) {
      memcpy (writep, readp, active_width);
      writep += active_width;
      readp += stride;
903
  }
904
905
906
907
908
  [osxvideosink->osxwindow->gstview displayTexture];

  gst_video_meta_unmap (vmeta, 0, &info);

out:
909
  GST_OBJECT_UNLOCK (osxvideosink);
910
911
912
  [object release];

  [pool release];
913
914
915
916
917
918
919
920
921
922
  return;

no_window:
  GST_WARNING_OBJECT (osxvideosink, "not showing frame since we have no window (!?)");
  goto out;

no_texture_buffer:
  GST_ELEMENT_ERROR (osxvideosink, RESOURCE, WRITE, (NULL),
          ("the texture buffer is NULL"));
  goto out;
923
924
925
926
927
}

-(void) destroy
{
  NSAutoreleasePool *pool;
928
  GstOSXWindow *osxwindow;
929
930
931

  pool = [[NSAutoreleasePool alloc] init];

932
933
  osxwindow = osxvideosink->osxwindow;
  osxvideosink->osxwindow = NULL;
934

935
  if (osxwindow) {
936
    if (osxvideosink->superview) {
937
      [osxwindow->gstview removeFromSuperview];
938
    }
939
940
941
942
    [osxwindow->gstview release];
    if (osxwindow->internal) {
      if (!osxwindow->closed) {
        osxwindow->closed = TRUE;
943
        [osxwindow->win close];
944
        [osxwindow->win release];
945
946
      }
    }
947
    g_free (osxwindow);
948
949
950
  }
  [pool release];
}
951

952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
-(void) nsAppThread
{
  NSAutoreleasePool *pool;

  /* set the main runloop as the runloop for the current thread. This has the
   * effect that calling NSApp nextEventMatchingMask:untilDate:inMode:dequeue
   * runs the main runloop.
   */
  _CFRunLoopSetCurrent(CFRunLoopGetMain());

  /* this is needed to make IsMainThread checks in core foundation work from the
   * current thread
   */
  _CFMainPThread = pthread_self();

  pool = [[NSAutoreleasePool alloc] init];

  [NSApplication sharedApplication];
  [NSApp finishLaunching];

972
973
974
  g_mutex_lock (&_run_loop_mutex);
  g_cond_signal (&_run_loop_cond);
  g_mutex_unlock (&_run_loop_mutex);
975

976
977
978
979
980
981
  /* run the loop */
  run_ns_app_loop ();

  [pool release];
}

982
983
-(void) checkMainRunLoop
{
984
985
986
  g_mutex_lock (&_run_loop_mutex);
  g_cond_signal (&_run_loop_cond);
  g_mutex_unlock (&_run_loop_mutex);
987
988
}

989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
@end

@ implementation GstBufferObject
-(id) initWithBuffer: (GstBuffer*) buffer
{
  self = [super init];
  gst_buffer_ref(buffer);
  self->buf = buffer;
  return self;
}

-(void) dealloc{
  gst_buffer_unref(buf);
  [super dealloc];
}
@end

1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
static gboolean
plugin_init (GstPlugin * plugin)
{

  if (!gst_element_register (plugin, "osxvideosink",
          GST_RANK_PRIMARY, GST_TYPE_OSX_VIDEO_SINK))
    return FALSE;

  GST_DEBUG_CATEGORY_INIT (gst_debug_osx_video_sink, "osxvideosink", 0,
      "osxvideosink element");

  return TRUE;
}

GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
    GST_VERSION_MINOR,
1022
    osxvideo,
1023
1024
    "OSX native video output plugin",
    plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)