Merge remote-tracking branch 'remotes/origin/upstream/1.6' into tizen
[platform/upstream/gst-plugins-good.git] / sys / directsound / gstdirectsoundsink.c
1 /* GStreamer
2 * Copyright (C) 2005 Sebastien Moutte <sebastien@moutte.net>
3 * Copyright (C) 2007 Pioneers of the Inevitable <songbird@songbirdnest.com>
4 * Copyright (C) 2010 Fluendo S.A. <support@fluendo.com>
5 *
6 * gstdirectsoundsink.c:
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 * Library General Public License for more details.
17 *
18 * You should have received a copy of the GNU Library General Public
19 * License along with this library; if not, write to the
20 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
22 *
23 *
24 * The development of this code was made possible due to the involvement
25 * of Pioneers of the Inevitable, the creators of the Songbird Music player
26 *
27 */
28
29 /**
30  * SECTION:element-directsoundsink
31  *
32  * This element lets you output sound using the DirectSound API.
33  *
34  * Note that you should almost always use generic audio conversion elements
35  * like audioconvert and audioresample in front of an audiosink to make sure
36  * your pipeline works under all circumstances (those conversion elements will
37  * act in passthrough-mode if no conversion is necessary).
38  *
39  * <refsect2>
40  * <title>Example pipelines</title>
41  * |[
42  * gst-launch-1.0 -v audiotestsrc ! audioconvert ! volume volume=0.1 ! directsoundsink
43  * ]| will output a sine wave (continuous beep sound) to your sound card (with
44  * a very low volume as precaution).
45  * |[
46  * gst-launch-1.0 -v filesrc location=music.ogg ! decodebin ! audioconvert ! audioresample ! directsoundsink
47  * ]| will play an Ogg/Vorbis audio file and output it.
48  * </refsect2>
49  */
50
51 #ifdef HAVE_CONFIG_H
52 #include "config.h"
53 #endif
54
55 #include <gst/base/gstbasesink.h>
56 #include "gstdirectsoundsink.h"
57 #include <gst/audio/gstaudioiec61937.h>
58
59 #include <math.h>
60
61 #ifdef __CYGWIN__
62 #include <unistd.h>
63 #ifndef _swab
64 #define _swab swab
65 #endif
66 #endif
67
68 #define DEFAULT_MUTE FALSE
69
70 GST_DEBUG_CATEGORY_STATIC (directsoundsink_debug);
71 #define GST_CAT_DEFAULT directsoundsink_debug
72
73 static void gst_directsound_sink_finalize (GObject * object);
74
75 static void gst_directsound_sink_set_property (GObject * object, guint prop_id,
76     const GValue * value, GParamSpec * pspec);
77 static void gst_directsound_sink_get_property (GObject * object, guint prop_id,
78     GValue * value, GParamSpec * pspec);
79
80 static GstCaps *gst_directsound_sink_getcaps (GstBaseSink * bsink,
81     GstCaps * filter);
82 static GstBuffer *gst_directsound_sink_payload (GstAudioBaseSink * sink,
83     GstBuffer * buf);
84 static gboolean gst_directsound_sink_prepare (GstAudioSink * asink,
85     GstAudioRingBufferSpec * spec);
86 static gboolean gst_directsound_sink_unprepare (GstAudioSink * asink);
87 static gboolean gst_directsound_sink_open (GstAudioSink * asink);
88 static gboolean gst_directsound_sink_close (GstAudioSink * asink);
89 static gint gst_directsound_sink_write (GstAudioSink * asink,
90     gpointer data, guint length);
91 static guint gst_directsound_sink_delay (GstAudioSink * asink);
92 static void gst_directsound_sink_reset (GstAudioSink * asink);
93 static GstCaps *gst_directsound_probe_supported_formats (GstDirectSoundSink *
94     dsoundsink, const GstCaps * template_caps);
95 static gboolean gst_directsound_sink_query (GstBaseSink * pad,
96     GstQuery * query);
97
98 static void gst_directsound_sink_set_volume (GstDirectSoundSink * sink,
99     gdouble volume, gboolean store);
100 static gdouble gst_directsound_sink_get_volume (GstDirectSoundSink * sink);
101 static void gst_directsound_sink_set_mute (GstDirectSoundSink * sink,
102     gboolean mute);
103 static gboolean gst_directsound_sink_get_mute (GstDirectSoundSink * sink);
104 static const gchar *gst_directsound_sink_get_device (GstDirectSoundSink *
105     dsoundsink);
106 static void gst_directsound_sink_set_device (GstDirectSoundSink * dsoundsink,
107     const gchar * device_id);
108
109 static gboolean gst_directsound_sink_is_spdif_format (GstAudioRingBufferSpec *
110     spec);
111
112 static GstStaticPadTemplate directsoundsink_sink_factory =
113     GST_STATIC_PAD_TEMPLATE ("sink",
114     GST_PAD_SINK,
115     GST_PAD_ALWAYS,
116     GST_STATIC_CAPS ("audio/x-raw, "
117         "format = (string) S16LE, "
118         "layout = (string) interleaved, "
119         "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, 2 ]; "
120         "audio/x-raw, "
121         "format = (string) U8, "
122         "layout = (string) interleaved, "
123         "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, 2 ];"
124         "audio/x-ac3, framed = (boolean) true;"
125         "audio/x-dts, framed = (boolean) true;"));
126
127 enum
128 {
129   PROP_0,
130   PROP_VOLUME,
131   PROP_MUTE,
132   PROP_DEVICE
133 };
134
135 #define gst_directsound_sink_parent_class parent_class
136 G_DEFINE_TYPE_WITH_CODE (GstDirectSoundSink, gst_directsound_sink,
137     GST_TYPE_AUDIO_SINK, G_IMPLEMENT_INTERFACE (GST_TYPE_STREAM_VOLUME, NULL)
138     );
139
140 static void
141 gst_directsound_sink_finalize (GObject * object)
142 {
143   GstDirectSoundSink *dsoundsink = GST_DIRECTSOUND_SINK (object);
144
145   g_free (dsoundsink->device_id);
146   dsoundsink->device_id = NULL;
147
148   g_mutex_clear (&dsoundsink->dsound_lock);
149
150   G_OBJECT_CLASS (parent_class)->finalize (object);
151 }
152
153 static void
154 gst_directsound_sink_class_init (GstDirectSoundSinkClass * klass)
155 {
156   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
157   GstBaseSinkClass *gstbasesink_class = GST_BASE_SINK_CLASS (klass);
158   GstAudioSinkClass *gstaudiosink_class = GST_AUDIO_SINK_CLASS (klass);
159   GstAudioBaseSinkClass *gstaudiobasesink_class =
160       GST_AUDIO_BASE_SINK_CLASS (klass);
161   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
162
163   GST_DEBUG_CATEGORY_INIT (directsoundsink_debug, "directsoundsink", 0,
164       "DirectSound sink");
165
166   gobject_class->finalize = gst_directsound_sink_finalize;
167   gobject_class->set_property = gst_directsound_sink_set_property;
168   gobject_class->get_property = gst_directsound_sink_get_property;
169
170   gstbasesink_class->get_caps =
171       GST_DEBUG_FUNCPTR (gst_directsound_sink_getcaps);
172
173   gstbasesink_class->query = GST_DEBUG_FUNCPTR (gst_directsound_sink_query);
174
175   gstaudiobasesink_class->payload =
176       GST_DEBUG_FUNCPTR (gst_directsound_sink_payload);
177
178   gstaudiosink_class->prepare =
179       GST_DEBUG_FUNCPTR (gst_directsound_sink_prepare);
180   gstaudiosink_class->unprepare =
181       GST_DEBUG_FUNCPTR (gst_directsound_sink_unprepare);
182   gstaudiosink_class->open = GST_DEBUG_FUNCPTR (gst_directsound_sink_open);
183   gstaudiosink_class->close = GST_DEBUG_FUNCPTR (gst_directsound_sink_close);
184   gstaudiosink_class->write = GST_DEBUG_FUNCPTR (gst_directsound_sink_write);
185   gstaudiosink_class->delay = GST_DEBUG_FUNCPTR (gst_directsound_sink_delay);
186   gstaudiosink_class->reset = GST_DEBUG_FUNCPTR (gst_directsound_sink_reset);
187
188   g_object_class_install_property (gobject_class,
189       PROP_VOLUME,
190       g_param_spec_double ("volume", "Volume",
191           "Volume of this stream", 0.0, 1.0, 1.0,
192           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
193
194   g_object_class_install_property (gobject_class,
195       PROP_MUTE,
196       g_param_spec_boolean ("mute", "Mute",
197           "Mute state of this stream", DEFAULT_MUTE,
198           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
199
200   g_object_class_install_property (gobject_class,
201       PROP_DEVICE,
202       g_param_spec_string ("device", "Device",
203           "DirectSound playback device as a GUID string",
204           NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
205
206   gst_element_class_set_static_metadata (element_class,
207       "Direct Sound Audio Sink", "Sink/Audio",
208       "Output to a sound card via Direct Sound",
209       "Sebastien Moutte <sebastien@moutte.net>");
210
211   gst_element_class_add_pad_template (element_class,
212       gst_static_pad_template_get (&directsoundsink_sink_factory));
213 }
214
215 static void
216 gst_directsound_sink_init (GstDirectSoundSink * dsoundsink)
217 {
218   dsoundsink->volume = 100;
219   dsoundsink->mute = FALSE;
220   dsoundsink->device_id = NULL;
221   dsoundsink->pDS = NULL;
222   dsoundsink->cached_caps = NULL;
223   dsoundsink->pDSBSecondary = NULL;
224   dsoundsink->current_circular_offset = 0;
225   dsoundsink->buffer_size = DSBSIZE_MIN;
226   dsoundsink->volume = 100;
227   g_mutex_init (&dsoundsink->dsound_lock);
228   dsoundsink->first_buffer_after_reset = FALSE;
229 }
230
231 static void
232 gst_directsound_sink_set_property (GObject * object,
233     guint prop_id, const GValue * value, GParamSpec * pspec)
234 {
235   GstDirectSoundSink *sink = GST_DIRECTSOUND_SINK (object);
236
237   switch (prop_id) {
238     case PROP_VOLUME:
239       gst_directsound_sink_set_volume (sink, g_value_get_double (value), TRUE);
240       break;
241     case PROP_MUTE:
242       gst_directsound_sink_set_mute (sink, g_value_get_boolean (value));
243       break;
244     case PROP_DEVICE:
245       gst_directsound_sink_set_device (sink, g_value_get_string (value));
246       break;
247     default:
248       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
249       break;
250   }
251 }
252
253 static void
254 gst_directsound_sink_get_property (GObject * object,
255     guint prop_id, GValue * value, GParamSpec * pspec)
256 {
257   GstDirectSoundSink *sink = GST_DIRECTSOUND_SINK (object);
258
259   switch (prop_id) {
260     case PROP_VOLUME:
261       g_value_set_double (value, gst_directsound_sink_get_volume (sink));
262       break;
263     case PROP_MUTE:
264       g_value_set_boolean (value, gst_directsound_sink_get_mute (sink));
265       break;
266     case PROP_DEVICE:
267       g_value_set_string (value, gst_directsound_sink_get_device (sink));
268       break;
269     default:
270       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
271       break;
272   }
273 }
274
275 static GstCaps *
276 gst_directsound_sink_getcaps (GstBaseSink * bsink, GstCaps * filter)
277 {
278   GstElementClass *element_class;
279   GstPadTemplate *pad_template;
280   GstDirectSoundSink *dsoundsink = GST_DIRECTSOUND_SINK (bsink);
281   GstCaps *caps;
282
283   if (dsoundsink->pDS == NULL) {
284     GST_DEBUG_OBJECT (dsoundsink, "device not open, using template caps");
285     return NULL;                /* base class will get template caps for us */
286   }
287
288   if (dsoundsink->cached_caps) {
289     caps = gst_caps_ref (dsoundsink->cached_caps);
290   } else {
291     element_class = GST_ELEMENT_GET_CLASS (dsoundsink);
292     pad_template = gst_element_class_get_pad_template (element_class, "sink");
293     g_return_val_if_fail (pad_template != NULL, NULL);
294
295     caps = gst_directsound_probe_supported_formats (dsoundsink,
296         gst_pad_template_get_caps (pad_template));
297     if (caps)
298       dsoundsink->cached_caps = gst_caps_ref (caps);
299   }
300
301   if (caps && filter) {
302     GstCaps *tmp =
303         gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
304     gst_caps_unref (caps);
305     caps = tmp;
306   }
307
308   if (caps) {
309     gchar *caps_string = gst_caps_to_string (caps);
310     GST_DEBUG_OBJECT (dsoundsink, "returning caps %s", caps_string);
311     g_free (caps_string);
312   }
313
314   return caps;
315 }
316
317 static gboolean
318 gst_directsound_sink_acceptcaps (GstBaseSink * sink, GstQuery * query)
319 {
320   GstDirectSoundSink *dsink = GST_DIRECTSOUND_SINK (sink);
321   GstPad *pad;
322   GstCaps *caps;
323   GstCaps *pad_caps;
324   GstStructure *st;
325   gboolean ret = FALSE;
326   GstAudioRingBufferSpec spec = { 0 };
327
328   if (G_UNLIKELY (dsink == NULL))
329     return FALSE;
330
331   pad = sink->sinkpad;
332
333   gst_query_parse_accept_caps (query, &caps);
334   GST_DEBUG_OBJECT (pad, "caps %" GST_PTR_FORMAT, caps);
335
336   pad_caps = gst_pad_query_caps (pad, NULL);
337   if (pad_caps) {
338     gboolean cret = gst_caps_is_subset (caps, pad_caps);
339     gst_caps_unref (pad_caps);
340     if (!cret) {
341       GST_DEBUG_OBJECT (dsink,
342           "Caps are not a subset of the pad caps, not accepting caps");
343       goto done;
344     }
345   }
346
347   /* If we've not got fixed caps, creating a stream might fail, so let's just
348    * return from here with default acceptcaps behaviour */
349   if (!gst_caps_is_fixed (caps)) {
350     GST_DEBUG_OBJECT (dsink, "Caps are not fixed, not accepting caps");
351     goto done;
352   }
353
354   spec.latency_time = GST_SECOND;
355   if (!gst_audio_ring_buffer_parse_caps (&spec, caps)) {
356     GST_DEBUG_OBJECT (dsink, "Failed to parse caps, not accepting");
357     goto done;
358   }
359
360   /* Make sure input is framed (one frame per buffer) and can be payloaded */
361   switch (spec.type) {
362     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_AC3:
363     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_DTS:
364     {
365       gboolean framed = FALSE, parsed = FALSE;
366       st = gst_caps_get_structure (caps, 0);
367
368       gst_structure_get_boolean (st, "framed", &framed);
369       gst_structure_get_boolean (st, "parsed", &parsed);
370       if ((!framed && !parsed) || gst_audio_iec61937_frame_size (&spec) <= 0) {
371         GST_DEBUG_OBJECT (dsink, "Wrong AC3/DTS caps, not accepting");
372         goto done;
373       }
374     }
375     default:
376       break;
377   }
378   ret = TRUE;
379   GST_DEBUG_OBJECT (dsink, "Accepting caps");
380
381 done:
382   gst_query_set_accept_caps_result (query, ret);
383   return TRUE;
384 }
385
386 static gboolean
387 gst_directsound_sink_query (GstBaseSink * sink, GstQuery * query)
388 {
389   gboolean res = TRUE;
390
391   switch (GST_QUERY_TYPE (query)) {
392     case GST_QUERY_ACCEPT_CAPS:
393       res = gst_directsound_sink_acceptcaps (sink, query);
394       break;
395     default:
396       res = GST_BASE_SINK_CLASS (parent_class)->query (sink, query);
397   }
398
399   return res;
400 }
401
402 static LPGUID
403 string_to_guid (const gchar * str)
404 {
405   HRESULT ret;
406   gunichar2 *wstr;
407   LPGUID out;
408
409   wstr = g_utf8_to_utf16 (str, -1, NULL, NULL, NULL);
410   if (!wstr)
411     return NULL;
412
413   out = g_new (GUID, 1);
414   ret = CLSIDFromString ((LPOLESTR) wstr, out);
415   g_free (wstr);
416   if (ret != NOERROR) {
417     g_free (out);
418     return NULL;
419   }
420
421   return out;
422 }
423
424 static gboolean
425 gst_directsound_sink_open (GstAudioSink * asink)
426 {
427   GstDirectSoundSink *dsoundsink;
428   HRESULT hRes;
429   LPGUID lpGuid = NULL;
430
431   dsoundsink = GST_DIRECTSOUND_SINK (asink);
432
433   if (dsoundsink->device_id)
434     lpGuid = string_to_guid (dsoundsink->device_id);
435
436   /* create and initialize a DirecSound object */
437   if (FAILED (hRes = DirectSoundCreate (lpGuid, &dsoundsink->pDS, NULL))) {
438     GST_ELEMENT_ERROR (dsoundsink, RESOURCE, OPEN_READ,
439         ("gst_directsound_sink_open: DirectSoundCreate: %s",
440             DXGetErrorString9 (hRes)), (NULL));
441     g_free (lpGuid);
442     return FALSE;
443   }
444
445   g_free (lpGuid);
446
447   if (FAILED (hRes = IDirectSound_SetCooperativeLevel (dsoundsink->pDS,
448               GetDesktopWindow (), DSSCL_PRIORITY))) {
449     GST_ELEMENT_ERROR (dsoundsink, RESOURCE, OPEN_READ,
450         ("gst_directsound_sink_open: IDirectSound_SetCooperativeLevel: %s",
451             DXGetErrorString9 (hRes)), (NULL));
452     return FALSE;
453   }
454
455   return TRUE;
456 }
457
458 static gboolean
459 gst_directsound_sink_is_spdif_format (GstAudioRingBufferSpec * spec)
460 {
461   return spec->type == GST_AUDIO_RING_BUFFER_FORMAT_TYPE_AC3 ||
462       spec->type == GST_AUDIO_RING_BUFFER_FORMAT_TYPE_DTS;
463 }
464
465 static gboolean
466 gst_directsound_sink_prepare (GstAudioSink * asink,
467     GstAudioRingBufferSpec * spec)
468 {
469   GstDirectSoundSink *dsoundsink;
470   HRESULT hRes;
471   DSBUFFERDESC descSecondary;
472   WAVEFORMATEX wfx;
473
474   dsoundsink = GST_DIRECTSOUND_SINK (asink);
475
476   /*save number of bytes per sample and buffer format */
477   dsoundsink->bytes_per_sample = spec->info.bpf;
478   dsoundsink->type = spec->type;
479
480   /* fill the WAVEFORMATEX structure with spec params */
481   memset (&wfx, 0, sizeof (wfx));
482   if (!gst_directsound_sink_is_spdif_format (spec)) {
483     wfx.cbSize = sizeof (wfx);
484     wfx.wFormatTag = WAVE_FORMAT_PCM;
485     wfx.nChannels = spec->info.channels;
486     wfx.nSamplesPerSec = spec->info.rate;
487     wfx.wBitsPerSample = (spec->info.bpf * 8) / wfx.nChannels;
488     wfx.nBlockAlign = spec->info.bpf;
489     wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
490
491     /* Create directsound buffer with size based on our configured
492      * buffer_size (which is 200 ms by default) */
493     dsoundsink->buffer_size =
494         gst_util_uint64_scale_int (wfx.nAvgBytesPerSec, spec->buffer_time,
495         GST_MSECOND);
496     /* Make sure we make those numbers multiple of our sample size in bytes */
497     dsoundsink->buffer_size -= dsoundsink->buffer_size % spec->info.bpf;
498
499     spec->segsize =
500         gst_util_uint64_scale_int (wfx.nAvgBytesPerSec, spec->latency_time,
501         GST_MSECOND);
502     spec->segsize -= spec->segsize % spec->info.bpf;
503     spec->segtotal = dsoundsink->buffer_size / spec->segsize;
504   } else {
505 #ifdef WAVE_FORMAT_DOLBY_AC3_SPDIF
506     wfx.cbSize = 0;
507     wfx.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
508     wfx.nChannels = 2;
509     wfx.nSamplesPerSec = 48000;
510     wfx.wBitsPerSample = 16;
511     wfx.nBlockAlign = wfx.wBitsPerSample / 8 * wfx.nChannels;
512     wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
513
514     spec->segsize = 6144;
515     spec->segtotal = 10;
516 #else
517     g_assert_not_reached ();
518 #endif
519   }
520
521   // Make the final buffer size be an integer number of segments
522   dsoundsink->buffer_size = spec->segsize * spec->segtotal;
523
524   GST_INFO_OBJECT (dsoundsink,
525       "GstAudioRingBufferSpec->channels: %d, GstAudioRingBufferSpec->rate: %d, GstAudioRingBufferSpec->bytes_per_sample: %d\n"
526       "WAVEFORMATEX.nSamplesPerSec: %ld, WAVEFORMATEX.wBitsPerSample: %d, WAVEFORMATEX.nBlockAlign: %d, WAVEFORMATEX.nAvgBytesPerSec: %ld\n"
527       "Size of dsound circular buffer=>%d\n", spec->info.channels,
528       spec->info.rate, spec->info.bpf, wfx.nSamplesPerSec, wfx.wBitsPerSample,
529       wfx.nBlockAlign, wfx.nAvgBytesPerSec, dsoundsink->buffer_size);
530
531   /* create a secondary directsound buffer */
532   memset (&descSecondary, 0, sizeof (DSBUFFERDESC));
533   descSecondary.dwSize = sizeof (DSBUFFERDESC);
534   descSecondary.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_GLOBALFOCUS;
535   if (!gst_directsound_sink_is_spdif_format (spec))
536     descSecondary.dwFlags |= DSBCAPS_CTRLVOLUME;
537
538   descSecondary.dwBufferBytes = dsoundsink->buffer_size;
539   descSecondary.lpwfxFormat = (WAVEFORMATEX *) & wfx;
540
541   hRes = IDirectSound_CreateSoundBuffer (dsoundsink->pDS, &descSecondary,
542       &dsoundsink->pDSBSecondary, NULL);
543   if (FAILED (hRes)) {
544     GST_ELEMENT_ERROR (dsoundsink, RESOURCE, OPEN_READ,
545         ("gst_directsound_sink_prepare: IDirectSound_CreateSoundBuffer: %s",
546             DXGetErrorString9 (hRes)), (NULL));
547     return FALSE;
548   }
549
550   gst_directsound_sink_set_volume (dsoundsink, dsoundsink->volume, FALSE);
551
552   return TRUE;
553 }
554
555 static gboolean
556 gst_directsound_sink_unprepare (GstAudioSink * asink)
557 {
558   GstDirectSoundSink *dsoundsink;
559
560   dsoundsink = GST_DIRECTSOUND_SINK (asink);
561
562   /* release secondary DirectSound buffer */
563   if (dsoundsink->pDSBSecondary) {
564     IDirectSoundBuffer_Release (dsoundsink->pDSBSecondary);
565     dsoundsink->pDSBSecondary = NULL;
566   }
567
568   return TRUE;
569 }
570
571 static gboolean
572 gst_directsound_sink_close (GstAudioSink * asink)
573 {
574   GstDirectSoundSink *dsoundsink = NULL;
575
576   dsoundsink = GST_DIRECTSOUND_SINK (asink);
577
578   /* release DirectSound object */
579   g_return_val_if_fail (dsoundsink->pDS != NULL, FALSE);
580   IDirectSound_Release (dsoundsink->pDS);
581   dsoundsink->pDS = NULL;
582
583   gst_caps_replace (&dsoundsink->cached_caps, NULL);
584
585   return TRUE;
586 }
587
588 static gint
589 gst_directsound_sink_write (GstAudioSink * asink, gpointer data, guint length)
590 {
591   GstDirectSoundSink *dsoundsink;
592   DWORD dwStatus;
593   HRESULT hRes;
594   LPVOID pLockedBuffer1 = NULL, pLockedBuffer2 = NULL;
595   DWORD dwSizeBuffer1, dwSizeBuffer2;
596   DWORD dwCurrentPlayCursor;
597
598   dsoundsink = GST_DIRECTSOUND_SINK (asink);
599
600   GST_DSOUND_LOCK (dsoundsink);
601
602   /* get current buffer status */
603   hRes = IDirectSoundBuffer_GetStatus (dsoundsink->pDSBSecondary, &dwStatus);
604
605   /* get current play cursor position */
606   hRes = IDirectSoundBuffer_GetCurrentPosition (dsoundsink->pDSBSecondary,
607       &dwCurrentPlayCursor, NULL);
608
609   if (SUCCEEDED (hRes) && (dwStatus & DSBSTATUS_PLAYING)) {
610     DWORD dwFreeBufferSize;
611
612   calculate_freesize:
613     /* calculate the free size of the circular buffer */
614     if (dwCurrentPlayCursor < dsoundsink->current_circular_offset)
615       dwFreeBufferSize =
616           dsoundsink->buffer_size - (dsoundsink->current_circular_offset -
617           dwCurrentPlayCursor);
618     else
619       dwFreeBufferSize =
620           dwCurrentPlayCursor - dsoundsink->current_circular_offset;
621
622     if (length >= dwFreeBufferSize) {
623       Sleep (100);
624       hRes = IDirectSoundBuffer_GetCurrentPosition (dsoundsink->pDSBSecondary,
625           &dwCurrentPlayCursor, NULL);
626
627       hRes =
628           IDirectSoundBuffer_GetStatus (dsoundsink->pDSBSecondary, &dwStatus);
629       if (SUCCEEDED (hRes) && (dwStatus & DSBSTATUS_PLAYING))
630         goto calculate_freesize;
631       else {
632         dsoundsink->first_buffer_after_reset = FALSE;
633         GST_DSOUND_UNLOCK (dsoundsink);
634         return 0;
635       }
636     }
637   }
638
639   if (dwStatus & DSBSTATUS_BUFFERLOST) {
640     hRes = IDirectSoundBuffer_Restore (dsoundsink->pDSBSecondary);      /*need a loop waiting the buffer is restored?? */
641
642     dsoundsink->current_circular_offset = 0;
643   }
644
645   hRes = IDirectSoundBuffer_Lock (dsoundsink->pDSBSecondary,
646       dsoundsink->current_circular_offset, length, &pLockedBuffer1,
647       &dwSizeBuffer1, &pLockedBuffer2, &dwSizeBuffer2, 0L);
648
649   if (SUCCEEDED (hRes)) {
650     // Write to pointers without reordering.
651     memcpy (pLockedBuffer1, data, dwSizeBuffer1);
652     if (pLockedBuffer2 != NULL)
653       memcpy (pLockedBuffer2, (LPBYTE) data + dwSizeBuffer1, dwSizeBuffer2);
654
655     // Update where the buffer will lock (for next time)
656     dsoundsink->current_circular_offset += dwSizeBuffer1 + dwSizeBuffer2;
657     dsoundsink->current_circular_offset %= dsoundsink->buffer_size;     /* Circular buffer */
658
659     hRes = IDirectSoundBuffer_Unlock (dsoundsink->pDSBSecondary, pLockedBuffer1,
660         dwSizeBuffer1, pLockedBuffer2, dwSizeBuffer2);
661   }
662
663   /* if the buffer was not in playing state yet, call play on the buffer 
664      except if this buffer is the fist after a reset (base class call reset and write a buffer when setting the sink to pause) */
665   if (!(dwStatus & DSBSTATUS_PLAYING) &&
666       dsoundsink->first_buffer_after_reset == FALSE) {
667     hRes = IDirectSoundBuffer_Play (dsoundsink->pDSBSecondary, 0, 0,
668         DSBPLAY_LOOPING);
669   }
670
671   dsoundsink->first_buffer_after_reset = FALSE;
672
673   GST_DSOUND_UNLOCK (dsoundsink);
674
675   return length;
676 }
677
678 static guint
679 gst_directsound_sink_delay (GstAudioSink * asink)
680 {
681   GstDirectSoundSink *dsoundsink;
682   HRESULT hRes;
683   DWORD dwCurrentPlayCursor;
684   DWORD dwBytesInQueue = 0;
685   gint nNbSamplesInQueue = 0;
686   DWORD dwStatus;
687
688   dsoundsink = GST_DIRECTSOUND_SINK (asink);
689
690   /* get current buffer status */
691   hRes = IDirectSoundBuffer_GetStatus (dsoundsink->pDSBSecondary, &dwStatus);
692
693   if (dwStatus & DSBSTATUS_PLAYING) {
694     /*evaluate the number of samples in queue in the circular buffer */
695     hRes = IDirectSoundBuffer_GetCurrentPosition (dsoundsink->pDSBSecondary,
696         &dwCurrentPlayCursor, NULL);
697
698     if (hRes == S_OK) {
699       if (dwCurrentPlayCursor < dsoundsink->current_circular_offset)
700         dwBytesInQueue =
701             dsoundsink->current_circular_offset - dwCurrentPlayCursor;
702       else
703         dwBytesInQueue =
704             dsoundsink->current_circular_offset + (dsoundsink->buffer_size -
705             dwCurrentPlayCursor);
706
707       nNbSamplesInQueue = dwBytesInQueue / dsoundsink->bytes_per_sample;
708     }
709   }
710
711   return nNbSamplesInQueue;
712 }
713
714 static void
715 gst_directsound_sink_reset (GstAudioSink * asink)
716 {
717   GstDirectSoundSink *dsoundsink;
718   LPVOID pLockedBuffer = NULL;
719   DWORD dwSizeBuffer = 0;
720
721   dsoundsink = GST_DIRECTSOUND_SINK (asink);
722
723   GST_DSOUND_LOCK (dsoundsink);
724
725   if (dsoundsink->pDSBSecondary) {
726     /*stop playing */
727     HRESULT hRes = IDirectSoundBuffer_Stop (dsoundsink->pDSBSecondary);
728
729     /*reset position */
730     hRes = IDirectSoundBuffer_SetCurrentPosition (dsoundsink->pDSBSecondary, 0);
731     dsoundsink->current_circular_offset = 0;
732
733     /*reset the buffer */
734     hRes = IDirectSoundBuffer_Lock (dsoundsink->pDSBSecondary,
735         dsoundsink->current_circular_offset, dsoundsink->buffer_size,
736         &pLockedBuffer, &dwSizeBuffer, NULL, NULL, 0L);
737
738     if (SUCCEEDED (hRes)) {
739       memset (pLockedBuffer, 0, dwSizeBuffer);
740
741       hRes =
742           IDirectSoundBuffer_Unlock (dsoundsink->pDSBSecondary, pLockedBuffer,
743           dwSizeBuffer, NULL, 0);
744     }
745   }
746
747   dsoundsink->first_buffer_after_reset = TRUE;
748
749   GST_DSOUND_UNLOCK (dsoundsink);
750 }
751
752 /*
753  * gst_directsound_probe_supported_formats:
754  *
755  * Takes the template caps and returns the subset which is actually
756  * supported by this device.
757  *
758  */
759
760 static GstCaps *
761 gst_directsound_probe_supported_formats (GstDirectSoundSink * dsoundsink,
762     const GstCaps * template_caps)
763 {
764   HRESULT hRes;
765   DSBUFFERDESC descSecondary;
766   WAVEFORMATEX wfx;
767   GstCaps *caps;
768   GstCaps *tmp, *tmp2;
769   LPDIRECTSOUNDBUFFER tmpBuffer;
770
771   caps = gst_caps_copy (template_caps);
772
773   /*
774    * Check availability of digital output by trying to create an SPDIF buffer
775    */
776
777 #ifdef WAVE_FORMAT_DOLBY_AC3_SPDIF
778   /* fill the WAVEFORMATEX structure with some standard AC3 over SPDIF params */
779   memset (&wfx, 0, sizeof (wfx));
780   wfx.cbSize = 0;
781   wfx.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
782   wfx.nChannels = 2;
783   wfx.nSamplesPerSec = 48000;
784   wfx.wBitsPerSample = 16;
785   wfx.nBlockAlign = 4;
786   wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
787
788   // create a secondary directsound buffer
789   memset (&descSecondary, 0, sizeof (DSBUFFERDESC));
790   descSecondary.dwSize = sizeof (DSBUFFERDESC);
791   descSecondary.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_GLOBALFOCUS;
792   descSecondary.dwBufferBytes = 6144;
793   descSecondary.lpwfxFormat = &wfx;
794
795   hRes = IDirectSound_CreateSoundBuffer (dsoundsink->pDS, &descSecondary,
796       &tmpBuffer, NULL);
797   if (FAILED (hRes)) {
798     GST_INFO_OBJECT (dsoundsink, "AC3 passthrough not supported "
799         "(IDirectSound_CreateSoundBuffer returned: %s)\n",
800         DXGetErrorString9 (hRes));
801     tmp = gst_caps_new_empty_simple ("audio/x-ac3");
802     tmp2 = gst_caps_subtract (caps, tmp);
803     gst_caps_unref (tmp);
804     gst_caps_unref (caps);
805     caps = tmp2;
806     tmp = gst_caps_new_empty_simple ("audio/x-dts");
807     tmp2 = gst_caps_subtract (caps, tmp);
808     gst_caps_unref (tmp);
809     gst_caps_unref (caps);
810     caps = tmp2;
811   } else {
812     GST_INFO_OBJECT (dsoundsink, "AC3 passthrough supported");
813     hRes = IDirectSoundBuffer_Release (tmpBuffer);
814     if (FAILED (hRes)) {
815       GST_DEBUG_OBJECT (dsoundsink,
816           "(IDirectSoundBuffer_Release returned: %s)\n",
817           DXGetErrorString9 (hRes));
818     }
819   }
820 #else
821   tmp = gst_caps_new_empty_simple ("audio/x-ac3");
822   tmp2 = gst_caps_subtract (caps, tmp);
823   gst_caps_unref (tmp);
824   gst_caps_unref (caps);
825   caps = tmp2;
826   tmp = gst_caps_new_empty_simple ("audio/x-dts");
827   tmp2 = gst_caps_subtract (caps, tmp);
828   gst_caps_unref (tmp);
829   gst_caps_unref (caps);
830   caps = tmp2;
831 #endif
832
833   return caps;
834 }
835
836 static GstBuffer *
837 gst_directsound_sink_payload (GstAudioBaseSink * sink, GstBuffer * buf)
838 {
839   if (gst_directsound_sink_is_spdif_format (&sink->ringbuffer->spec)) {
840     gint framesize = gst_audio_iec61937_frame_size (&sink->ringbuffer->spec);
841     GstBuffer *out;
842     GstMapInfo infobuf, infoout;
843     gboolean success;
844
845     if (framesize <= 0)
846       return NULL;
847
848     out = gst_buffer_new_and_alloc (framesize);
849
850     if (!gst_buffer_map (buf, &infobuf, GST_MAP_READWRITE)) {
851       gst_buffer_unref (out);
852       return NULL;
853     }
854     if (!gst_buffer_map (out, &infoout, GST_MAP_READWRITE)) {
855       gst_buffer_unmap (buf, &infobuf);
856       gst_buffer_unref (out);
857       return NULL;
858     }
859     success = gst_audio_iec61937_payload (infobuf.data, infobuf.size,
860         infoout.data, infoout.size, &sink->ringbuffer->spec, G_BYTE_ORDER);
861     if (!success) {
862       gst_buffer_unmap (out, &infoout);
863       gst_buffer_unmap (buf, &infobuf);
864       gst_buffer_unref (out);
865       return NULL;
866     }
867
868     gst_buffer_copy_into (out, buf, GST_BUFFER_COPY_ALL, 0, -1);
869     /* Fix endianness */
870     _swab ((gchar *) infoout.data, (gchar *) infoout.data, infobuf.size);
871     gst_buffer_unmap (out, &infoout);
872     gst_buffer_unmap (buf, &infobuf);
873     return out;
874   } else
875     return gst_buffer_ref (buf);
876 }
877
878 static void
879 gst_directsound_sink_set_volume (GstDirectSoundSink * dsoundsink,
880     gdouble dvolume, gboolean store)
881 {
882   glong volume;
883
884   volume = dvolume * 100;
885   if (store)
886     dsoundsink->volume = volume;
887
888   if (dsoundsink->pDSBSecondary) {
889     /* DirectSound controls volume using units of 100th of a decibel,
890      * ranging from -10000 to 0. We use a linear scale of 0 - 100
891      * here, so remap.
892      */
893     long dsVolume;
894     if (dsoundsink->volume == 0)
895       dsVolume = -10000;
896     else
897       dsVolume = 100 * (long) (20 * log10 ((double) dsoundsink->volume / 100.));
898     dsVolume = CLAMP (dsVolume, -10000, 0);
899
900     GST_DEBUG_OBJECT (dsoundsink,
901         "Setting volume on secondary buffer to %d from %d", (int) dsVolume,
902         (int) dsoundsink->volume);
903     IDirectSoundBuffer_SetVolume (dsoundsink->pDSBSecondary, dsVolume);
904   }
905 }
906
907 gdouble
908 gst_directsound_sink_get_volume (GstDirectSoundSink * dsoundsink)
909 {
910   return (gdouble) dsoundsink->volume / 100;
911 }
912
913 static void
914 gst_directsound_sink_set_mute (GstDirectSoundSink * dsoundsink, gboolean mute)
915 {
916   if (mute)
917     gst_directsound_sink_set_volume (dsoundsink, 0, FALSE);
918   else
919     gst_directsound_sink_set_volume (dsoundsink, dsoundsink->volume, FALSE);
920 }
921
922 static gboolean
923 gst_directsound_sink_get_mute (GstDirectSoundSink * dsoundsink)
924 {
925   return FALSE;
926 }
927
928 static const gchar *
929 gst_directsound_sink_get_device (GstDirectSoundSink * dsoundsink)
930 {
931   return dsoundsink->device_id;
932 }
933
934 static void
935 gst_directsound_sink_set_device (GstDirectSoundSink * dsoundsink,
936     const gchar * device_id)
937 {
938   g_free (dsoundsink->device_id);
939   dsoundsink->device_id = g_strdup (device_id);
940 }