splitmuxsink: Correctly catch FLUSH events in probes
[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 gchar *gst_hres_to_string (HRESULT hRes);
113
114 static GstStaticPadTemplate directsoundsink_sink_factory =
115     GST_STATIC_PAD_TEMPLATE ("sink",
116     GST_PAD_SINK,
117     GST_PAD_ALWAYS,
118     GST_STATIC_CAPS ("audio/x-raw, "
119         "format = (string) S16LE, "
120         "layout = (string) interleaved, "
121         "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, 2 ]; "
122         "audio/x-raw, "
123         "format = (string) U8, "
124         "layout = (string) interleaved, "
125         "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, 2 ];"
126         "audio/x-ac3, framed = (boolean) true;"
127         "audio/x-dts, framed = (boolean) true;"));
128
129 enum
130 {
131   PROP_0,
132   PROP_VOLUME,
133   PROP_MUTE,
134   PROP_DEVICE
135 };
136
137 #define gst_directsound_sink_parent_class parent_class
138 G_DEFINE_TYPE_WITH_CODE (GstDirectSoundSink, gst_directsound_sink,
139     GST_TYPE_AUDIO_SINK, G_IMPLEMENT_INTERFACE (GST_TYPE_STREAM_VOLUME, NULL)
140     );
141
142 static void
143 gst_directsound_sink_finalize (GObject * object)
144 {
145   GstDirectSoundSink *dsoundsink = GST_DIRECTSOUND_SINK (object);
146
147   g_free (dsoundsink->device_id);
148   dsoundsink->device_id = NULL;
149
150   g_mutex_clear (&dsoundsink->dsound_lock);
151
152   G_OBJECT_CLASS (parent_class)->finalize (object);
153 }
154
155 static void
156 gst_directsound_sink_class_init (GstDirectSoundSinkClass * klass)
157 {
158   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
159   GstBaseSinkClass *gstbasesink_class = GST_BASE_SINK_CLASS (klass);
160   GstAudioSinkClass *gstaudiosink_class = GST_AUDIO_SINK_CLASS (klass);
161   GstAudioBaseSinkClass *gstaudiobasesink_class =
162       GST_AUDIO_BASE_SINK_CLASS (klass);
163   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
164
165   GST_DEBUG_CATEGORY_INIT (directsoundsink_debug, "directsoundsink", 0,
166       "DirectSound sink");
167
168   gobject_class->finalize = gst_directsound_sink_finalize;
169   gobject_class->set_property = gst_directsound_sink_set_property;
170   gobject_class->get_property = gst_directsound_sink_get_property;
171
172   gstbasesink_class->get_caps =
173       GST_DEBUG_FUNCPTR (gst_directsound_sink_getcaps);
174
175   gstbasesink_class->query = GST_DEBUG_FUNCPTR (gst_directsound_sink_query);
176
177   gstaudiobasesink_class->payload =
178       GST_DEBUG_FUNCPTR (gst_directsound_sink_payload);
179
180   gstaudiosink_class->prepare =
181       GST_DEBUG_FUNCPTR (gst_directsound_sink_prepare);
182   gstaudiosink_class->unprepare =
183       GST_DEBUG_FUNCPTR (gst_directsound_sink_unprepare);
184   gstaudiosink_class->open = GST_DEBUG_FUNCPTR (gst_directsound_sink_open);
185   gstaudiosink_class->close = GST_DEBUG_FUNCPTR (gst_directsound_sink_close);
186   gstaudiosink_class->write = GST_DEBUG_FUNCPTR (gst_directsound_sink_write);
187   gstaudiosink_class->delay = GST_DEBUG_FUNCPTR (gst_directsound_sink_delay);
188   gstaudiosink_class->reset = GST_DEBUG_FUNCPTR (gst_directsound_sink_reset);
189
190   g_object_class_install_property (gobject_class,
191       PROP_VOLUME,
192       g_param_spec_double ("volume", "Volume",
193           "Volume of this stream", 0.0, 1.0, 1.0,
194           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
195
196   g_object_class_install_property (gobject_class,
197       PROP_MUTE,
198       g_param_spec_boolean ("mute", "Mute",
199           "Mute state of this stream", DEFAULT_MUTE,
200           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
201
202   g_object_class_install_property (gobject_class,
203       PROP_DEVICE,
204       g_param_spec_string ("device", "Device",
205           "DirectSound playback device as a GUID string",
206           NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
207
208   gst_element_class_set_static_metadata (element_class,
209       "Direct Sound Audio Sink", "Sink/Audio",
210       "Output to a sound card via Direct Sound",
211       "Sebastien Moutte <sebastien@moutte.net>");
212
213   gst_element_class_add_static_pad_template (element_class,
214       &directsoundsink_sink_factory);
215 }
216
217 static void
218 gst_directsound_sink_init (GstDirectSoundSink * dsoundsink)
219 {
220   dsoundsink->volume = 100;
221   dsoundsink->mute = FALSE;
222   dsoundsink->device_id = NULL;
223   dsoundsink->pDS = NULL;
224   dsoundsink->cached_caps = NULL;
225   dsoundsink->pDSBSecondary = NULL;
226   dsoundsink->current_circular_offset = 0;
227   dsoundsink->buffer_size = DSBSIZE_MIN;
228   dsoundsink->volume = 100;
229   g_mutex_init (&dsoundsink->dsound_lock);
230   dsoundsink->first_buffer_after_reset = FALSE;
231 }
232
233 static void
234 gst_directsound_sink_set_property (GObject * object,
235     guint prop_id, const GValue * value, GParamSpec * pspec)
236 {
237   GstDirectSoundSink *sink = GST_DIRECTSOUND_SINK (object);
238
239   switch (prop_id) {
240     case PROP_VOLUME:
241       gst_directsound_sink_set_volume (sink, g_value_get_double (value), TRUE);
242       break;
243     case PROP_MUTE:
244       gst_directsound_sink_set_mute (sink, g_value_get_boolean (value));
245       break;
246     case PROP_DEVICE:
247       gst_directsound_sink_set_device (sink, g_value_get_string (value));
248       break;
249     default:
250       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
251       break;
252   }
253 }
254
255 static void
256 gst_directsound_sink_get_property (GObject * object,
257     guint prop_id, GValue * value, GParamSpec * pspec)
258 {
259   GstDirectSoundSink *sink = GST_DIRECTSOUND_SINK (object);
260
261   switch (prop_id) {
262     case PROP_VOLUME:
263       g_value_set_double (value, gst_directsound_sink_get_volume (sink));
264       break;
265     case PROP_MUTE:
266       g_value_set_boolean (value, gst_directsound_sink_get_mute (sink));
267       break;
268     case PROP_DEVICE:
269       g_value_set_string (value, gst_directsound_sink_get_device (sink));
270       break;
271     default:
272       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
273       break;
274   }
275 }
276
277 static GstCaps *
278 gst_directsound_sink_getcaps (GstBaseSink * bsink, GstCaps * filter)
279 {
280   GstElementClass *element_class;
281   GstPadTemplate *pad_template;
282   GstDirectSoundSink *dsoundsink = GST_DIRECTSOUND_SINK (bsink);
283   GstCaps *caps;
284
285   if (dsoundsink->pDS == NULL) {
286     GST_DEBUG_OBJECT (dsoundsink, "device not open, using template caps");
287     return NULL;                /* base class will get template caps for us */
288   }
289
290   if (dsoundsink->cached_caps) {
291     caps = gst_caps_ref (dsoundsink->cached_caps);
292   } else {
293     element_class = GST_ELEMENT_GET_CLASS (dsoundsink);
294     pad_template = gst_element_class_get_pad_template (element_class, "sink");
295     g_return_val_if_fail (pad_template != NULL, NULL);
296
297     caps = gst_directsound_probe_supported_formats (dsoundsink,
298         gst_pad_template_get_caps (pad_template));
299     if (caps)
300       dsoundsink->cached_caps = gst_caps_ref (caps);
301   }
302
303   if (caps && filter) {
304     GstCaps *tmp =
305         gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
306     gst_caps_unref (caps);
307     caps = tmp;
308   }
309
310   if (caps) {
311     gchar *caps_string = gst_caps_to_string (caps);
312     GST_DEBUG_OBJECT (dsoundsink, "returning caps %s", caps_string);
313     g_free (caps_string);
314   }
315
316   return caps;
317 }
318
319 static gboolean
320 gst_directsound_sink_acceptcaps (GstBaseSink * sink, GstQuery * query)
321 {
322   GstDirectSoundSink *dsink = GST_DIRECTSOUND_SINK (sink);
323   GstPad *pad;
324   GstCaps *caps;
325   GstCaps *pad_caps;
326   GstStructure *st;
327   gboolean ret = FALSE;
328   GstAudioRingBufferSpec spec = { 0 };
329
330   if (G_UNLIKELY (dsink == NULL))
331     return FALSE;
332
333   pad = sink->sinkpad;
334
335   gst_query_parse_accept_caps (query, &caps);
336   GST_DEBUG_OBJECT (pad, "caps %" GST_PTR_FORMAT, caps);
337
338   pad_caps = gst_pad_query_caps (pad, NULL);
339   if (pad_caps) {
340     gboolean cret = gst_caps_is_subset (caps, pad_caps);
341     gst_caps_unref (pad_caps);
342     if (!cret) {
343       GST_DEBUG_OBJECT (dsink,
344           "Caps are not a subset of the pad caps, not accepting caps");
345       goto done;
346     }
347   }
348
349   /* If we've not got fixed caps, creating a stream might fail, so let's just
350    * return from here with default acceptcaps behaviour */
351   if (!gst_caps_is_fixed (caps)) {
352     GST_DEBUG_OBJECT (dsink, "Caps are not fixed, not accepting caps");
353     goto done;
354   }
355
356   spec.latency_time = GST_SECOND;
357   if (!gst_audio_ring_buffer_parse_caps (&spec, caps)) {
358     GST_DEBUG_OBJECT (dsink, "Failed to parse caps, not accepting");
359     goto done;
360   }
361
362   /* Make sure input is framed (one frame per buffer) and can be payloaded */
363   switch (spec.type) {
364     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_AC3:
365     case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_DTS:
366     {
367       gboolean framed = FALSE, parsed = FALSE;
368       st = gst_caps_get_structure (caps, 0);
369
370       gst_structure_get_boolean (st, "framed", &framed);
371       gst_structure_get_boolean (st, "parsed", &parsed);
372       if ((!framed && !parsed) || gst_audio_iec61937_frame_size (&spec) <= 0) {
373         GST_DEBUG_OBJECT (dsink, "Wrong AC3/DTS caps, not accepting");
374         goto done;
375       }
376     }
377     default:
378       break;
379   }
380   ret = TRUE;
381   GST_DEBUG_OBJECT (dsink, "Accepting caps");
382
383 done:
384   gst_query_set_accept_caps_result (query, ret);
385   return TRUE;
386 }
387
388 static gboolean
389 gst_directsound_sink_query (GstBaseSink * sink, GstQuery * query)
390 {
391   gboolean res = TRUE;
392
393   switch (GST_QUERY_TYPE (query)) {
394     case GST_QUERY_ACCEPT_CAPS:
395       res = gst_directsound_sink_acceptcaps (sink, query);
396       break;
397     default:
398       res = GST_BASE_SINK_CLASS (parent_class)->query (sink, query);
399   }
400
401   return res;
402 }
403
404 static LPGUID
405 string_to_guid (const gchar * str)
406 {
407   HRESULT ret;
408   gunichar2 *wstr;
409   LPGUID out;
410
411   wstr = g_utf8_to_utf16 (str, -1, NULL, NULL, NULL);
412   if (!wstr)
413     return NULL;
414
415   out = g_new (GUID, 1);
416   ret = CLSIDFromString ((LPOLESTR) wstr, out);
417   g_free (wstr);
418   if (ret != NOERROR) {
419     g_free (out);
420     return NULL;
421   }
422
423   return out;
424 }
425
426 static gboolean
427 gst_directsound_sink_open (GstAudioSink * asink)
428 {
429   GstDirectSoundSink *dsoundsink;
430   HRESULT hRes;
431   LPGUID lpGuid = NULL;
432
433   dsoundsink = GST_DIRECTSOUND_SINK (asink);
434
435   if (dsoundsink->device_id) {
436     lpGuid = string_to_guid (dsoundsink->device_id);
437     if (lpGuid == NULL) {
438       GST_ELEMENT_ERROR (dsoundsink, RESOURCE, OPEN_READ,
439           ("gst_directsound_sink_open: device set, but guid not found: %s",
440               dsoundsink->device_id), (NULL));
441       return FALSE;
442     }
443   }
444
445   /* create and initialize a DirecSound object */
446   if (FAILED (hRes = DirectSoundCreate (lpGuid, &dsoundsink->pDS, NULL))) {
447     gchar *error_text = gst_hres_to_string (hRes);
448     GST_ELEMENT_ERROR (dsoundsink, RESOURCE, OPEN_READ,
449         ("gst_directsound_sink_open: DirectSoundCreate: %s",
450             error_text), (NULL));
451     g_free (lpGuid);
452     g_free (error_text);
453     return FALSE;
454   }
455
456   g_free (lpGuid);
457
458   if (FAILED (hRes = IDirectSound_SetCooperativeLevel (dsoundsink->pDS,
459               GetDesktopWindow (), DSSCL_PRIORITY))) {
460     gchar *error_text = gst_hres_to_string (hRes);
461     GST_ELEMENT_ERROR (dsoundsink, RESOURCE, OPEN_READ,
462         ("gst_directsound_sink_open: IDirectSound_SetCooperativeLevel: %s",
463             error_text), (NULL));
464     g_free (error_text);
465     return FALSE;
466   }
467
468   return TRUE;
469 }
470
471 static gboolean
472 gst_directsound_sink_is_spdif_format (GstAudioRingBufferSpec * spec)
473 {
474   return spec->type == GST_AUDIO_RING_BUFFER_FORMAT_TYPE_AC3 ||
475       spec->type == GST_AUDIO_RING_BUFFER_FORMAT_TYPE_DTS;
476 }
477
478 static gboolean
479 gst_directsound_sink_prepare (GstAudioSink * asink,
480     GstAudioRingBufferSpec * spec)
481 {
482   GstDirectSoundSink *dsoundsink;
483   HRESULT hRes;
484   DSBUFFERDESC descSecondary;
485   WAVEFORMATEX wfx;
486
487   dsoundsink = GST_DIRECTSOUND_SINK (asink);
488
489   /*save number of bytes per sample and buffer format */
490   dsoundsink->bytes_per_sample = spec->info.bpf;
491   dsoundsink->type = spec->type;
492
493   /* fill the WAVEFORMATEX structure with spec params */
494   memset (&wfx, 0, sizeof (wfx));
495   if (!gst_directsound_sink_is_spdif_format (spec)) {
496     wfx.cbSize = sizeof (wfx);
497     wfx.wFormatTag = WAVE_FORMAT_PCM;
498     wfx.nChannels = spec->info.channels;
499     wfx.nSamplesPerSec = spec->info.rate;
500     wfx.wBitsPerSample = (spec->info.bpf * 8) / wfx.nChannels;
501     wfx.nBlockAlign = spec->info.bpf;
502     wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
503
504     /* Create directsound buffer with size based on our configured
505      * buffer_size (which is 200 ms by default) */
506     dsoundsink->buffer_size =
507         gst_util_uint64_scale_int (wfx.nAvgBytesPerSec, spec->buffer_time,
508         GST_MSECOND);
509     /* Make sure we make those numbers multiple of our sample size in bytes */
510     dsoundsink->buffer_size -= dsoundsink->buffer_size % spec->info.bpf;
511
512     spec->segsize =
513         gst_util_uint64_scale_int (wfx.nAvgBytesPerSec, spec->latency_time,
514         GST_MSECOND);
515     spec->segsize -= spec->segsize % spec->info.bpf;
516     spec->segtotal = dsoundsink->buffer_size / spec->segsize;
517   } else {
518 #ifdef WAVE_FORMAT_DOLBY_AC3_SPDIF
519     wfx.cbSize = 0;
520     wfx.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
521     wfx.nChannels = 2;
522     wfx.nSamplesPerSec = 48000;
523     wfx.wBitsPerSample = 16;
524     wfx.nBlockAlign = wfx.wBitsPerSample / 8 * wfx.nChannels;
525     wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
526
527     spec->segsize = 6144;
528     spec->segtotal = 10;
529 #else
530     g_assert_not_reached ();
531 #endif
532   }
533
534   // Make the final buffer size be an integer number of segments
535   dsoundsink->buffer_size = spec->segsize * spec->segtotal;
536
537   GST_INFO_OBJECT (dsoundsink,
538       "GstAudioRingBufferSpec->channels: %d, GstAudioRingBufferSpec->rate: %d, GstAudioRingBufferSpec->bytes_per_sample: %d\n"
539       "WAVEFORMATEX.nSamplesPerSec: %ld, WAVEFORMATEX.wBitsPerSample: %d, WAVEFORMATEX.nBlockAlign: %d, WAVEFORMATEX.nAvgBytesPerSec: %ld\n"
540       "Size of dsound circular buffer=>%d\n", spec->info.channels,
541       spec->info.rate, spec->info.bpf, wfx.nSamplesPerSec, wfx.wBitsPerSample,
542       wfx.nBlockAlign, wfx.nAvgBytesPerSec, dsoundsink->buffer_size);
543
544   /* create a secondary directsound buffer */
545   memset (&descSecondary, 0, sizeof (DSBUFFERDESC));
546   descSecondary.dwSize = sizeof (DSBUFFERDESC);
547   descSecondary.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_GLOBALFOCUS;
548   if (!gst_directsound_sink_is_spdif_format (spec))
549     descSecondary.dwFlags |= DSBCAPS_CTRLVOLUME;
550
551   descSecondary.dwBufferBytes = dsoundsink->buffer_size;
552   descSecondary.lpwfxFormat = (WAVEFORMATEX *) & wfx;
553
554   hRes = IDirectSound_CreateSoundBuffer (dsoundsink->pDS, &descSecondary,
555       &dsoundsink->pDSBSecondary, NULL);
556   if (FAILED (hRes)) {
557     gchar *error_text = gst_hres_to_string (hRes);
558     GST_ELEMENT_ERROR (dsoundsink, RESOURCE, OPEN_READ,
559         ("gst_directsound_sink_prepare: IDirectSound_CreateSoundBuffer: %s",
560             error_text), (NULL));
561     g_free (error_text);
562     return FALSE;
563   }
564
565   gst_directsound_sink_set_volume (dsoundsink, dsoundsink->volume, FALSE);
566   gst_directsound_sink_set_mute (dsoundsink, dsoundsink->mute);
567
568   return TRUE;
569 }
570
571 static gboolean
572 gst_directsound_sink_unprepare (GstAudioSink * asink)
573 {
574   GstDirectSoundSink *dsoundsink;
575
576   dsoundsink = GST_DIRECTSOUND_SINK (asink);
577
578   /* release secondary DirectSound buffer */
579   if (dsoundsink->pDSBSecondary) {
580     IDirectSoundBuffer_Release (dsoundsink->pDSBSecondary);
581     dsoundsink->pDSBSecondary = NULL;
582   }
583
584   return TRUE;
585 }
586
587 static gboolean
588 gst_directsound_sink_close (GstAudioSink * asink)
589 {
590   GstDirectSoundSink *dsoundsink = NULL;
591
592   dsoundsink = GST_DIRECTSOUND_SINK (asink);
593
594   /* release DirectSound object */
595   g_return_val_if_fail (dsoundsink->pDS != NULL, FALSE);
596   IDirectSound_Release (dsoundsink->pDS);
597   dsoundsink->pDS = NULL;
598
599   gst_caps_replace (&dsoundsink->cached_caps, NULL);
600
601   return TRUE;
602 }
603
604 static gint
605 gst_directsound_sink_write (GstAudioSink * asink, gpointer data, guint length)
606 {
607   GstDirectSoundSink *dsoundsink;
608   DWORD dwStatus = 0;
609   HRESULT hRes, hRes2;
610   LPVOID pLockedBuffer1 = NULL, pLockedBuffer2 = NULL;
611   DWORD dwSizeBuffer1, dwSizeBuffer2;
612   DWORD dwCurrentPlayCursor;
613
614   dsoundsink = GST_DIRECTSOUND_SINK (asink);
615
616   GST_DSOUND_LOCK (dsoundsink);
617
618   /* get current buffer status */
619   hRes = IDirectSoundBuffer_GetStatus (dsoundsink->pDSBSecondary, &dwStatus);
620
621   /* get current play cursor position */
622   hRes2 = IDirectSoundBuffer_GetCurrentPosition (dsoundsink->pDSBSecondary,
623       &dwCurrentPlayCursor, NULL);
624
625   if (SUCCEEDED (hRes) && SUCCEEDED (hRes2) && (dwStatus & DSBSTATUS_PLAYING)) {
626     DWORD dwFreeBufferSize = 0;
627     DWORD sleepTime = 0;
628
629   calculate_freesize:
630     /* calculate the free size of the circular buffer */
631     if (dwCurrentPlayCursor < dsoundsink->current_circular_offset)
632       dwFreeBufferSize =
633           dsoundsink->buffer_size - (dsoundsink->current_circular_offset -
634           dwCurrentPlayCursor);
635     else
636       dwFreeBufferSize =
637           dwCurrentPlayCursor - dsoundsink->current_circular_offset;
638
639     if (length >= dwFreeBufferSize) {
640       sleepTime =
641           ((length -
642               dwFreeBufferSize) * 1000) / (dsoundsink->bytes_per_sample *
643           GST_AUDIO_BASE_SINK (asink)->ringbuffer->spec.info.rate);
644       if (sleepTime > 0) {
645         GST_DEBUG_OBJECT (dsoundsink,
646             "gst_directsound_sink_write: length:%i, FreeBufSiz: %ld, sleepTime: %ld, bps: %i, rate: %i",
647             length, dwFreeBufferSize, sleepTime, dsoundsink->bytes_per_sample,
648             GST_AUDIO_BASE_SINK (asink)->ringbuffer->spec.info.rate);
649         Sleep (sleepTime);
650       }
651       hRes = IDirectSoundBuffer_GetCurrentPosition (dsoundsink->pDSBSecondary,
652           &dwCurrentPlayCursor, NULL);
653
654       hRes2 =
655           IDirectSoundBuffer_GetStatus (dsoundsink->pDSBSecondary, &dwStatus);
656       if (SUCCEEDED (hRes) && SUCCEEDED (hRes2)
657           && (dwStatus & DSBSTATUS_PLAYING))
658         goto calculate_freesize;
659       else {
660         gchar *err1, *err2;
661
662         dsoundsink->first_buffer_after_reset = FALSE;
663         GST_DSOUND_UNLOCK (dsoundsink);
664
665         err1 = gst_hres_to_string (hRes);
666         err2 = gst_hres_to_string (hRes2);
667         GST_ELEMENT_ERROR (dsoundsink, RESOURCE, OPEN_WRITE,
668             ("gst_directsound_sink_write: IDirectSoundBuffer_GetStatus %s, "
669                 "IDirectSoundBuffer_GetCurrentPosition: %s, dwStatus: %lu",
670                 err2, err1, dwStatus), (NULL));
671         g_free (err1);
672         g_free (err2);
673         return -1;
674       }
675     }
676   }
677
678   if (dwStatus & DSBSTATUS_BUFFERLOST) {
679     hRes = IDirectSoundBuffer_Restore (dsoundsink->pDSBSecondary);      /*need a loop waiting the buffer is restored?? */
680
681     dsoundsink->current_circular_offset = 0;
682   }
683
684   hRes = IDirectSoundBuffer_Lock (dsoundsink->pDSBSecondary,
685       dsoundsink->current_circular_offset, length, &pLockedBuffer1,
686       &dwSizeBuffer1, &pLockedBuffer2, &dwSizeBuffer2, 0L);
687
688   if (SUCCEEDED (hRes)) {
689     // Write to pointers without reordering.
690     memcpy (pLockedBuffer1, data, dwSizeBuffer1);
691     if (pLockedBuffer2 != NULL)
692       memcpy (pLockedBuffer2, (LPBYTE) data + dwSizeBuffer1, dwSizeBuffer2);
693
694     // Update where the buffer will lock (for next time)
695     dsoundsink->current_circular_offset += dwSizeBuffer1 + dwSizeBuffer2;
696     dsoundsink->current_circular_offset %= dsoundsink->buffer_size;     /* Circular buffer */
697
698     hRes = IDirectSoundBuffer_Unlock (dsoundsink->pDSBSecondary, pLockedBuffer1,
699         dwSizeBuffer1, pLockedBuffer2, dwSizeBuffer2);
700   }
701
702   /* if the buffer was not in playing state yet, call play on the buffer 
703      except if this buffer is the fist after a reset (base class call reset and write a buffer when setting the sink to pause) */
704   if (!(dwStatus & DSBSTATUS_PLAYING) &&
705       dsoundsink->first_buffer_after_reset == FALSE) {
706     hRes = IDirectSoundBuffer_Play (dsoundsink->pDSBSecondary, 0, 0,
707         DSBPLAY_LOOPING);
708   }
709
710   dsoundsink->first_buffer_after_reset = FALSE;
711
712   GST_DSOUND_UNLOCK (dsoundsink);
713
714   return length;
715 }
716
717 static guint
718 gst_directsound_sink_delay (GstAudioSink * asink)
719 {
720   GstDirectSoundSink *dsoundsink;
721   HRESULT hRes;
722   DWORD dwCurrentPlayCursor;
723   DWORD dwBytesInQueue = 0;
724   gint nNbSamplesInQueue = 0;
725   DWORD dwStatus;
726
727   dsoundsink = GST_DIRECTSOUND_SINK (asink);
728
729   /* get current buffer status */
730   hRes = IDirectSoundBuffer_GetStatus (dsoundsink->pDSBSecondary, &dwStatus);
731
732   if (SUCCEEDED (hRes) && (dwStatus & DSBSTATUS_PLAYING)) {
733     /*evaluate the number of samples in queue in the circular buffer */
734     hRes = IDirectSoundBuffer_GetCurrentPosition (dsoundsink->pDSBSecondary,
735         &dwCurrentPlayCursor, NULL);
736
737     if (hRes == S_OK) {
738       if (dwCurrentPlayCursor < dsoundsink->current_circular_offset)
739         dwBytesInQueue =
740             dsoundsink->current_circular_offset - dwCurrentPlayCursor;
741       else
742         dwBytesInQueue =
743             dsoundsink->current_circular_offset + (dsoundsink->buffer_size -
744             dwCurrentPlayCursor);
745
746       nNbSamplesInQueue = dwBytesInQueue / dsoundsink->bytes_per_sample;
747     }
748   }
749
750   return nNbSamplesInQueue;
751 }
752
753 static void
754 gst_directsound_sink_reset (GstAudioSink * asink)
755 {
756   GstDirectSoundSink *dsoundsink;
757   LPVOID pLockedBuffer = NULL;
758   DWORD dwSizeBuffer = 0;
759
760   dsoundsink = GST_DIRECTSOUND_SINK (asink);
761
762   GST_DSOUND_LOCK (dsoundsink);
763
764   if (dsoundsink->pDSBSecondary) {
765     /*stop playing */
766     HRESULT hRes = IDirectSoundBuffer_Stop (dsoundsink->pDSBSecondary);
767
768     /*reset position */
769     hRes = IDirectSoundBuffer_SetCurrentPosition (dsoundsink->pDSBSecondary, 0);
770     dsoundsink->current_circular_offset = 0;
771
772     /*reset the buffer */
773     hRes = IDirectSoundBuffer_Lock (dsoundsink->pDSBSecondary,
774         dsoundsink->current_circular_offset, dsoundsink->buffer_size,
775         &pLockedBuffer, &dwSizeBuffer, NULL, NULL, 0L);
776
777     if (SUCCEEDED (hRes)) {
778       memset (pLockedBuffer, 0, dwSizeBuffer);
779
780       hRes =
781           IDirectSoundBuffer_Unlock (dsoundsink->pDSBSecondary, pLockedBuffer,
782           dwSizeBuffer, NULL, 0);
783     }
784   }
785
786   dsoundsink->first_buffer_after_reset = TRUE;
787
788   GST_DSOUND_UNLOCK (dsoundsink);
789 }
790
791 /*
792  * gst_directsound_probe_supported_formats:
793  *
794  * Takes the template caps and returns the subset which is actually
795  * supported by this device.
796  *
797  */
798
799 static GstCaps *
800 gst_directsound_probe_supported_formats (GstDirectSoundSink * dsoundsink,
801     const GstCaps * template_caps)
802 {
803   HRESULT hRes;
804   DSBUFFERDESC descSecondary;
805   WAVEFORMATEX wfx;
806   GstCaps *caps;
807   GstCaps *tmp, *tmp2;
808   LPDIRECTSOUNDBUFFER tmpBuffer;
809
810   caps = gst_caps_copy (template_caps);
811
812   /*
813    * Check availability of digital output by trying to create an SPDIF buffer
814    */
815
816 #ifdef WAVE_FORMAT_DOLBY_AC3_SPDIF
817   /* fill the WAVEFORMATEX structure with some standard AC3 over SPDIF params */
818   memset (&wfx, 0, sizeof (wfx));
819   wfx.cbSize = 0;
820   wfx.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
821   wfx.nChannels = 2;
822   wfx.nSamplesPerSec = 48000;
823   wfx.wBitsPerSample = 16;
824   wfx.nBlockAlign = 4;
825   wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
826
827   // create a secondary directsound buffer
828   memset (&descSecondary, 0, sizeof (DSBUFFERDESC));
829   descSecondary.dwSize = sizeof (DSBUFFERDESC);
830   descSecondary.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_GLOBALFOCUS;
831   descSecondary.dwBufferBytes = 6144;
832   descSecondary.lpwfxFormat = &wfx;
833
834   hRes = IDirectSound_CreateSoundBuffer (dsoundsink->pDS, &descSecondary,
835       &tmpBuffer, NULL);
836   if (FAILED (hRes)) {
837     gchar *error_text = gst_hres_to_string (hRes);
838     GST_INFO_OBJECT (dsoundsink, "AC3 passthrough not supported "
839         "(IDirectSound_CreateSoundBuffer returned: %s)\n", error_text);
840     g_free (error_text);
841     tmp = gst_caps_new_empty_simple ("audio/x-ac3");
842     tmp2 = gst_caps_subtract (caps, tmp);
843     gst_caps_unref (tmp);
844     gst_caps_unref (caps);
845     caps = tmp2;
846     tmp = gst_caps_new_empty_simple ("audio/x-dts");
847     tmp2 = gst_caps_subtract (caps, tmp);
848     gst_caps_unref (tmp);
849     gst_caps_unref (caps);
850     caps = tmp2;
851   } else {
852     GST_INFO_OBJECT (dsoundsink, "AC3 passthrough supported");
853     hRes = IDirectSoundBuffer_Release (tmpBuffer);
854     if (FAILED (hRes)) {
855       gchar *error_text = gst_hres_to_string (hRes);
856       GST_DEBUG_OBJECT (dsoundsink,
857           "(IDirectSoundBuffer_Release returned: %s)\n", error_text);
858       g_free (error_text);
859     }
860   }
861 #else
862   tmp = gst_caps_new_empty_simple ("audio/x-ac3");
863   tmp2 = gst_caps_subtract (caps, tmp);
864   gst_caps_unref (tmp);
865   gst_caps_unref (caps);
866   caps = tmp2;
867   tmp = gst_caps_new_empty_simple ("audio/x-dts");
868   tmp2 = gst_caps_subtract (caps, tmp);
869   gst_caps_unref (tmp);
870   gst_caps_unref (caps);
871   caps = tmp2;
872 #endif
873
874   return caps;
875 }
876
877 static GstBuffer *
878 gst_directsound_sink_payload (GstAudioBaseSink * sink, GstBuffer * buf)
879 {
880   if (gst_directsound_sink_is_spdif_format (&sink->ringbuffer->spec)) {
881     gint framesize = gst_audio_iec61937_frame_size (&sink->ringbuffer->spec);
882     GstBuffer *out;
883     GstMapInfo infobuf, infoout;
884     gboolean success;
885
886     if (framesize <= 0)
887       return NULL;
888
889     out = gst_buffer_new_and_alloc (framesize);
890
891     if (!gst_buffer_map (buf, &infobuf, GST_MAP_READWRITE)) {
892       gst_buffer_unref (out);
893       return NULL;
894     }
895     if (!gst_buffer_map (out, &infoout, GST_MAP_READWRITE)) {
896       gst_buffer_unmap (buf, &infobuf);
897       gst_buffer_unref (out);
898       return NULL;
899     }
900     success = gst_audio_iec61937_payload (infobuf.data, infobuf.size,
901         infoout.data, infoout.size, &sink->ringbuffer->spec, G_BYTE_ORDER);
902     if (!success) {
903       gst_buffer_unmap (out, &infoout);
904       gst_buffer_unmap (buf, &infobuf);
905       gst_buffer_unref (out);
906       return NULL;
907     }
908
909     gst_buffer_copy_into (out, buf, GST_BUFFER_COPY_ALL, 0, -1);
910     /* Fix endianness */
911     _swab ((gchar *) infoout.data, (gchar *) infoout.data, infobuf.size);
912     gst_buffer_unmap (out, &infoout);
913     gst_buffer_unmap (buf, &infobuf);
914     return out;
915   } else
916     return gst_buffer_ref (buf);
917 }
918
919 static void
920 gst_directsound_sink_set_volume (GstDirectSoundSink * dsoundsink,
921     gdouble dvolume, gboolean store)
922 {
923   glong volume;
924
925   volume = dvolume * 100;
926   if (store)
927     dsoundsink->volume = volume;
928
929   if (dsoundsink->pDSBSecondary) {
930     /* DirectSound controls volume using units of 100th of a decibel,
931      * ranging from -10000 to 0. We use a linear scale of 0 - 100
932      * here, so remap.
933      */
934     long dsVolume;
935     if (volume == 0 || dsoundsink->mute)
936       dsVolume = -10000;
937     else
938       dsVolume = 100 * (long) (20 * log10 ((double) volume / 100.));
939     dsVolume = CLAMP (dsVolume, -10000, 0);
940
941     GST_DEBUG_OBJECT (dsoundsink,
942         "Setting volume on secondary buffer to %d from %d", (int) dsVolume,
943         (int) volume);
944     IDirectSoundBuffer_SetVolume (dsoundsink->pDSBSecondary, dsVolume);
945   }
946 }
947
948 gdouble
949 gst_directsound_sink_get_volume (GstDirectSoundSink * dsoundsink)
950 {
951   return (gdouble) dsoundsink->volume / 100;
952 }
953
954 static void
955 gst_directsound_sink_set_mute (GstDirectSoundSink * dsoundsink, gboolean mute)
956 {
957   if (mute) {
958     gst_directsound_sink_set_volume (dsoundsink, 0, FALSE);
959     dsoundsink->mute = TRUE;
960   } else {
961     gst_directsound_sink_set_volume (dsoundsink,
962         gst_directsound_sink_get_volume (dsoundsink), FALSE);
963     dsoundsink->mute = FALSE;
964   }
965
966 }
967
968 static gboolean
969 gst_directsound_sink_get_mute (GstDirectSoundSink * dsoundsink)
970 {
971   return dsoundsink->mute;
972 }
973
974 static const gchar *
975 gst_directsound_sink_get_device (GstDirectSoundSink * dsoundsink)
976 {
977   return dsoundsink->device_id;
978 }
979
980 static void
981 gst_directsound_sink_set_device (GstDirectSoundSink * dsoundsink,
982     const gchar * device_id)
983 {
984   g_free (dsoundsink->device_id);
985   dsoundsink->device_id = g_strdup (device_id);
986 }
987
988 /* Converts a HRESULT error to a text string
989  * LPTSTR is either a */
990 static gchar *
991 gst_hres_to_string (HRESULT hRes)
992 {
993   DWORD flags;
994   gchar *ret_text;
995   LPTSTR error_text = NULL;
996
997   flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER
998       | FORMAT_MESSAGE_IGNORE_INSERTS;
999   FormatMessage (flags, NULL, hRes, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1000       (LPTSTR) & error_text, 0, NULL);
1001
1002 #ifdef UNICODE
1003   /* If UNICODE is defined, LPTSTR is LPWSTR which is UTF-16 */
1004   ret_text = g_utf16_to_utf8 (error_text, 0, NULL, NULL, NULL);
1005 #else
1006   ret_text = g_strdup (error_text);
1007 #endif
1008
1009   LocalFree (error_text);
1010   return ret_text;
1011 }