gstalsasink.c 36 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
 * License along with this library; if not, write to the
Tim-Philipp Müller's avatar
Tim-Philipp Müller committed
19 20
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
21 22
 */

Wim Taymans's avatar
Wim Taymans committed
23 24
/**
 * SECTION:element-alsasink
25
 * @title: alsasink
26
 * @see_also: alsasrc
Wim Taymans's avatar
Wim Taymans committed
27
 *
Arun Raghavan's avatar
Arun Raghavan committed
28
 * This element renders audio samples using the ALSA audio API.
29
 *
30
 * ## Example pipelines
31
 * |[
32
 * gst-launch-1.0 -v uridecodebin uri=file:///path/to/audio.ogg ! audioconvert ! audioresample ! autoaudiosink
33 34 35 36
 * ]|
 *
 * Play an Ogg/Vorbis file and output audio via ALSA.
 *
Wim Taymans's avatar
Wim Taymans committed
37 38
 */

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 52
#include "gstalsasink.h"

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

56 57 58 59
#ifndef ESTRPIPE
#define ESTRPIPE EPIPE
#endif

60 61
#define DEFAULT_DEVICE		"default"
#define DEFAULT_DEVICE_NAME	""
62
#define DEFAULT_CARD_NAME	""
63 64
#define SPDIF_PERIOD_SIZE 1536
#define SPDIF_BUFFER_SIZE 15360
65

Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
66 67 68 69
enum
{
  PROP_0,
  PROP_DEVICE,
70 71 72
  PROP_DEVICE_NAME,
  PROP_CARD_NAME,
  PROP_LAST
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
73 74
};

75
static void gst_alsasink_init_interfaces (GType type);
76 77 78
#define gst_alsasink_parent_class parent_class
G_DEFINE_TYPE_WITH_CODE (GstAlsaSink, gst_alsasink,
    GST_TYPE_AUDIO_SINK, gst_alsasink_init_interfaces (g_define_type_id));
79

80
static void gst_alsasink_finalise (GObject * object);
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
81 82 83 84
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);
85

86
static GstCaps *gst_alsasink_getcaps (GstBaseSink * bsink, GstCaps * filter);
87
static gboolean gst_alsasink_query (GstBaseSink * bsink, GstQuery * query);
88

89 90
static gboolean gst_alsasink_open (GstAudioSink * asink);
static gboolean gst_alsasink_prepare (GstAudioSink * asink,
91
    GstAudioRingBufferSpec * spec);
92
static gboolean gst_alsasink_unprepare (GstAudioSink * asink);
93
static gboolean gst_alsasink_close (GstAudioSink * asink);
94
static gint gst_alsasink_write (GstAudioSink * asink, gpointer data,
95 96
    guint length);
static guint gst_alsasink_delay (GstAudioSink * asink);
Axel Mårtensson's avatar
Axel Mårtensson committed
97 98 99
static void gst_alsasink_pause (GstAudioSink * asink);
static void gst_alsasink_resume (GstAudioSink * asink);
static void gst_alsasink_stop (GstAudioSink * asink);
100 101 102
static gboolean gst_alsasink_acceptcaps (GstAlsaSink * alsa, GstCaps * caps);
static GstBuffer *gst_alsasink_payload (GstAudioBaseSink * sink,
    GstBuffer * buf);
103

104 105
static gint output_ref;         /* 0    */
static snd_output_t *output;    /* NULL */
106
static GMutex output_mutex;
107

108 109 110 111
static GstStaticPadTemplate alsasink_sink_factory =
    GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
Wim Taymans's avatar
Wim Taymans committed
112
    GST_STATIC_CAPS ("audio/x-raw, "
113
        "format = (string) " GST_AUDIO_FORMATS_ALL ", "
114
        "layout = (string) interleaved, "
115
        "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, MAX ]; "
116
        PASSTHROUGH_CAPS)
117 118
    );

119 120 121 122 123 124
static void
gst_alsasink_finalise (GObject * object)
{
  GstAlsaSink *sink = GST_ALSA_SINK (object);

  g_free (sink->device);
125
  g_mutex_clear (&sink->alsa_lock);
yanghuolin's avatar
yanghuolin committed
126
  g_mutex_clear (&sink->delay_lock);
127

128
  g_mutex_lock (&output_mutex);
129 130 131 132 133
  --output_ref;
  if (output_ref == 0) {
    snd_output_close (output);
    output = NULL;
  }
134
  g_mutex_unlock (&output_mutex);
135

136
  G_OBJECT_CLASS (parent_class)->finalize (object);
137 138
}

139 140 141
static void
gst_alsasink_init_interfaces (GType type)
{
142
#if 0
143
  gst_alsa_type_add_device_property_probe_interface (type);
144
#endif
145 146
}

147
static void
148
gst_alsasink_class_init (GstAlsaSinkClass * klass)
149
{
150
  GObjectClass *gobject_class;
151
  GstElementClass *gstelement_class;
152
  GstBaseSinkClass *gstbasesink_class;
153
  GstAudioBaseSinkClass *gstbaseaudiosink_class;
154 155 156
  GstAudioSinkClass *gstaudiosink_class;

  gobject_class = (GObjectClass *) klass;
157
  gstelement_class = (GstElementClass *) klass;
158
  gstbasesink_class = (GstBaseSinkClass *) klass;
159
  gstbaseaudiosink_class = (GstAudioBaseSinkClass *) klass;
160
  gstaudiosink_class = (GstAudioSinkClass *) klass;
161

162
  parent_class = g_type_class_peek_parent (klass);
163

164 165 166
  gobject_class->finalize = gst_alsasink_finalise;
  gobject_class->get_property = gst_alsasink_get_property;
  gobject_class->set_property = gst_alsasink_set_property;
167

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

172 173
  gst_element_class_add_static_pad_template (gstelement_class,
      &alsasink_sink_factory);
174

175
  gstbasesink_class->get_caps = GST_DEBUG_FUNCPTR (gst_alsasink_getcaps);
176 177 178
  gstbasesink_class->query = GST_DEBUG_FUNCPTR (gst_alsasink_query);

  gstbaseaudiosink_class->payload = GST_DEBUG_FUNCPTR (gst_alsasink_payload);
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
179

180
  gstaudiosink_class->open = GST_DEBUG_FUNCPTR (gst_alsasink_open);
181 182
  gstaudiosink_class->prepare = GST_DEBUG_FUNCPTR (gst_alsasink_prepare);
  gstaudiosink_class->unprepare = GST_DEBUG_FUNCPTR (gst_alsasink_unprepare);
183 184 185
  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);
Axel Mårtensson's avatar
Axel Mårtensson committed
186 187 188
  gstaudiosink_class->stop = GST_DEBUG_FUNCPTR (gst_alsasink_stop);
  gstaudiosink_class->pause = GST_DEBUG_FUNCPTR (gst_alsasink_pause);
  gstaudiosink_class->resume = GST_DEBUG_FUNCPTR (gst_alsasink_resume);
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
189 190 191 192

  g_object_class_install_property (gobject_class, PROP_DEVICE,
      g_param_spec_string ("device", "Device",
          "ALSA device, as defined in an asound configuration file",
193
          DEFAULT_DEVICE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
194 195 196

  g_object_class_install_property (gobject_class, PROP_DEVICE_NAME,
      g_param_spec_string ("device-name", "Device name",
197
          "Human-readable name of the sound device", DEFAULT_DEVICE_NAME,
198
          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
199 200 201 202

  g_object_class_install_property (gobject_class, PROP_CARD_NAME,
      g_param_spec_string ("card-name", "Card name",
          "Human-readable name of the sound card", DEFAULT_CARD_NAME,
203 204
          G_PARAM_READABLE | G_PARAM_STATIC_STRINGS |
          GST_PARAM_DOC_SHOW_DEFAULT));
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
205 206 207 208 209 210 211 212 213 214 215 216
}

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:
217 218 219 220 221 222
      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
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
      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;
242
    case PROP_DEVICE_NAME:
243 244 245
      g_value_take_string (value,
          gst_alsa_find_device_name (GST_OBJECT_CAST (sink),
              sink->device, sink->handle, SND_PCM_STREAM_PLAYBACK));
246
      break;
247 248 249 250 251
    case PROP_CARD_NAME:
      g_value_take_string (value,
          gst_alsa_find_card_name (GST_OBJECT_CAST (sink),
              sink->device, SND_PCM_STREAM_PLAYBACK));
      break;
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
252 253 254 255
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
256
}
257

258
static void
259
gst_alsasink_init (GstAlsaSink * alsasink)
260
{
261
  GST_DEBUG_OBJECT (alsasink, "initializing alsasink");
262

263
  alsasink->device = g_strdup (DEFAULT_DEVICE);
264
  alsasink->handle = NULL;
265
  alsasink->cached_caps = NULL;
Axel Mårtensson's avatar
Axel Mårtensson committed
266 267 268
  alsasink->is_paused = FALSE;
  alsasink->after_paused = FALSE;
  alsasink->hw_support_pause = FALSE;
269
  g_mutex_init (&alsasink->alsa_lock);
yanghuolin's avatar
yanghuolin committed
270
  g_mutex_init (&alsasink->delay_lock);
271

272
  g_mutex_lock (&output_mutex);
273 274 275 276
  if (output_ref == 0) {
    snd_output_stdio_attach (&output, stdout, 0);
    ++output_ref;
  }
277
  g_mutex_unlock (&output_mutex);
278 279
}

280
#define CHECK(call, error) \
281 282 283 284 285
G_STMT_START {             \
  if ((err = call) < 0) {  \
    GST_WARNING_OBJECT (alsa, "Error %d (%s) calling " #call, err, snd_strerror (err)); \
    goto error;            \
  }                        \
286 287
} G_STMT_END;

288
static GstCaps *
289
gst_alsasink_getcaps (GstBaseSink * bsink, GstCaps * filter)
290 291 292 293
{
  GstElementClass *element_class;
  GstPadTemplate *pad_template;
  GstAlsaSink *sink = GST_ALSA_SINK (bsink);
294
  GstCaps *caps, *templ_caps;
295

296
  GST_OBJECT_LOCK (sink);
297
  if (sink->handle == NULL) {
298
    GST_OBJECT_UNLOCK (sink);
299 300 301 302 303
    GST_DEBUG_OBJECT (sink, "device not open, using template caps");
    return NULL;                /* base class will get template caps for us */
  }

  if (sink->cached_caps) {
304 305
    if (filter) {
      caps = gst_caps_intersect_full (filter, sink->cached_caps,
306
          GST_CAPS_INTERSECT_FIRST);
307
      GST_OBJECT_UNLOCK (sink);
308 309 310 311 312
      GST_LOG_OBJECT (sink, "Returning cached caps %" GST_PTR_FORMAT " with "
          "filter %" GST_PTR_FORMAT " applied: %" GST_PTR_FORMAT,
          sink->cached_caps, filter, caps);
      return caps;
    } else {
313 314 315 316
      caps = gst_caps_ref (sink->cached_caps);
      GST_OBJECT_UNLOCK (sink);
      GST_LOG_OBJECT (sink, "Returning cached caps %" GST_PTR_FORMAT, caps);
      return caps;
317
    }
318 319
  }

320 321
  element_class = GST_ELEMENT_GET_CLASS (sink);
  pad_template = gst_element_class_get_pad_template (element_class, "sink");
322 323 324 325 326
  if (pad_template == NULL) {
    GST_OBJECT_UNLOCK (sink);
    g_assert_not_reached ();
    return NULL;
  }
327

328
  templ_caps = gst_pad_template_get_caps (pad_template);
329 330
  caps = gst_alsa_probe_supported_formats (GST_OBJECT (sink), sink->device,
      sink->handle, templ_caps);
331
  gst_caps_unref (templ_caps);
332

333 334
  if (caps) {
    sink->cached_caps = gst_caps_ref (caps);
335 336
  }

337 338
  GST_OBJECT_UNLOCK (sink);

339
  GST_INFO_OBJECT (sink, "returning caps %" GST_PTR_FORMAT, caps);
340

341 342 343 344 345 346 347 348 349 350
  if (filter) {
    GstCaps *intersection;

    intersection =
        gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
    gst_caps_unref (caps);
    return intersection;
  } else {
    return caps;
  }
351 352
}

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
static gboolean
gst_alsasink_acceptcaps (GstAlsaSink * alsa, GstCaps * caps)
{
  GstPad *pad = GST_BASE_SINK (alsa)->sinkpad;
  GstCaps *pad_caps;
  GstStructure *st;
  gboolean ret = FALSE;
  GstAudioRingBufferSpec spec = { 0 };

  pad_caps = gst_pad_query_caps (pad, caps);
  if (!pad_caps || gst_caps_is_empty (pad_caps)) {
    if (pad_caps)
      gst_caps_unref (pad_caps);
    ret = FALSE;
    goto done;
  }
  gst_caps_unref (pad_caps);

  /* If we've not got fixed caps, creating a stream might fail, so let's just
   * return from here with default acceptcaps behaviour */
  if (!gst_caps_is_fixed (caps))
    goto done;

376 377 378 379
  /* parse helper expects this set, so avoid nasty warning
   * will be set properly later on anyway  */
  spec.latency_time = GST_SECOND;
  if (!gst_audio_ring_buffer_parse_caps (&spec, caps))
380 381 382
    goto done;

  /* Make sure input is framed (one frame per buffer) and can be payloaded */
383
  switch (spec.type) {
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_AC3:
    case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_EAC3:
    case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_DTS:
    case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_MPEG:
    {
      gboolean framed = FALSE, parsed = FALSE;
      st = gst_caps_get_structure (caps, 0);

      gst_structure_get_boolean (st, "framed", &framed);
      gst_structure_get_boolean (st, "parsed", &parsed);
      if ((!framed && !parsed) || gst_audio_iec61937_frame_size (&spec) <= 0)
        goto done;
    }
    default:{
    }
  }
  ret = TRUE;

done:
403
  gst_caps_replace (&spec.caps, NULL);
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
  return ret;
}

static gboolean
gst_alsasink_query (GstBaseSink * sink, GstQuery * query)
{
  GstAlsaSink *alsa = GST_ALSA_SINK (sink);
  gboolean ret;

  switch (GST_QUERY_TYPE (query)) {
    case GST_QUERY_ACCEPT_CAPS:
    {
      GstCaps *caps;

      gst_query_parse_accept_caps (query, &caps);
      ret = gst_alsasink_acceptcaps (alsa, caps);
      gst_query_set_accept_caps_result (query, ret);
      ret = TRUE;
      break;
    }
    default:
      ret = GST_BASE_SINK_CLASS (parent_class)->query (sink, query);
      break;
  }
  return ret;
}

431 432
static int
set_hwparams (GstAlsaSink * alsa)
433
{
434
  guint rrate;
Stefan Kost's avatar
Stefan Kost committed
435
  gint err;
436
  snd_pcm_hw_params_t *params;
437
  guint period_time, buffer_time;
438

439
  snd_pcm_hw_params_malloc (&params);
440

441 442 443
  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);
444

445 446 447 448 449 450
  /* 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:
451 452 453 454 455 456
  /* 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 */
457 458 459 460 461 462 463 464 465 466
  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;
    }
  }
467 468 469 470 471 472 473
  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;
474
  CHECK (snd_pcm_hw_params_set_rate_near (alsa->handle, params, &rrate, NULL),
475 476
      no_rate);

Stefan Kost's avatar
Stefan Kost committed
477
#ifndef GST_DISABLE_GST_DEBUG
478 479 480 481
  /* get and dump some limits */
  {
    guint min, max;

Stefan Kost's avatar
Stefan Kost committed
482 483
    snd_pcm_hw_params_get_buffer_time_min (params, &min, NULL);
    snd_pcm_hw_params_get_buffer_time_max (params, &max, NULL);
484 485 486 487

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

Stefan Kost's avatar
Stefan Kost committed
488 489
    snd_pcm_hw_params_get_period_time_min (params, &min, NULL);
    snd_pcm_hw_params_get_period_time_max (params, &max, NULL);
490 491 492 493

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

Stefan Kost's avatar
Stefan Kost committed
494 495
    snd_pcm_hw_params_get_periods_min (params, &min, NULL);
    snd_pcm_hw_params_get_periods_max (params, &max, NULL);
496 497 498

    GST_DEBUG_OBJECT (alsa, "periods min %u, max %u", min, max);
  }
Stefan Kost's avatar
Stefan Kost committed
499
#endif
500 501 502

  /* 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. */
503
  if (buffer_time != -1 && !alsa->iec958) {
504
    /* set the buffer time */
505
    if ((err = snd_pcm_hw_params_set_buffer_time_near (alsa->handle, params,
Stefan Kost's avatar
Stefan Kost committed
506
                &buffer_time, NULL)) < 0) {
507 508 509 510 511 512 513
      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;
    }
514
    GST_DEBUG_OBJECT (alsa, "buffer time %u", buffer_time);
515
    alsa->buffer_time = buffer_time;
516
  }
517
  if (period_time != -1 && !alsa->iec958) {
518
    /* set the period time */
519
    if ((err = snd_pcm_hw_params_set_period_time_near (alsa->handle, params,
Stefan Kost's avatar
Stefan Kost committed
520
                &period_time, NULL)) < 0) {
521 522 523 524 525 526 527
      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;
    }
528
    GST_DEBUG_OBJECT (alsa, "period time %u", period_time);
529
    alsa->period_time = period_time;
530
  }
531

532 533 534 535 536 537 538 539 540 541 542
  /* 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);
  }

543 544 545
  /* write the parameters to device */
  CHECK (snd_pcm_hw_params (alsa->handle, params), set_hw_params);

546
  /* now get the configured values */
547 548
  CHECK (snd_pcm_hw_params_get_buffer_size (params, &alsa->buffer_size),
      buffer_size);
Stefan Kost's avatar
Stefan Kost committed
549
  CHECK (snd_pcm_hw_params_get_period_size (params, &alsa->period_size, NULL),
550 551
      period_size);

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

Axel Mårtensson's avatar
Axel Mårtensson committed
555 556 557 558 559
  /* Check if hardware supports pause */
  alsa->hw_support_pause = snd_pcm_hw_params_can_pause (params);
  GST_DEBUG_OBJECT (alsa, "Hw support pause: %s",
      alsa->hw_support_pause ? "yes" : "no");

560
  snd_pcm_hw_params_free (params);
561 562 563 564 565
  return 0;

  /* ERRORS */
no_config:
  {
566
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
567
        ("Broken configuration for playback: no configurations available: %s",
568
            snd_strerror (err)));
569
    snd_pcm_hw_params_free (params);
570 571 572 573
    return err;
  }
wrong_access:
  {
574 575
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Access type not available for playback: %s", snd_strerror (err)));
576
    snd_pcm_hw_params_free (params);
577 578 579 580
    return err;
  }
no_sample_format:
  {
581 582
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Sample format not available for playback: %s", snd_strerror (err)));
583
    snd_pcm_hw_params_free (params);
584 585 586 587
    return err;
  }
no_channels:
  {
588 589 590 591 592 593 594 595 596 597 598
    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);
599 600
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, ("%s", msg),
        ("%s", snd_strerror (err)));
601
    g_free (msg);
602
    snd_pcm_hw_params_free (params);
603 604 605 606
    return err;
  }
no_rate:
  {
607
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
608
        ("Rate %iHz not available for playback: %s",
609
            alsa->rate, snd_strerror (err)));
610 611 612 613
    return err;
  }
buffer_size:
  {
614 615
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Unable to get buffer size for playback: %s", snd_strerror (err)));
616
    snd_pcm_hw_params_free (params);
617 618 619 620
    return err;
  }
period_size:
  {
621 622
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Unable to get period size for playback: %s", snd_strerror (err)));
623
    snd_pcm_hw_params_free (params);
624 625 626 627
    return err;
  }
set_hw_params:
  {
628 629
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Unable to set hw params for playback: %s", snd_strerror (err)));
630
    snd_pcm_hw_params_free (params);
631 632 633 634 635 636 637 638 639 640
    return err;
  }
}

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

641
  snd_pcm_sw_params_malloc (&params);
642 643 644 645 646 647 648 649 650 651 652 653

  /* 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);
654 655 656 657

#if GST_CHECK_ALSA_VERSION(1,0,16)
  /* snd_pcm_sw_params_set_xfer_align() is deprecated, alignment is always 1 */
#else
658 659
  /* align all transfers to 1 sample */
  CHECK (snd_pcm_sw_params_set_xfer_align (alsa->handle, params, 1), set_align);
660
#endif
661 662 663 664

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

665
  snd_pcm_sw_params_free (params);
666 667 668 669 670
  return 0;

  /* ERRORS */
no_config:
  {
671
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
672
        ("Unable to determine current swparams for playback: %s",
673
            snd_strerror (err)));
674
    snd_pcm_sw_params_free (params);
675 676 677 678
    return err;
  }
start_threshold:
  {
679
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
680
        ("Unable to set start threshold mode for playback: %s",
681
            snd_strerror (err)));
682
    snd_pcm_sw_params_free (params);
683 684 685 686
    return err;
  }
set_avail:
  {
687 688
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Unable to set avail min for playback: %s", snd_strerror (err)));
689
    snd_pcm_sw_params_free (params);
690 691
    return err;
  }
692
#if !GST_CHECK_ALSA_VERSION(1,0,16)
693 694
set_align:
  {
695 696
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Unable to set transfer align for playback: %s", snd_strerror (err)));
697
    snd_pcm_sw_params_free (params);
698 699
    return err;
  }
700
#endif
701 702
set_sw_params:
  {
703 704
    GST_ELEMENT_ERROR (alsa, RESOURCE, SETTINGS, (NULL),
        ("Unable to set sw params for playback: %s", snd_strerror (err)));
705
    snd_pcm_sw_params_free (params);
706
    return err;
707 708
  }
}
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
709

710
static gboolean
711
alsasink_parse_spec (GstAlsaSink * alsa, GstAudioRingBufferSpec * spec)
712
{
713 714 715
  /* Initialize our boolean */
  alsa->iec958 = FALSE;

716
  switch (spec->type) {
717
    case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_RAW:
Wim Taymans's avatar
Wim Taymans committed
718 719 720 721 722 723 724
      switch (GST_AUDIO_INFO_FORMAT (&spec->info)) {
        case GST_AUDIO_FORMAT_U8:
          alsa->format = SND_PCM_FORMAT_U8;
          break;
        case GST_AUDIO_FORMAT_S8:
          alsa->format = SND_PCM_FORMAT_S8;
          break;
725
        case GST_AUDIO_FORMAT_S16LE:
Wim Taymans's avatar
Wim Taymans committed
726 727
          alsa->format = SND_PCM_FORMAT_S16_LE;
          break;
728
        case GST_AUDIO_FORMAT_S16BE:
Wim Taymans's avatar
Wim Taymans committed
729 730
          alsa->format = SND_PCM_FORMAT_S16_BE;
          break;
731
        case GST_AUDIO_FORMAT_U16LE:
Wim Taymans's avatar
Wim Taymans committed
732 733
          alsa->format = SND_PCM_FORMAT_U16_LE;
          break;
734
        case GST_AUDIO_FORMAT_U16BE:
Wim Taymans's avatar
Wim Taymans committed
735 736
          alsa->format = SND_PCM_FORMAT_U16_BE;
          break;
737
        case GST_AUDIO_FORMAT_S24_32LE:
Wim Taymans's avatar
Wim Taymans committed
738 739
          alsa->format = SND_PCM_FORMAT_S24_LE;
          break;
740
        case GST_AUDIO_FORMAT_S24_32BE:
Wim Taymans's avatar
Wim Taymans committed
741 742
          alsa->format = SND_PCM_FORMAT_S24_BE;
          break;
743
        case GST_AUDIO_FORMAT_U24_32LE:
Wim Taymans's avatar
Wim Taymans committed
744 745
          alsa->format = SND_PCM_FORMAT_U24_LE;
          break;
746
        case GST_AUDIO_FORMAT_U24_32BE:
Wim Taymans's avatar
Wim Taymans committed
747 748
          alsa->format = SND_PCM_FORMAT_U24_BE;
          break;
749
        case GST_AUDIO_FORMAT_S32LE:
Wim Taymans's avatar
Wim Taymans committed
750 751
          alsa->format = SND_PCM_FORMAT_S32_LE;
          break;
752
        case GST_AUDIO_FORMAT_S32BE:
Wim Taymans's avatar
Wim Taymans committed
753 754
          alsa->format = SND_PCM_FORMAT_S32_BE;
          break;
755
        case GST_AUDIO_FORMAT_U32LE:
Wim Taymans's avatar
Wim Taymans committed
756 757
          alsa->format = SND_PCM_FORMAT_U32_LE;
          break;
758
        case GST_AUDIO_FORMAT_U32BE:
Wim Taymans's avatar
Wim Taymans committed
759 760
          alsa->format = SND_PCM_FORMAT_U32_BE;
          break;
761
        case GST_AUDIO_FORMAT_S24LE:
Wim Taymans's avatar
Wim Taymans committed
762 763
          alsa->format = SND_PCM_FORMAT_S24_3LE;
          break;
764
        case GST_AUDIO_FORMAT_S24BE:
Wim Taymans's avatar
Wim Taymans committed
765 766
          alsa->format = SND_PCM_FORMAT_S24_3BE;
          break;
767
        case GST_AUDIO_FORMAT_U24LE:
Wim Taymans's avatar
Wim Taymans committed
768 769
          alsa->format = SND_PCM_FORMAT_U24_3LE;
          break;
770
        case GST_AUDIO_FORMAT_U24BE:
Wim Taymans's avatar
Wim Taymans committed
771 772
          alsa->format = SND_PCM_FORMAT_U24_3BE;
          break;
773
        case GST_AUDIO_FORMAT_S20LE:
Wim Taymans's avatar
Wim Taymans committed
774 775
          alsa->format = SND_PCM_FORMAT_S20_3LE;
          break;
776
        case GST_AUDIO_FORMAT_S20BE:
Wim Taymans's avatar
Wim Taymans committed
777 778
          alsa->format = SND_PCM_FORMAT_S20_3BE;
          break;
779
        case GST_AUDIO_FORMAT_U20LE:
Wim Taymans's avatar
Wim Taymans committed
780 781
          alsa->format = SND_PCM_FORMAT_U20_3LE;
          break;
782
        case GST_AUDIO_FORMAT_U20BE:
Wim Taymans's avatar
Wim Taymans committed
783 784
          alsa->format = SND_PCM_FORMAT_U20_3BE;
          break;
785
        case GST_AUDIO_FORMAT_S18LE:
Wim Taymans's avatar
Wim Taymans committed
786 787
          alsa->format = SND_PCM_FORMAT_S18_3LE;
          break;
788
        case GST_AUDIO_FORMAT_S18BE:
Wim Taymans's avatar
Wim Taymans committed
789 790
          alsa->format = SND_PCM_FORMAT_S18_3BE;
          break;
791
        case GST_AUDIO_FORMAT_U18LE:
Wim Taymans's avatar
Wim Taymans committed
792 793
          alsa->format = SND_PCM_FORMAT_U18_3LE;
          break;
794
        case GST_AUDIO_FORMAT_U18BE:
Wim Taymans's avatar
Wim Taymans committed
795 796
          alsa->format = SND_PCM_FORMAT_U18_3BE;
          break;
797
        case GST_AUDIO_FORMAT_F32LE:
798
          alsa->format = SND_PCM_FORMAT_FLOAT_LE;
799
          break;
800
        case GST_AUDIO_FORMAT_F32BE:
801 802
          alsa->format = SND_PCM_FORMAT_FLOAT_BE;
          break;
803
        case GST_AUDIO_FORMAT_F64LE:
804 805
          alsa->format = SND_PCM_FORMAT_FLOAT64_LE;
          break;
806
        case GST_AUDIO_FORMAT_F64BE:
807 808 809 810
          alsa->format = SND_PCM_FORMAT_FLOAT64_BE;
          break;
        default:
          goto error;
811
      }
812
      break;
813
    case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_A_LAW:
814 815
      alsa->format = SND_PCM_FORMAT_A_LAW;
      break;
816
    case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_MU_LAW:
817 818
      alsa->format = SND_PCM_FORMAT_MU_LAW;
      break;
819 820 821 822
    case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_AC3:
    case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_EAC3:
    case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_DTS:
    case GST_AUDIO_RING_BUFFER_FORMAT_TYPE_MPEG:
823
      alsa->format = SND_PCM_FORMAT_S16_BE;
824
      alsa->iec958 = TRUE;
825
      break;
826 827 828 829
    default:
      goto error;

  }
Wim Taymans's avatar
Wim Taymans committed
830 831
  alsa->rate = GST_AUDIO_INFO_RATE (&spec->info);
  alsa->channels = GST_AUDIO_INFO_CHANNELS (&spec->info);
832 833 834 835
  alsa->buffer_time = spec->buffer_time;
  alsa->period_time = spec->latency_time;
  alsa->access = SND_PCM_ACCESS_RW_INTERLEAVED;

836 837 838 839
  if (spec->type == GST_AUDIO_RING_BUFFER_FORMAT_TYPE_RAW && alsa->channels < 9)
    gst_audio_ring_buffer_set_channel_positions (GST_AUDIO_BASE_SINK
        (alsa)->ringbuffer, alsa_position[alsa->channels - 1]);

840 841 842 843 844 845
  return TRUE;

  /* ERRORS */
error:
  {
    return FALSE;
846 847
  }
}
848 849

static gboolean
850
gst_alsasink_open (GstAudioSink * asink)
851
{
852 853
  GstAlsaSink *alsa;
  gint err;
854

855
  alsa = GST_ALSA_SINK (asink);
856

857 858
  /* open in non-blocking mode, we'll use snd_pcm_wait() for space to become
   * available. */
859 860
  CHECK (snd_pcm_open (&alsa->handle, alsa->device, SND_PCM_STREAM_PLAYBACK,
          SND_PCM_NONBLOCK), open_error);
861
  GST_LOG_OBJECT (alsa, "Opened device %s", alsa->device);
862

863 864 865 866 867
  return TRUE;

  /* ERRORS */
open_error:
  {
868
    if (err == -EBUSY) {
869 870 871 872
      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));
873 874
    } else {
      GST_ELEMENT_ERROR (alsa, RESOURCE, OPEN_WRITE,
875 876
          (_("Could not open audio device for playback.")),
          ("Playback open error on device '%s': %s", alsa->device,
877
              snd_strerror (err)));
878
    }
879 880 881 882 883
    return FALSE;
  }
}

static gboolean
884
gst_alsasink_prepare (GstAudioSink * asink, GstAudioRingBufferSpec * spec)
885 886 887 888 889 890
{
  GstAlsaSink *alsa;
  gint err;

  alsa = GST_ALSA_SINK (asink);

891
  if (alsa->iec958) {
892
    snd_pcm_close (alsa->handle);
893
    alsa->handle = gst_alsa_open_iec958_pcm (GST_OBJECT (alsa), alsa->device);
894 895 896 897 898
    if (G_UNLIKELY (!alsa->handle)) {
      goto no_iec958;
    }
  }

899 900 901
  if (!alsasink_parse_spec (alsa, spec))
    goto spec_parse;

902 903 904
  CHECK (set_hwparams (alsa), hw_params_failed);
  CHECK (set_swparams (alsa), sw_params_failed);

Wim Taymans's avatar
Wim Taymans committed
905 906
  alsa->bpf = GST_AUDIO_INFO_BPF (&spec->info);
  spec->segsize = alsa->period_size * alsa->bpf;
907 908
  spec->segtotal = alsa->buffer_size / alsa->period_size;

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
  {
    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);
  }

925
#ifdef SND_CHMAP_API_VERSION
926 927
  alsa_detect_channels_mapping (GST_OBJECT (alsa), alsa->handle, spec,
      alsa->channels, GST_AUDIO_BASE_SINK (alsa)->ringbuffer);