gstalsasink.c 26.7 KB
Newer Older
1
2
/* GStreamer
 * Copyright (C) 2005 Wim Taymans <wim@fluendo.com>
3
 * Copyright (C) 2006 Tim-Philipp Müller <tim centricular net>
4
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
5
 * gstalsasink.c:
6
7
8
9
10
11
12
13
 *
 * 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
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
16
17
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
18
19
20
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
21
22
 */

Wim Taymans's avatar
Wim Taymans committed
23
24
25
26
27
/**
 * SECTION:element-alsasink
 * @see_also: alsasrc, alsamixer
 *
 * This element renders raw audio samples using the ALSA api.
28
29
 *
 * <refsect2>
Wim Taymans's avatar
Wim Taymans committed
30
 * <title>Example pipelines</title>
31
 * |[
32
 * gst-launch -v filesrc location=sine.ogg ! oggdemux ! vorbisdec ! audioconvert ! audioresample ! alsasink
33
 * ]| Play an Ogg/Vorbis file.
Wim Taymans's avatar
Wim Taymans committed
34
35
36
37
38
 * </refsect2>
 *
 * Last reviewed on 2006-03-01 (0.10.4)
 */

39
40
41
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
42
43
44
45
46
47
#include <sys/ioctl.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <getopt.h>
48
#include <alsa/asoundlib.h>
49

50
#include "gstalsa.h"
51
#include "gstalsasink.h"
52
#include "gstalsadeviceprobe.h"
53

54
55
#include <gst/gst-i18n-plugin.h>

56
57
#define DEFAULT_DEVICE		"default"
#define DEFAULT_DEVICE_NAME	""
58
59
#define SPDIF_PERIOD_SIZE 1536
#define SPDIF_BUFFER_SIZE 15360
60

Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
61
62
63
64
enum
{
  PROP_0,
  PROP_DEVICE,
65
  PROP_DEVICE_NAME
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
66
67
};

68
69
70
71
72
static void gst_alsasink_init_interfaces (GType type);

GST_BOILERPLATE_FULL (GstAlsaSink, gst_alsasink, GstAudioSink,
    GST_TYPE_AUDIO_SINK, gst_alsasink_init_interfaces);

73
static void gst_alsasink_finalise (GObject * object);
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
74
75
76
77
static void gst_alsasink_set_property (GObject * object,
    guint prop_id, const GValue * value, GParamSpec * pspec);
static void gst_alsasink_get_property (GObject * object,
    guint prop_id, GValue * value, GParamSpec * pspec);
78

79
static GstCaps *gst_alsasink_getcaps (GstBaseSink * bsink);
80

81
82
static gboolean gst_alsasink_open (GstAudioSink * asink);
static gboolean gst_alsasink_prepare (GstAudioSink * asink,
83
    GstRingBufferSpec * spec);
84
static gboolean gst_alsasink_unprepare (GstAudioSink * asink);
85
86
87
88
89
static gboolean gst_alsasink_close (GstAudioSink * asink);
static guint gst_alsasink_write (GstAudioSink * asink, gpointer data,
    guint length);
static guint gst_alsasink_delay (GstAudioSink * asink);
static void gst_alsasink_reset (GstAudioSink * asink);
90

91
92
93
94
static gint output_ref;         /* 0    */
static snd_output_t *output;    /* NULL */
static GStaticMutex output_mutex = G_STATIC_MUTEX_INIT;

95

Jens Granseuer's avatar
Jens Granseuer committed
96
97
98
99
100
101
#if (G_BYTE_ORDER == G_LITTLE_ENDIAN)
# define ALSA_SINK_FACTORY_ENDIANNESS	"LITTLE_ENDIAN, BIG_ENDIAN"
#else
# define ALSA_SINK_FACTORY_ENDIANNESS	"BIG_ENDIAN, LITTLE_ENDIAN"
#endif

102
103
104
105
106
static GstStaticPadTemplate alsasink_sink_factory =
    GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("audio/x-raw-int, "
107
108
109
110
        "endianness = (int) { " ALSA_SINK_FACTORY_ENDIANNESS " }, "
        "signed = (boolean) { TRUE, FALSE }, "
        "width = (int) 32, "
        "depth = (int) 32, "
111
        "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, MAX ]; "
112
        "audio/x-raw-int, "
Jens Granseuer's avatar
Jens Granseuer committed
113
        "endianness = (int) { " ALSA_SINK_FACTORY_ENDIANNESS " }, "
114
        "signed = (boolean) { TRUE, FALSE }, "
115
116
117
118
119
120
121
122
123
124
125
126
        "width = (int) 24, "
        "depth = (int) 24, "
        "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, MAX ]; "
        "audio/x-raw-int, "
        "endianness = (int) { " ALSA_SINK_FACTORY_ENDIANNESS " }, "
        "signed = (boolean) { TRUE, FALSE }, "
        "width = (int) 32, "
        "depth = (int) 24, "
        "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, MAX ]; "
        "audio/x-raw-int, "
        "endianness = (int) { " ALSA_SINK_FACTORY_ENDIANNESS " }, "
        "signed = (boolean) { TRUE, FALSE }, "
127
128
        "width = (int) 16, "
        "depth = (int) 16, "
129
        "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, MAX ]; "
130
131
132
133
        "audio/x-raw-int, "
        "signed = (boolean) { TRUE, FALSE }, "
        "width = (int) 8, "
        "depth = (int) 8, "
134
135
        "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, MAX ];"
        "audio/x-iec958")
136
137
    );

138
139
140
141
142
143
static void
gst_alsasink_finalise (GObject * object)
{
  GstAlsaSink *sink = GST_ALSA_SINK (object);

  g_free (sink->device);
144
  g_mutex_free (sink->alsa_lock);
145

146
147
148
149
150
151
152
153
  g_static_mutex_lock (&output_mutex);
  --output_ref;
  if (output_ref == 0) {
    snd_output_close (output);
    output = NULL;
  }
  g_static_mutex_unlock (&output_mutex);

154
  G_OBJECT_CLASS (parent_class)->finalize (object);
155
156
}

157
158
159
160
161
162
static void
gst_alsasink_init_interfaces (GType type)
{
  gst_alsa_type_add_device_property_probe_interface (type);
}

163
static void
164
gst_alsasink_base_init (gpointer g_class)
165
166
{
  GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
167

168
169
170
  gst_element_class_set_details_simple (element_class,
      "Audio sink (ALSA)", "Sink/Audio",
      "Output to a sound card via ALSA", "Wim Taymans <wim@fluendo.com>");
171

172
173
  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&alsasink_sink_factory));
174
}
175

176
static void
177
gst_alsasink_class_init (GstAlsaSinkClass * klass)
178
{
179
180
181
182
183
184
185
  GObjectClass *gobject_class;
  GstBaseSinkClass *gstbasesink_class;
  GstAudioSinkClass *gstaudiosink_class;

  gobject_class = (GObjectClass *) klass;
  gstbasesink_class = (GstBaseSinkClass *) klass;
  gstaudiosink_class = (GstAudioSinkClass *) klass;
186

187
  parent_class = g_type_class_peek_parent (klass);
188

189
190
191
  gobject_class->finalize = gst_alsasink_finalise;
  gobject_class->get_property = gst_alsasink_get_property;
  gobject_class->set_property = gst_alsasink_set_property;
192

193
  gstbasesink_class->get_caps = GST_DEBUG_FUNCPTR (gst_alsasink_getcaps);
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
194

195
  gstaudiosink_class->open = GST_DEBUG_FUNCPTR (gst_alsasink_open);
196
197
  gstaudiosink_class->prepare = GST_DEBUG_FUNCPTR (gst_alsasink_prepare);
  gstaudiosink_class->unprepare = GST_DEBUG_FUNCPTR (gst_alsasink_unprepare);
198
199
200
201
  gstaudiosink_class->close = GST_DEBUG_FUNCPTR (gst_alsasink_close);
  gstaudiosink_class->write = GST_DEBUG_FUNCPTR (gst_alsasink_write);
  gstaudiosink_class->delay = GST_DEBUG_FUNCPTR (gst_alsasink_delay);
  gstaudiosink_class->reset = GST_DEBUG_FUNCPTR (gst_alsasink_reset);
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
202
203
204
205

  g_object_class_install_property (gobject_class, PROP_DEVICE,
      g_param_spec_string ("device", "Device",
          "ALSA device, as defined in an asound configuration file",
206
          DEFAULT_DEVICE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
207
208
209

  g_object_class_install_property (gobject_class, PROP_DEVICE_NAME,
      g_param_spec_string ("device-name", "Device name",
210
          "Human-readable name of the sound device", DEFAULT_DEVICE_NAME,
211
          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
212
213
214
215
216
217
218
219
220
221
222
223
}

static void
gst_alsasink_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
{
  GstAlsaSink *sink;

  sink = GST_ALSA_SINK (object);

  switch (prop_id) {
    case PROP_DEVICE:
224
225
226
227
228
229
      g_free (sink->device);
      sink->device = g_value_dup_string (value);
      /* setting NULL restores the default device */
      if (sink->device == NULL) {
        sink->device = g_strdup (DEFAULT_DEVICE);
      }
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_alsasink_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec)
{
  GstAlsaSink *sink;

  sink = GST_ALSA_SINK (object);

  switch (prop_id) {
    case PROP_DEVICE:
      g_value_set_string (value, sink->device);
      break;
249
    case PROP_DEVICE_NAME:
250
251
252
      g_value_take_string (value,
          gst_alsa_find_device_name (GST_OBJECT_CAST (sink),
              sink->device, sink->handle, SND_PCM_STREAM_PLAYBACK));
253
      break;
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
254
255
256
257
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
258
}
259

260
static void
261
gst_alsasink_init (GstAlsaSink * alsasink, GstAlsaSinkClass * g_class)
262
{
263
  GST_DEBUG_OBJECT (alsasink, "initializing alsasink");
264

265
  alsasink->device = g_strdup (DEFAULT_DEVICE);
266
  alsasink->handle = NULL;
267
  alsasink->cached_caps = NULL;
268
269
  alsasink->alsa_lock = g_mutex_new ();

270
271
272
273
274
275
  g_static_mutex_lock (&output_mutex);
  if (output_ref == 0) {
    snd_output_stdio_attach (&output, stdout, 0);
    ++output_ref;
  }
  g_static_mutex_unlock (&output_mutex);
276
277
}

278
#define CHECK(call, error) \
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
279
280
281
G_STMT_START {                  \
if ((err = call) < 0)           \
  goto error;                   \
282
283
} G_STMT_END;

284
285
286
287
288
289
static GstCaps *
gst_alsasink_getcaps (GstBaseSink * bsink)
{
  GstElementClass *element_class;
  GstPadTemplate *pad_template;
  GstAlsaSink *sink = GST_ALSA_SINK (bsink);
290
  GstCaps *caps;
291
292
293
294
295
296
297

  if (sink->handle == NULL) {
    GST_DEBUG_OBJECT (sink, "device not open, using template caps");
    return NULL;                /* base class will get template caps for us */
  }

  if (sink->cached_caps) {
298
    GST_LOG_OBJECT (sink, "Returning cached caps");
299
300
301
    return gst_caps_ref (sink->cached_caps);
  }

302
303
304
  element_class = GST_ELEMENT_GET_CLASS (sink);
  pad_template = gst_element_class_get_pad_template (element_class, "sink");
  g_return_val_if_fail (pad_template != NULL, NULL);
305

306
307
  caps = gst_alsa_probe_supported_formats (GST_OBJECT (sink), sink->handle,
      gst_pad_template_get_caps (pad_template));
308

309
310
  if (caps) {
    sink->cached_caps = gst_caps_ref (caps);
311
312
  }

313
  GST_INFO_OBJECT (sink, "returning caps %" GST_PTR_FORMAT, caps);
314
315
316
317

  return caps;
}

318
319
static int
set_hwparams (GstAlsaSink * alsa)
320
{
321
322
323
  guint rrate;
  gint err, dir;
  snd_pcm_hw_params_t *params;
324
  guint period_time, buffer_time;
325

326
  snd_pcm_hw_params_malloc (&params);
327

328
329
330
  GST_DEBUG_OBJECT (alsa, "Negotiating to %d channels @ %d Hz (format = %s) "
      "SPDIF (%d)", alsa->channels, alsa->rate,
      snd_pcm_format_name (alsa->format), alsa->iec958);
331

332
333
334
335
336
337
  /* start with requested values, if we cannot configure alsa for those values,
   * we set these values to -1, which will leave the default alsa values */
  buffer_time = alsa->buffer_time;
  period_time = alsa->period_time;

retry:
338
339
340
341
342
343
  /* choose all parameters */
  CHECK (snd_pcm_hw_params_any (alsa->handle, params), no_config);
  /* set the interleaved read/write format */
  CHECK (snd_pcm_hw_params_set_access (alsa->handle, params, alsa->access),
      wrong_access);
  /* set the sample format */
344
345
346
347
348
349
350
351
352
353
  if (alsa->iec958) {
    /* Try to use big endian first else fallback to le and swap bytes */
    if (snd_pcm_hw_params_set_format (alsa->handle, params, alsa->format) < 0) {
      alsa->format = SND_PCM_FORMAT_S16_LE;
      alsa->need_swap = TRUE;
      GST_DEBUG_OBJECT (alsa, "falling back to little endian with swapping");
    } else {
      alsa->need_swap = FALSE;
    }
  }
354
355
356
357
358
359
360
  CHECK (snd_pcm_hw_params_set_format (alsa->handle, params, alsa->format),
      no_sample_format);
  /* set the count of channels */
  CHECK (snd_pcm_hw_params_set_channels (alsa->handle, params, alsa->channels),
      no_channels);
  /* set the stream rate */
  rrate = alsa->rate;
361
  CHECK (snd_pcm_hw_params_set_rate_near (alsa->handle, params, &rrate, NULL),
362
363
364
365
      no_rate);
  if (rrate != alsa->rate)
    goto rate_match;

366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
  /* get and dump some limits */
  {
    guint min, max;

    snd_pcm_hw_params_get_buffer_time_min (params, &min, &dir);
    snd_pcm_hw_params_get_buffer_time_max (params, &max, &dir);

    GST_DEBUG_OBJECT (alsa, "buffer time %u, min %u, max %u",
        alsa->buffer_time, min, max);

    snd_pcm_hw_params_get_period_time_min (params, &min, &dir);
    snd_pcm_hw_params_get_period_time_max (params, &max, &dir);

    GST_DEBUG_OBJECT (alsa, "period time %u, min %u, max %u",
        alsa->period_time, min, max);

    snd_pcm_hw_params_get_periods_min (params, &min, &dir);
    snd_pcm_hw_params_get_periods_max (params, &max, &dir);

    GST_DEBUG_OBJECT (alsa, "periods min %u, max %u", min, max);
  }

  /* now try to configure the buffer time and period time, if one
   * of those fail, we fall back to the defaults and emit a warning. */
390
  if (buffer_time != -1 && !alsa->iec958) {
391
    /* set the buffer time */
392
393
394
395
396
397
398
399
400
    if ((err = snd_pcm_hw_params_set_buffer_time_near (alsa->handle, params,
                &buffer_time, &dir)) < 0) {
      GST_ELEMENT_WARNING (alsa, RESOURCE, SETTINGS, (NULL),
          ("Unable to set buffer time %i for playback: %s",
              buffer_time, snd_strerror (err)));
      /* disable buffer_time the next round */
      buffer_time = -1;
      goto retry;
    }
401
    GST_DEBUG_OBJECT (alsa, "buffer time %u", buffer_time);
402
  }
403
  if (period_time != -1 && !alsa->iec958) {
404
    /* set the period time */
405
406
407
408
409
410
411
412
413
    if ((err = snd_pcm_hw_params_set_period_time_near (alsa->handle, params,
                &period_time, &dir)) < 0) {
      GST_ELEMENT_WARNING (alsa, RESOURCE, SETTINGS, (NULL),
          ("Unable to set period time %i for playback: %s",
              period_time, snd_strerror (err)));
      /* disable period_time the next round */
      period_time = -1;
      goto retry;
    }
414
    GST_DEBUG_OBJECT (alsa, "period time %u", period_time);
415
  }
416

417
418
419
420
421
422
423
424
425
426
427
  /* Set buffer size and period size manually for SPDIF */
  if (G_UNLIKELY (alsa->iec958)) {
    snd_pcm_uframes_t buffer_size = SPDIF_BUFFER_SIZE;
    snd_pcm_uframes_t period_size = SPDIF_PERIOD_SIZE;

    CHECK (snd_pcm_hw_params_set_buffer_size_near (alsa->handle, params,
            &buffer_size), buffer_size);
    CHECK (snd_pcm_hw_params_set_period_size_near (alsa->handle, params,
            &period_size, NULL), period_size);
  }

428
429
430
  /* write the parameters to device */
  CHECK (snd_pcm_hw_params (alsa->handle, params), set_hw_params);

431
  /* now get the configured values */
432
433
434
435
436
  CHECK (snd_pcm_hw_params_get_buffer_size (params, &alsa->buffer_size),
      buffer_size);
  CHECK (snd_pcm_hw_params_get_period_size (params, &alsa->period_size, &dir),
      period_size);

Tim-Philipp Müller's avatar
Tim-Philipp Müller committed
437
  GST_DEBUG_OBJECT (alsa, "buffer size %lu, period size %lu", alsa->buffer_size,
438
439
      alsa->period_size);

440
  snd_pcm_hw_params_free (params);
441
442
443
444
445
  return 0;

  /* ERRORS */
no_config:
  {
446
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
447
        ("Broken configuration for playback: no configurations available: %s",
448
            snd_strerror (err)));
449
    snd_pcm_hw_params_free (params);
450
451
452
453
    return err;
  }
wrong_access:
  {
454
455
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Access type not available for playback: %s", snd_strerror (err)));
456
    snd_pcm_hw_params_free (params);
457
458
459
460
    return err;
  }
no_sample_format:
  {
461
462
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Sample format not available for playback: %s", snd_strerror (err)));
463
    snd_pcm_hw_params_free (params);
464
465
466
467
    return err;
  }
no_channels:
  {
468
469
470
471
472
473
474
475
476
477
478
479
480
    gchar *msg = NULL;

    if ((alsa->channels) == 1)
      msg = g_strdup (_("Could not open device for playback in mono mode."));
    if ((alsa->channels) == 2)
      msg = g_strdup (_("Could not open device for playback in stereo mode."));
    if ((alsa->channels) > 2)
      msg =
          g_strdup_printf (_
          ("Could not open device for playback in %d-channel mode."),
          alsa->channels);
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (msg), (snd_strerror (err)));
    g_free (msg);
481
    snd_pcm_hw_params_free (params);
482
483
484
485
    return err;
  }
no_rate:
  {
486
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
487
        ("Rate %iHz not available for playback: %s",
488
            alsa->rate, snd_strerror (err)));
489
490
491
492
    return err;
  }
rate_match:
  {
493
494
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Rate doesn't match (requested %iHz, get %iHz)", alsa->rate, err));
495
    snd_pcm_hw_params_free (params);
496
497
498
499
    return -EINVAL;
  }
buffer_size:
  {
500
501
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Unable to get buffer size for playback: %s", snd_strerror (err)));
502
    snd_pcm_hw_params_free (params);
503
504
505
506
    return err;
  }
period_size:
  {
507
508
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Unable to get period size for playback: %s", snd_strerror (err)));
509
    snd_pcm_hw_params_free (params);
510
511
512
513
    return err;
  }
set_hw_params:
  {
514
515
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Unable to set hw params for playback: %s", snd_strerror (err)));
516
    snd_pcm_hw_params_free (params);
517
518
519
520
521
522
523
524
525
526
    return err;
  }
}

static int
set_swparams (GstAlsaSink * alsa)
{
  int err;
  snd_pcm_sw_params_t *params;

527
  snd_pcm_sw_params_malloc (&params);
528
529
530
531
532
533
534
535
536
537
538
539

  /* get the current swparams */
  CHECK (snd_pcm_sw_params_current (alsa->handle, params), no_config);
  /* start the transfer when the buffer is almost full: */
  /* (buffer_size / avail_min) * avail_min */
  CHECK (snd_pcm_sw_params_set_start_threshold (alsa->handle, params,
          (alsa->buffer_size / alsa->period_size) * alsa->period_size),
      start_threshold);

  /* allow the transfer when at least period_size samples can be processed */
  CHECK (snd_pcm_sw_params_set_avail_min (alsa->handle, params,
          alsa->period_size), set_avail);
540
541
542
543

#if GST_CHECK_ALSA_VERSION(1,0,16)
  /* snd_pcm_sw_params_set_xfer_align() is deprecated, alignment is always 1 */
#else
544
545
  /* align all transfers to 1 sample */
  CHECK (snd_pcm_sw_params_set_xfer_align (alsa->handle, params, 1), set_align);
546
#endif
547
548
549
550

  /* write the parameters to the playback device */
  CHECK (snd_pcm_sw_params (alsa->handle, params), set_sw_params);

551
  snd_pcm_sw_params_free (params);
552
553
554
555
556
  return 0;

  /* ERRORS */
no_config:
  {
557
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
558
        ("Unable to determine current swparams for playback: %s",
559
            snd_strerror (err)));
560
    snd_pcm_sw_params_free (params);
561
562
563
564
    return err;
  }
start_threshold:
  {
565
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
566
        ("Unable to set start threshold mode for playback: %s",
567
            snd_strerror (err)));
568
    snd_pcm_sw_params_free (params);
569
570
571
572
    return err;
  }
set_avail:
  {
573
574
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Unable to set avail min for playback: %s", snd_strerror (err)));
575
    snd_pcm_sw_params_free (params);
576
577
    return err;
  }
578
#if !GST_CHECK_ALSA_VERSION(1,0,16)
579
580
set_align:
  {
581
582
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Unable to set transfer align for playback: %s", snd_strerror (err)));
583
    snd_pcm_sw_params_free (params);
584
585
    return err;
  }
586
#endif
587
588
set_sw_params:
  {
589
590
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Unable to set sw params for playback: %s", snd_strerror (err)));
591
    snd_pcm_sw_params_free (params);
592
    return err;
593
594
  }
}
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
595

596
static gboolean
597
alsasink_parse_spec (GstAlsaSink * alsa, GstRingBufferSpec * spec)
598
{
599
600
601
  /* Initialize our boolean */
  alsa->iec958 = FALSE;

602
603
  switch (spec->type) {
    case GST_BUFTYPE_LINEAR:
604
605
606
607
      GST_DEBUG_OBJECT (alsa,
          "Linear format : depth=%d, width=%d, sign=%d, bigend=%d", spec->depth,
          spec->width, spec->sign, spec->bigend);

608
609
610
611
612
613
614
      alsa->format = snd_pcm_build_linear_format (spec->depth, spec->width,
          spec->sign ? 0 : 1, spec->bigend ? 1 : 0);
      break;
    case GST_BUFTYPE_FLOAT:
      switch (spec->format) {
        case GST_FLOAT32_LE:
          alsa->format = SND_PCM_FORMAT_FLOAT_LE;
615
          break;
616
617
618
619
620
621
622
623
624
625
626
        case GST_FLOAT32_BE:
          alsa->format = SND_PCM_FORMAT_FLOAT_BE;
          break;
        case GST_FLOAT64_LE:
          alsa->format = SND_PCM_FORMAT_FLOAT64_LE;
          break;
        case GST_FLOAT64_BE:
          alsa->format = SND_PCM_FORMAT_FLOAT64_BE;
          break;
        default:
          goto error;
627
      }
628
629
630
631
632
633
634
      break;
    case GST_BUFTYPE_A_LAW:
      alsa->format = SND_PCM_FORMAT_A_LAW;
      break;
    case GST_BUFTYPE_MU_LAW:
      alsa->format = SND_PCM_FORMAT_MU_LAW;
      break;
635
    case GST_BUFTYPE_IEC958:
636
      alsa->format = SND_PCM_FORMAT_S16_BE;
637
      alsa->iec958 = TRUE;
638
      break;
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
    default:
      goto error;

  }
  alsa->rate = spec->rate;
  alsa->channels = spec->channels;
  alsa->buffer_time = spec->buffer_time;
  alsa->period_time = spec->latency_time;
  alsa->access = SND_PCM_ACCESS_RW_INTERLEAVED;

  return TRUE;

  /* ERRORS */
error:
  {
    return FALSE;
655
656
  }
}
657
658

static gboolean
659
gst_alsasink_open (GstAudioSink * asink)
660
{
661
662
  GstAlsaSink *alsa;
  gint err;
663

664
  alsa = GST_ALSA_SINK (asink);
665

666
667
  /* open in non-blocking mode, we'll use snd_pcm_wait() for space to become
   * available. */
668
669
  CHECK (snd_pcm_open (&alsa->handle, alsa->device, SND_PCM_STREAM_PLAYBACK,
          SND_PCM_NONBLOCK), open_error);
670
  GST_LOG_OBJECT (alsa, "Opened device %s", alsa->device);
671

672
673
674
675
676
  return TRUE;

  /* ERRORS */
open_error:
  {
677
    if (err == -EBUSY) {
678
679
680
681
      GST_ELEMENT_ERROR (alsa, RESOURCE, BUSY,
          (_("Could not open audio device for playback. "
                  "Device is being used by another application.")),
          ("Device '%s' is busy", alsa->device));
682
683
    } else {
      GST_ELEMENT_ERROR (alsa, RESOURCE, OPEN_WRITE,
684
685
          (_("Could not open audio device for playback.")),
          ("Playback open error on device '%s': %s", alsa->device,
686
              snd_strerror (err)));
687
    }
688
689
690
691
692
693
694
695
696
697
698
699
    return FALSE;
  }
}

static gboolean
gst_alsasink_prepare (GstAudioSink * asink, GstRingBufferSpec * spec)
{
  GstAlsaSink *alsa;
  gint err;

  alsa = GST_ALSA_SINK (asink);

700
701
702
703
704
705
706
707
  if (spec->format == GST_IEC958) {
    snd_pcm_close (alsa->handle);
    alsa->handle = gst_alsa_open_iec958_pcm (GST_OBJECT (alsa));
    if (G_UNLIKELY (!alsa->handle)) {
      goto no_iec958;
    }
  }

708
709
710
  if (!alsasink_parse_spec (alsa, spec))
    goto spec_parse;

711
712
713
  CHECK (set_hwparams (alsa), hw_params_failed);
  CHECK (set_swparams (alsa), sw_params_failed);

714
715
  alsa->bytes_per_sample = spec->bytes_per_sample;
  spec->segsize = alsa->period_size * spec->bytes_per_sample;
716
717
  spec->segtotal = alsa->buffer_size / alsa->period_size;

718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
  {
    snd_output_t *out_buf = NULL;
    char *msg = NULL;

    snd_output_buffer_open (&out_buf);
    snd_pcm_dump_hw_setup (alsa->handle, out_buf);
    snd_output_buffer_string (out_buf, &msg);
    GST_DEBUG_OBJECT (alsa, "Hardware setup: \n%s", msg);
    snd_output_close (out_buf);
    snd_output_buffer_open (&out_buf);
    snd_pcm_dump_sw_setup (alsa->handle, out_buf);
    snd_output_buffer_string (out_buf, &msg);
    GST_DEBUG_OBJECT (alsa, "Software setup: \n%s", msg);
    snd_output_close (out_buf);
  }

734
735
736
  return TRUE;

  /* ERRORS */
737
738
739
740
741
742
no_iec958:
  {
    GST_ELEMENT_ERROR (alsa, RESOURCE, OPEN_WRITE, (NULL),
        ("Could not open IEC958 (SPDIF) device for playback"));
    return FALSE;
  }
743
744
spec_parse:
  {
745
746
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Error parsing spec"));
747
    return FALSE;
748
  }
749
750
hw_params_failed:
  {
751
752
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Setting of hwparams failed: %s", snd_strerror (err)));
753
754
755
756
    return FALSE;
  }
sw_params_failed:
  {
757
758
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Setting of swparams failed: %s", snd_strerror (err)));
759
    return FALSE;
760
  }
761
}
762

763
static gboolean
764
gst_alsasink_unprepare (GstAudioSink * asink)
765
766
767
768
769
{
  GstAlsaSink *alsa;

  alsa = GST_ALSA_SINK (asink);

770
771
  snd_pcm_drop (alsa->handle);
  snd_pcm_hw_free (alsa->handle);
772
773
774
775
776
777
778
779
780

  return TRUE;
}

static gboolean
gst_alsasink_close (GstAudioSink * asink)
{
  GstAlsaSink *alsa = GST_ALSA_SINK (asink);

781
  if (alsa->handle) {
782
    snd_pcm_close (alsa->handle);
783
784
    alsa->handle = NULL;
  }
785
  gst_caps_replace (&alsa->cached_caps, NULL);
786
787

  return TRUE;
788
}
789
790
791
792
793
794


/*
 *   Underrun and suspend recovery
 */
static gint
795
xrun_recovery (GstAlsaSink * alsa, snd_pcm_t * handle, gint err)
796
{
797
  GST_DEBUG_OBJECT (alsa, "xrun recovery %d", err);
798
799
800
801

  if (err == -EPIPE) {          /* under-run */
    err = snd_pcm_prepare (handle);
    if (err < 0)
802
803
      GST_WARNING_OBJECT (alsa,
          "Can't recovery from underrun, prepare failed: %s",
804
805
806
807
808
809
810
811
812
          snd_strerror (err));
    return 0;
  } else if (err == -ESTRPIPE) {
    while ((err = snd_pcm_resume (handle)) == -EAGAIN)
      g_usleep (100);           /* wait until the suspend flag is released */

    if (err < 0) {
      err = snd_pcm_prepare (handle);
      if (err < 0)
813
814
        GST_WARNING_OBJECT (alsa,
            "Can't recovery from suspend, prepare failed: %s",
815
            snd_strerror (err));
816
    }
817
    return 0;
818
819
820
821
  }
  return err;
}

822
823
824
825
826
827
static guint
gst_alsasink_write (GstAudioSink * asink, gpointer data, guint length)
{
  GstAlsaSink *alsa;
  gint err;
  gint cptr;
828
  gint16 *ptr = data;
829

830
  alsa = GST_ALSA_SINK (asink);
831

832
833
834
835
  if (alsa->iec958 && alsa->need_swap) {
    guint i;

    GST_DEBUG_OBJECT (asink, "swapping bytes");
836
837
    for (i = 0; i < length / 2; i++) {
      ptr[i] = GUINT16_SWAP_LE_BE (ptr[i]);
838
839
840
841
842
    }
  }

  GST_LOG_OBJECT (asink, "received audio samples buffer of %u bytes", length);

843
  cptr = length / alsa->bytes_per_sample;
844

845
  GST_ALSA_SINK_LOCK (asink);
846
  while (cptr > 0) {
847
848
849
850
    /* start by doing a blocking wait for free space. Set the timeout
     * to 4 times the period time */
    err = snd_pcm_wait (alsa->handle, (4 * alsa->period_time / 1000));
    if (err < 0) {
Wim Taymans's avatar
Wim Taymans committed
851
      GST_DEBUG_OBJECT (asink, "wait error, %d", err);
852
    } else {
853
854
      err = snd_pcm_writei (alsa->handle, ptr, cptr);
    }
855

856
    GST_DEBUG_OBJECT (asink, "written %d frames out of %d", err, cptr);
857
    if (err < 0) {
858
      GST_DEBUG_OBJECT (asink, "Write error: %s", snd_strerror (err));
859
      if (err == -EAGAIN) {
860
        continue;
861
      } else if (xrun_recovery (alsa, alsa->handle, err) < 0) {
862
        goto write_error;
863
      }
864
      continue;
865
866
    }

867
    ptr += snd_pcm_frames_to_bytes (alsa->handle, err);
868
    cptr -= err;
869
  }
870
  GST_ALSA_SINK_UNLOCK (asink);
871

872
  return length - (cptr * alsa->bytes_per_sample);
873
874
875

write_error:
  {
876
    GST_ALSA_SINK_UNLOCK (asink);
877
878
    return length;              /* skip one period */
  }
879
880
}

881
882
static guint
gst_alsasink_delay (GstAudioSink * asink)
883
{
884
885
  GstAlsaSink *alsa;
  snd_pcm_sframes_t delay;
886
  int res;
887

888
  alsa = GST_ALSA_SINK (asink);
889

890
891
  res = snd_pcm_delay (alsa->handle, &delay);
  if (G_UNLIKELY (res < 0)) {
892
    /* on errors, report 0 delay */
893
894
895
    GST_DEBUG_OBJECT (alsa, "snd_pcm_delay returned %d", res);
    delay = 0;
  }
896
897
898
899
900
  if (G_UNLIKELY (delay < 0)) {
    /* make sure we never return a negative delay */
    GST_WARNING_OBJECT (alsa, "snd_pcm_delay returned negative delay");
    delay = 0;
  }
901

902
  return delay;
903
904
}

905
906
static void
gst_alsasink_reset (GstAudioSink * asink)
907
{
908
909
910
911
912
  GstAlsaSink *alsa;
  gint err;

  alsa = GST_ALSA_SINK (asink);

913
  GST_ALSA_SINK_LOCK (asink);
914
  GST_DEBUG_OBJECT (alsa, "drop");
915
  CHECK (snd_pcm_drop (alsa->handle), drop_error);
916
  GST_DEBUG_OBJECT (alsa, "prepare");
917
  CHECK (snd_pcm_prepare (alsa->handle), prepare_error);
918
  GST_DEBUG_OBJECT (alsa, "reset done");
919
  GST_ALSA_SINK_UNLOCK (asink);
920
921
922
923
924
925

  return;

  /* ERRORS */
drop_error:
  {
926
927
    GST_ERROR_OBJECT (alsa, "alsa-reset: pcm drop error: %s",
        snd_strerror (err));
928
    GST_ALSA_SINK_UNLOCK (asink);
929
    return;
930
  }
931
932
prepare_error:
  {
933
934
    GST_ERROR_OBJECT (alsa, "alsa-reset: pcm prepare error: %s",
        snd_strerror (err));
935
    GST_ALSA_SINK_UNLOCK (asink);
936
    return;
937
938
  }
}