gstalsa.c 78.2 KB
Newer Older
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
1
/*
2
3
4
 * Copyright (C) 2001 CodeFactory AB
 * Copyright (C) 2001 Thomas Nyberg <thomas@codefactory.se>
 * Copyright (C) 2001-2002 Andy Wingo <apwingo@eos.ncsu.edu>
5
 * Copyright (C) 2003 Benjamin Otte <in7y118@public.uni-hamburg.de>
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
21

22
#include <sys/time.h>
23
#include "gstalsa.h"
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
24

25
/* error checking for standard alsa functions */
26
27
28
29
30
31
#define SIMPLE_ERROR_CHECK(value) G_STMT_START{ \
  int err = (value); \
  if (err < 0) { \
    return FALSE; \
  } \
}G_STMT_END
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#ifdef G_HAVE_ISO_VARARGS
#define ERROR_CHECK(value, ...) G_STMT_START{ \
  int err = (value); \
  if (err < 0) { \
    g_warning ( __VA_ARGS__, snd_strerror (err)); \
    return FALSE; \
  } \
}G_STMT_END
#elif defined(G_HAVE_GNUC_VARARGS)
#define ERROR_CHECK(value, args...) G_STMT_START{ \
  int err = (value); \
  if (err < 0) { \
    g_warning ( ## args, snd_strerror (err)); \
    return FALSE; \
  } \
}G_STMT_END
#else
#define ERROR_CHECK(value, args...) G_STMT_START{ \
  int err = (value); \
  if (err < 0) { \
    g_warning (snd_strerror (err)); \
    return FALSE; \
  } \
}G_STMT_END
#endif
57
/* elementfactory information */
58
static GstElementDetails gst_alsa_sink_details = {
59
60
61
62
63
64
  "Alsa Sink",
  "Sink/Audio",
  "LGPL",
  "Output to a sound card via ALSA",
  VERSION,
  "Thomas Nyberg <thomas@codefactory.se>, "
Benjamin Otte's avatar
Benjamin Otte committed
65
  "Andy Wingo <apwingo@eos.ncsu.edu>, "
66
67
  "Benjamin Otte <in7y118@public.uni-hamburg.de>",
  "(C) 2001-2003"
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
68
69
};

70
/* elementfactory information */
71
static GstElementDetails gst_alsa_src_details = {
72
73
74
75
76
77
  "Alsa Src",
  "Source/Audio",
  "LGPL",
  "Read from a sound card via ALSA",
  VERSION,
  "Thomas Nyberg <thomas@codefactory.se>, "
Benjamin Otte's avatar
Benjamin Otte committed
78
  "Andy Wingo <apwingo@eos.ncsu.edu>, "
79
80
  "Benjamin Otte <in7y118@public.uni-hamburg.de>",
  "(C) 2001-2003"
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
81
82
};

83
/* GObject functions */
84
85
86
87
88
89
90
91
92
93
94
static void			gst_alsa_class_init		(GstAlsaClass *		klass);
static void			gst_alsa_init			(GstAlsa *		this);
static void			gst_alsa_dispose		(GObject *		object);
static void			gst_alsa_set_property		(GObject *		object,
								 guint			prop_id,
								 const GValue *		value,
								 GParamSpec *		pspec);
static void			gst_alsa_get_property		(GObject *		object,
								 guint			prop_id,
								 GValue *		value,
								 GParamSpec *		pspec);
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
95

96
/* GstAlsaSink functions */
Benjamin Otte's avatar
Benjamin Otte committed
97
98
static GstPadTemplate *		gst_alsa_sink_pad_factory 	(void);
static GstPadTemplate *		gst_alsa_sink_request_pad_factory (void);
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
static void			gst_alsa_sink_class_init	(GstAlsaSinkClass *	klass);
static void			gst_alsa_sink_init		(GstAlsaSink *		this);
static inline void		gst_alsa_sink_flush_one_pad	(GstAlsaSink *		sink,
								 gint 			i);
static void			gst_alsa_sink_flush_pads	(GstAlsaSink *		sink);
static int			gst_alsa_sink_mmap		(GstAlsa *		this,
								 snd_pcm_sframes_t *	avail);
static int			gst_alsa_sink_write		(GstAlsa *		this,
								 snd_pcm_sframes_t *	avail);
static void			gst_alsa_sink_loop		(GstElement *		element);
static gboolean			gst_alsa_sink_check_event	(GstAlsaSink *		sink, 
								 gint			pad_nr);
static GstElementStateReturn	gst_alsa_sink_change_state	(GstElement *		element);

/* GstAlsaSrc functions */
static GstPadTemplate *		gst_alsa_src_pad_factory 	(void);
static GstPadTemplate *		gst_alsa_src_request_pad_factory (void);
static void			gst_alsa_src_class_init		(GstAlsaSrcClass *	klass);
static void			gst_alsa_src_init		(GstAlsaSrc *		this);
118
119
120
121
static int			gst_alsa_src_mmap		(GstAlsa *		this,
								 snd_pcm_sframes_t *	avail);
static int			gst_alsa_src_read		(GstAlsa *		this,
								 snd_pcm_sframes_t *	avail);
122
static void			gst_alsa_src_loop		(GstElement *		element);
123
124
static void			gst_alsa_src_flush		(GstAlsaSrc *		src);
static GstElementStateReturn	gst_alsa_src_change_state	(GstElement *		element);
Benjamin Otte's avatar
Benjamin Otte committed
125

Benjamin Otte's avatar
Benjamin Otte committed
126
/* GStreamer functions for pads, queries, conversions and state changing */
127
128
129
130
131
132
133
134
135
136
137
static GstPad *			gst_alsa_request_new_pad	(GstElement *		element, 
								 GstPadTemplate *	templ,
								 const gchar *		name);
static GstPadLinkReturn		gst_alsa_link 			(GstPad *		pad, 
								 GstCaps *		caps);
static GstCaps *		gst_alsa_get_caps		(GstPad *		pad,
								 GstCaps *		caps);
static GstCaps *		gst_alsa_caps			(snd_pcm_format_t	format,
								 gint			rate,
								 gint			channels);
static GstElementStateReturn	gst_alsa_change_state		(GstElement *		element);
Benjamin Otte's avatar
Benjamin Otte committed
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
static const GstFormat * 	gst_alsa_get_formats	 	(GstPad *		pad);
static gboolean 		gst_alsa_convert 		(GstAlsa *		this,
								 GstFormat		src_format, 
								 gint64			src_value,
	            						 GstFormat *		dest_format,
								 gint64 *		dest_value);
static gboolean 		gst_alsa_pad_convert 		(GstPad *		pad,
								 GstFormat		src_format, 
								 gint64			src_value,
	            						 GstFormat *		dest_format,
								 gint64 *		dest_value);
static const GstQueryType * 	gst_alsa_get_query_types 	(GstPad *		pad);
static gboolean 		gst_alsa_query_func 		(GstElement *		element,
								 GstQueryType		type, 
								 GstFormat *		format,
								 gint64 *		value);
static gboolean 		gst_alsa_query	 		(GstElement *		element,
								 GstQueryType		type, 
								 GstFormat *		format,
								 gint64 *		value);
static gboolean 		gst_alsa_pad_query 		(GstPad *		pad,
								 GstQueryType		type,
								 GstFormat *		format,
								 gint64 *		value);
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
162

163
/* audio processing functions */
164
static void			gst_alsa_xrun_recovery		(GstAlsa *		this);
165
166
167
inline static snd_pcm_sframes_t	gst_alsa_update_avail		(GstAlsa *		this);
inline static gboolean		gst_alsa_pcm_wait		(GstAlsa *		this);
inline static gboolean		gst_alsa_start			(GstAlsa *		this);
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
168

169
/* alsa setup / start / stop functions */
170
static void			gst_alsa_set_eos		(GstAlsa *		this);
Benjamin Otte's avatar
Benjamin Otte committed
171

172
173
174
175
static gboolean			gst_alsa_probe_hw_params	(GstAlsa *		this, 
								 GstAlsaFormat *	format);
static gboolean			gst_alsa_set_hw_params		(GstAlsa *		this);
static gboolean			gst_alsa_set_sw_params		(GstAlsa *		this);
Benjamin Otte's avatar
Benjamin Otte committed
176

177
178
179
180
181
static gboolean			gst_alsa_open_audio		(GstAlsa *		this);
static gboolean			gst_alsa_start_audio		(GstAlsa *		this);
static gboolean			gst_alsa_drain_audio		(GstAlsa *		this);
static gboolean 		gst_alsa_stop_audio		(GstAlsa *		this);
static gboolean 		gst_alsa_close_audio		(GstAlsa *		this);
Benjamin Otte's avatar
Benjamin Otte committed
182
183

/* clock functions */
184
185
static void	 		gst_alsa_clock_class_init 	(GstAlsaClockClass *	klass);
static void 			gst_alsa_clock_init 		(GstAlsaClock *		clock);
Benjamin Otte's avatar
Benjamin Otte committed
186
static GstAlsaClock *		gst_alsa_clock_new		(gchar *name, 
Benjamin Otte's avatar
Benjamin Otte committed
187
								 GstAlsaClockGetTimeFunc func,
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
								 GstAlsa* 		owner);

static void			gst_alsa_clock_start	 	(GstAlsaClock *		clock);
static void			gst_alsa_clock_stop	 	(GstAlsaClock *		clock);

static GstClockTime		gst_alsa_clock_get_internal_time (GstClock *		clock);
static guint64			gst_alsa_clock_get_resolution	(GstClock *		clock);
static GstClockEntryStatus	gst_alsa_clock_wait		(GstClock *		clock,
								 GstClockEntry *	entry);
static void			gst_alsa_clock_unlock		(GstClock *		clock, 
								 GstClockEntry *	entry);

static GstClockTime		gst_alsa_sink_get_time		(GstAlsa *		this);
static GstClockTime		gst_alsa_src_get_time		(GstAlsa *		this);
static GstClock *		gst_alsa_get_clock		(GstElement *		element);
static void			gst_alsa_set_clock		(GstElement *		element, 
								 GstClock *		clock);
Benjamin Otte's avatar
Benjamin Otte committed
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
static GstClockClass *		clock_parent_class = NULL;
/* static guint gst_alsa_clock_signals[LAST_SIGNAL] = { 0 }; */

/* format conversions */
static inline snd_pcm_uframes_t	gst_alsa_timestamp_to_samples 	(GstAlsa *		this, 
								 GstClockTime 		time);
static inline GstClockTime 	gst_alsa_samples_to_timestamp 	(GstAlsa *		this, 
								 snd_pcm_uframes_t 	samples);
static inline snd_pcm_uframes_t	gst_alsa_bytes_to_samples 	(GstAlsa *		this, 
								 guint	 		bytes);
static inline guint	 	gst_alsa_samples_to_bytes 	(GstAlsa *		this, 
								 snd_pcm_uframes_t 	samples);
static inline GstClockTime	gst_alsa_bytes_to_timestamp 	(GstAlsa *		this, 
								 guint	 		bytes);
static inline guint	 	gst_alsa_timestamp_to_bytes 	(GstAlsa *		this, 
								 GstClockTime	 	time);
221

222
/*** TYPE FUNCTIONS ***********************************************************/
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
223
224

GType
225
gst_alsa_get_type (void)
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
226
{
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
  static GType alsa_type = 0;

  if (!alsa_type) {
    static const GTypeInfo alsa_info = {
      sizeof (GstAlsaClass),
      NULL,
      NULL,
      (GClassInitFunc) gst_alsa_class_init,
      NULL,
      NULL,
      sizeof (GstAlsa),
      0,
      (GInstanceInitFunc) gst_alsa_init,
    };

242
    alsa_type = g_type_register_static (GST_TYPE_ELEMENT, "GstAlsa", &alsa_info, 0);
243
244
  }
  return alsa_type;
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
245
246
}

247
/*** GOBJECT FUNCTIONS ********************************************************/
248

249
250
251
252
253
enum
{
  ARG_0,
  ARG_DEVICE,
  ARG_PERIODCOUNT,
254
255
  ARG_PERIODSIZE,
  ARG_BUFFERSIZE,
Benjamin Otte's avatar
Benjamin Otte committed
256
  ARG_AUTORECOVER,
257
258
  ARG_MMAP,
  ARG_MAXDISCONT
259
};
260

261
static GstElement *parent_class = NULL;
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
262

263
264
static void
gst_alsa_class_init (GstAlsaClass *klass)
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
265
{
266
267
268
269
270
271
272
273
274
  GObjectClass *object_class;
  GstElementClass *element_class;

  object_class = (GObjectClass *) klass;
  element_class = (GstElementClass *) klass;

  if (parent_class == NULL)
    parent_class = g_type_class_ref (GST_TYPE_ELEMENT);

275
  object_class->dispose = gst_alsa_dispose;
276
277
278
279
280
281
282
283
284
  object_class->get_property = gst_alsa_get_property;
  object_class->set_property = gst_alsa_set_property;

  g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_DEVICE,
    g_param_spec_string ("device", "Device", "Alsa device, as defined in an asoundrc",
                         "default", G_PARAM_READWRITE | G_PARAM_CONSTRUCT));
  g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_PERIODCOUNT,
    g_param_spec_int ("period-count", "Period count", "Number of hardware buffers to use",
                      2, 64, 2, G_PARAM_READWRITE | G_PARAM_CONSTRUCT));
285
286
  g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_PERIODSIZE,
    g_param_spec_int ("period-size", "Period size", "Number of frames (samples on each channel) in one hardware period",
Benjamin Otte's avatar
Benjamin Otte committed
287
                      2, 8192, 8192, G_PARAM_READWRITE | G_PARAM_CONSTRUCT));
288
289
  g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_BUFFERSIZE,
    g_param_spec_int ("buffer-size", "Buffer size", "Number of frames the hardware buffer can hold",
Benjamin Otte's avatar
Benjamin Otte committed
290
                      4, 65536, 16384, G_PARAM_READWRITE));
291
  g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_AUTORECOVER,
292
    g_param_spec_boolean ("autorecover", "Automatic xrun recovery", "When TRUE tries to reduce processor load on xruns",
293
                          TRUE, G_PARAM_READWRITE | G_PARAM_CONSTRUCT));
Benjamin Otte's avatar
Benjamin Otte committed
294
295
296
  g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_MMAP,
    g_param_spec_boolean ("mmap", "Use mmap'ed access", "Wether to use mmap (faster) or standard read/write (more compatible)",
                          TRUE, G_PARAM_READWRITE | G_PARAM_CONSTRUCT));
297
298
299
  g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_MAXDISCONT,
    g_param_spec_uint64 ("max-discont", "Maximum Discontinuity", "GStreamer timeunits before the timestamp syncing starts dropping/insertting samples",
   /* rounding errors */ 1000, GST_SECOND, GST_ALSA_DEFAULT_DISCONT, G_PARAM_READWRITE | G_PARAM_CONSTRUCT));
300

Benjamin Otte's avatar
Benjamin Otte committed
301
302
303
304
305
  element_class->change_state    = GST_DEBUG_FUNCPTR (gst_alsa_change_state);
  element_class->query	 	 = GST_DEBUG_FUNCPTR (gst_alsa_query);
  element_class->request_new_pad = GST_DEBUG_FUNCPTR (gst_alsa_request_new_pad);
  element_class->set_clock 	 = GST_DEBUG_FUNCPTR (gst_alsa_set_clock);
  element_class->get_clock 	 = GST_DEBUG_FUNCPTR (gst_alsa_get_clock);
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
306
307
}

308
309
static void
gst_alsa_init (GstAlsa *this)
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
310
{
Benjamin Otte's avatar
Benjamin Otte committed
311
  GST_FLAG_SET (this, GST_ELEMENT_EVENT_AWARE);
312
  GST_FLAG_SET (this, GST_ELEMENT_THREAD_SUGGESTED);
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
313
}
314
315
316
317
318
static void
gst_alsa_dispose (GObject *object)
{
  GstAlsa *this = GST_ALSA (object);

319
  if (this->clock)
Benjamin Otte's avatar
Benjamin Otte committed
320
    gst_object_unparent (GST_OBJECT (this->clock));
Benjamin Otte's avatar
Benjamin Otte committed
321
322

  G_OBJECT_CLASS (parent_class)->dispose (object);
323
}
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
324
static void
325
326
gst_alsa_set_property (GObject *object, guint prop_id, const GValue *value,
                       GParamSpec *pspec)
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
327
{
328
  GstAlsa *this;
329
  gint buffer_size;
330
331
332
333
334
335
336
337
338

  this = (GstAlsa *) object;
  switch (prop_id) {
  case ARG_DEVICE:
    if (this->device)
      g_free (this->device);
    this->device = g_strdup (g_value_get_string (value));
    break;
  case ARG_PERIODCOUNT:
339
    g_return_if_fail (!GST_FLAG_IS_SET (this, GST_ALSA_RUNNING));
340
341
    this->period_count = g_value_get_int (value);
    break;
342
343
344
345
346
347
348
349
  case ARG_PERIODSIZE:
    g_return_if_fail (!GST_FLAG_IS_SET (this, GST_ALSA_RUNNING));
    this->period_size = g_value_get_int (value);
    break;
  case ARG_BUFFERSIZE:
    g_return_if_fail (!GST_FLAG_IS_SET (this, GST_ALSA_RUNNING));
    buffer_size = g_value_get_int (value);
    this->period_count = buffer_size / this->period_size;
350
351
352
353
    break;
  case ARG_AUTORECOVER:
    this->autorecover = g_value_get_boolean (value);
    return;
Benjamin Otte's avatar
Benjamin Otte committed
354
355
356
  case ARG_MMAP:
    this->mmap = g_value_get_boolean (value);
    return;
357
358
359
  case ARG_MAXDISCONT:
    this->max_discont = (GstClockTime) g_value_get_uint64 (value);
    return;
360
  default:
Benjamin Otte's avatar
Benjamin Otte committed
361
    G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
362
363
364
365
366
367
368
369
    return;
  }

  if (GST_STATE (this) == GST_STATE_NULL)
    return;

  if (GST_FLAG_IS_SET (this, GST_ALSA_RUNNING)) {
    gst_alsa_stop_audio (this);
370
    gst_alsa_start_audio (this);
371
  }
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
372
373
374
}

static void
375
376
gst_alsa_get_property (GObject *object, guint prop_id, GValue *value,
                       GParamSpec *pspec)
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
377
{
378
379
380
381
382
383
384
385
  GstAlsa *this;

  this = (GstAlsa *) object;

  switch (prop_id) {
  case ARG_DEVICE:
    g_value_set_string (value, this->device);
    break;
386
  case ARG_PERIODCOUNT:
387
388
    g_value_set_int (value, this->period_count);
    break;
389
390
  case ARG_PERIODSIZE:
    g_value_set_int (value, this->period_size);
391
    break;
392
393
  case ARG_BUFFERSIZE:
    g_value_set_int (value, this->period_size * this->period_count);
394
395
396
397
    break;
  case ARG_AUTORECOVER:
    g_value_set_boolean (value, this->autorecover);
    break;
Benjamin Otte's avatar
Benjamin Otte committed
398
399
400
  case ARG_MMAP:
    g_value_set_boolean (value, this->mmap);
    break;
401
402
403
  case ARG_MAXDISCONT:
    g_value_set_uint64 (value, (guint64) this->max_discont);
    return;
404
  default:
Benjamin Otte's avatar
Benjamin Otte committed
405
    G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
406
407
408
    break;
  }
}
409
410


411
/*** GSTALSASINK FUNCTIONS ****************************************************/
412

413
static GstAlsa *sink_parent_class = NULL;
414

415
416
417
418
static GstPadTemplate *
gst_alsa_sink_pad_factory (void)
{
  static GstPadTemplate *template = NULL;
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
419

420
  if (!template)
421
422
    template = gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
                                     gst_alsa_caps (SND_PCM_FORMAT_UNKNOWN, -1, -1),
423
                                     NULL);
424

425
  return template;
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
426
}
427
428
static GstPadTemplate *
gst_alsa_sink_request_pad_factory (void)
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
429
{
430
  static GstPadTemplate *template = NULL;
431

432
433
434
  if (!template)
    template =
      gst_pad_template_new ("sink%d", GST_PAD_SINK, GST_PAD_REQUEST,
435
                                     gst_alsa_caps (SND_PCM_FORMAT_UNKNOWN, -1, 1),
436
                            NULL);
437

438
  return template;
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
439
}
440
441
GType
gst_alsa_sink_get_type (void)
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
442
{
443
  static GType alsa_sink_type = 0;
444

445
446
447
448
449
450
451
452
453
454
455
456
  if (!alsa_sink_type) {
    static const GTypeInfo alsa_sink_info = {
      sizeof (GstAlsaSinkClass),
      NULL,
      NULL,
      (GClassInitFunc) gst_alsa_sink_class_init,
      NULL,
      NULL,
      sizeof (GstAlsaSink),
      0,
      (GInstanceInitFunc) gst_alsa_sink_init,
    };
457

458
    alsa_sink_type = g_type_register_static (GST_TYPE_ALSA, "GstAlsaSink", &alsa_sink_info, 0);
459
  }
460
461
462
463
464
465
466
467
  return alsa_sink_type;
}
static void
gst_alsa_sink_class_init (GstAlsaSinkClass *klass)
{
  GObjectClass *object_class;
  GstElementClass *element_class;
  GstAlsaClass *alsa_class;
468

469
470
471
  object_class = (GObjectClass *) klass;
  element_class = (GstElementClass *) klass;
  alsa_class = (GstAlsaClass *) klass;
472

473
474
475
476
477
478
  if (sink_parent_class == NULL)
    sink_parent_class = g_type_class_ref (GST_TYPE_ALSA);
  
  alsa_class->stream		= SND_PCM_STREAM_PLAYBACK;
  alsa_class->transmit_mmap	= gst_alsa_sink_mmap;
  alsa_class->transmit_rw	= gst_alsa_sink_write;
479

480
  element_class->change_state	= gst_alsa_sink_change_state;
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
481
}
482
483
static void
gst_alsa_sink_init (GstAlsaSink *sink)
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
484
{
485
  GstAlsa *this = GST_ALSA (sink);
Benjamin Otte's avatar
Benjamin Otte committed
486

487
488
489
490
491
492
493
494
495
  this->pad[0] = gst_pad_new_from_template (gst_alsa_sink_pad_factory (), "sink");
  gst_pad_set_link_function (this->pad[0], gst_alsa_link);
  gst_pad_set_getcaps_function (this->pad[0], gst_alsa_get_caps);
  gst_element_add_pad (GST_ELEMENT (this), this->pad[0]);
  
  this->clock = gst_alsa_clock_new ("alsasinkclock", gst_alsa_sink_get_time, this);
  /* we hold a ref to our clock until we're disposed */
  gst_object_ref (GST_OBJECT (this->clock));
  gst_object_sink (GST_OBJECT (this->clock));
496

497
498
  gst_element_set_loop_function (GST_ELEMENT (this), gst_alsa_sink_loop);
}
499

500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
static inline void
gst_alsa_sink_flush_one_pad (GstAlsaSink *sink, gint i)
{
  switch (sink->behaviour[i]) {
  case 0:
    if (sink->buf[i])
      gst_data_unref (GST_DATA (sink->buf[i]));
    sink->buf[i] = NULL;  
    sink->data[i] = NULL;
    sink->behaviour[i] = 0;
    sink->size[i] = 0;
    break;
  case 1:
    g_free (sink->data[i]);
    sink->data[i] = NULL;
    sink->behaviour[i] = 0;
    sink->size[i] = 0;
    break;
  default:
    g_assert_not_reached ();
  }
}
static void
gst_alsa_sink_flush_pads (GstAlsaSink *sink)
{
  gint i;
526

527
528
529
530
531
532
533
534
535
536
537
538
539
  for (i = 0; i < GST_ELEMENT (sink)->numpads; i++) {
    /* flush twice to unref buffer when behaviour == 1 */
    gst_alsa_sink_flush_one_pad (sink, i);
    gst_alsa_sink_flush_one_pad (sink, i);
  }
}
/* TRUE, if everything should continue */
static gboolean
gst_alsa_sink_check_event (GstAlsaSink *sink, gint pad_nr)
{
  gboolean cont = TRUE;
  GstEvent *event = GST_EVENT (sink->buf[pad_nr]);
  GstAlsa *this = GST_ALSA (sink);
540

541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
  if (event) {
    switch (GST_EVENT_TYPE (event)) {
      case GST_EVENT_EOS:
        gst_alsa_set_eos (this);
        cont = FALSE;
        break;
      case GST_EVENT_INTERRUPT:
	cont = FALSE;
        break;
      case GST_EVENT_NEW_MEDIA:
	/* only the first pad my seek */
	if (pad_nr != 0)
	  break;	    
	
	if (GST_CLOCK_TIME_IS_VALID (this->clock->start_time)) { /* if the clock is running */
	  g_assert (this->format);
	  /* adjust the start time */
	  this->clock->start_time += gst_alsa_samples_to_timestamp (this, this->transmitted);
	}
	this->transmitted = 0;
	/* FIXME: Notify the clock that we're at offset 0 again */
	break;
      case GST_EVENT_DISCONTINUOUS: 
	{
	  gint64 value;
	  
	  /* only the first pad my seek */
	  if (pad_nr != 0) {
	    break;	    
	  }
	  if (gst_event_discont_get_value (event, GST_FORMAT_TIME, &value)) {
	    if (!gst_clock_handle_discont (GST_ELEMENT (this)->clock, value))
	      g_printerr ("GstAlsa: clock couldn't handle discontinuity\n");
	  }
	  if (!gst_event_discont_get_value (event, GST_FORMAT_UNITS, &value)) {
	    if (!gst_event_discont_get_value (event, GST_FORMAT_BYTES, &value)) {
	      if (!gst_event_discont_get_value (event, GST_FORMAT_TIME, &value)) {
	        g_warning ("GstAlsa: Could not acquire samplecount after seek, the clock might screw your pipeline now");
	        break;
	      } else {
	        if (this->format) /* discont event before any data (and before any caps...) */
	          value = gst_alsa_timestamp_to_samples (this, value);
	      }
	    } else {
              if (this->format) /* discont event before any data (and before any caps...) */
	        value = gst_alsa_bytes_to_samples (this, value);
	    }
	  }
	  if (GST_CLOCK_TIME_IS_VALID (this->clock->start_time)) { /* if the clock is running */
	    g_assert (this->format);
	    /* adjust the start time */
	    this->clock->start_time += gst_alsa_samples_to_timestamp (this, this->transmitted) - 
	                               gst_alsa_samples_to_timestamp (this, value);
	  }
	  this->transmitted = value;
	  break;
        }
      default:
        g_warning ("GstAlsa: got an unknown event (Type: %d)", GST_EVENT_TYPE (event));
        break;
    }
    gst_event_unref (event);
    sink->buf[pad_nr] = NULL;
  } else {
    /* the element at the top of the chain did not emit an event. */
    g_assert_not_reached ();
  }
  return cont;
}
static int
gst_alsa_sink_mmap (GstAlsa *this, snd_pcm_sframes_t *avail)
{
  snd_pcm_uframes_t offset;
  const snd_pcm_channel_area_t *dst;
  snd_pcm_channel_area_t *src;
  GstAlsaSink *sink = GST_ALSA_SINK (this);
  int i, err, width = snd_pcm_format_physical_width (this->format->format);

  /* areas points to the memory areas that belong to gstreamer. */
  src = calloc(this->format->channels, sizeof(snd_pcm_channel_area_t));

  if (((GstElement *) this)->numpads == 1) {
    /* interleaved */
    for (i = 0; i < this->format->channels; i++) {
      src[i].addr = sink->data[0];
      src[i].first = i * width;
      src[i].step = this->format->channels * width;
    }
  } else {
    /* noninterleaved */
    for (i = 0; i < this->format->channels; i++) {
      src[i].addr = sink->data[i];
      src[i].first = 0;
      src[i].step = width;
635
636
    }
  }
637

638
639
640
641
  if ((err = snd_pcm_mmap_begin (this->handle, &dst, &offset, avail)) < 0) {
    g_warning ("gstalsa: mmap failed: %s", snd_strerror (err));
    return -1;
  }
642

643
644
645
646
647
648
649
650
651
652
653
654
655
656
  if ((err = snd_pcm_areas_copy (dst, offset, src, 0, this->format->channels, *avail, this->format->format)) < 0) {
    snd_pcm_mmap_commit (this->handle, offset, 0);
    g_warning ("gstalsa: data copy failed: %s", snd_strerror (err));
    return -1;
  }
  if ((err = snd_pcm_mmap_commit (this->handle, offset, *avail)) < 0) {
    g_warning ("gstalsa: mmap commit failed: %s", snd_strerror (err));
    return -1;
  }

  return err;
}
static int
gst_alsa_sink_write (GstAlsa *this, snd_pcm_sframes_t *avail)
Benjamin Otte's avatar
Benjamin Otte committed
657
{
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
  GstAlsaSink *sink = GST_ALSA_SINK (this);
  void *channels[this->format->channels];
  int err, i;

  if (((GstElement *) this)->numpads == 1) {
    /* interleaved */
    err = snd_pcm_writei (this->handle, sink->data[0], *avail);
  } else {
    /* noninterleaved */
    for (i = 0; i < this->format->channels; i++) {
      channels[i] = sink->data[i];
    }
    err = snd_pcm_writen (this->handle, channels, *avail);
  }
  /* error handling */
  if (err < 0) {
    if (err == -EPIPE) {
      gst_alsa_xrun_recovery (this);
      return 0;
    }
    g_warning ("error on data access: %s", snd_strerror (err));
  }
  return err;
Benjamin Otte's avatar
Benjamin Otte committed
681
}
682
683
static void
gst_alsa_sink_loop (GstElement *element)
684
{
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
  snd_pcm_sframes_t avail, avail2, copied;
  snd_pcm_uframes_t samplestamp;
  gint i;
  guint bytes; /* per channel */
  GstAlsa *this = GST_ALSA (element);
  GstAlsaSink *sink = GST_ALSA_SINK (element);

  g_return_if_fail (sink != NULL);

sink_restart:

  avail = gst_alsa_update_avail (this);
  if (avail == -EPIPE) goto sink_restart;
  if (avail < 0) return;
  if (avail > 0) {

  /* Not enough space. We grab data nonetheless and sleep afterwards */
    if (avail < this->period_size) {
      avail = this->period_size;
    }
    
    /* check how many bytes we still have in all our bytestreams */
    /* initialize this value to a somewhat sane state, we might alloc this much data below (which would be a bug, but who knows)... */
    bytes = this->period_size * this->period_count * element->numpads * 8; /* must be > max sample size in bytes */
    for (i = 0; i < element->numpads; i++) {
      g_assert (this->pad[i] != NULL);
      while (sink->size[i] == 0) {
        if (!sink->buf[i])
          sink->buf[i] = gst_pad_pull (this->pad[i]);
        if (GST_IS_EVENT (sink->buf[i])) {
	  if (gst_alsa_sink_check_event (sink, i))
	    continue;
	  return;
	}
        /* caps nego failed somewhere */
        if (this->format == NULL) {
          gst_element_error (GST_ELEMENT (this), "alsasink: No caps available");
          return;
        }
        samplestamp = gst_alsa_timestamp_to_samples (this, GST_BUFFER_TIMESTAMP (sink->buf[i]));
Benjamin Otte's avatar
Benjamin Otte committed
725
726
        if ((!GST_BUFFER_TIMESTAMP_IS_VALID (sink->buf[i])) || 
	     /* difference between expected and current is < GST_ALSA_DEVIATION */
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
	    ((this->transmitted + gst_alsa_timestamp_to_samples (this, this->max_discont) >= samplestamp) &&
	     (this->transmitted <= gst_alsa_timestamp_to_samples (this, this->max_discont) + samplestamp))) {
no_difference:
	  sink->size[i] = sink->buf[i]->size;
          sink->data[i] = sink->buf[i]->data;
          sink->behaviour[i] = 0;
	} else if (samplestamp > this->transmitted) {
	  /* there are empty samples in front of us, fill them with silence */
	  int samples = MIN (bytes, samplestamp - this->transmitted) * 
	             (element->numpads == 1 ? this->format->channels : 1);
	  int size = samples * snd_pcm_format_physical_width (this->format->format) / 8;
	  g_printerr ("Allocating %d bytes (%ld samples) now to resync: sample %ld expected, but got %ld\n", 
	              size, MIN (bytes, samplestamp - this->transmitted), this->transmitted, samplestamp);
	  sink->data[i] = g_malloc (size);
	  if (!sink->data[i]) {
	    g_warning ("GstAlsa: error allocating %d bytes, buffers unsynced now.", size);
	    goto no_difference;
	  }
	  sink->size[i] = size;
	  if (0 != snd_pcm_format_set_silence (this->format->format, sink->data[i], samples)) {
	    g_warning ("GstAlsa: error silencing buffer, enjoy the noise.");
	  }
	  sink->behaviour[i] = 1;
	} else if (gst_alsa_samples_to_bytes (this, this->transmitted - samplestamp) >= sink->buf[i]->size) {
Benjamin Otte's avatar
Benjamin Otte committed
751
752
	  g_printerr ("Skipping %lu samples to resync (complete buffer): sample %ld expected, but got %ld\n", 
	              gst_alsa_bytes_to_samples (this, sink->buf[i]->size), this->transmitted, samplestamp);	              
753
754
755
756
757
758
	  /* this buffer is way behind */
	  gst_buffer_unref (sink->buf[i]);
	  sink->buf[i] = NULL;
	  continue;
	} else if (this->transmitted > samplestamp) {
	  gint difference = gst_alsa_samples_to_bytes (this, this->transmitted - samplestamp);	
Benjamin Otte's avatar
Benjamin Otte committed
759
760
	  g_printerr ("Skipping %lu samples to resync: sample %ld expected, but got %ld\n",
		      (gulong) this->transmitted - samplestamp, this->transmitted, samplestamp);
761
762
763
764
765
766
767
	  /* this buffer is only a bit behind */
          sink->size[i] = sink->buf[i]->size - difference;
          sink->data[i] = sink->buf[i]->data + difference;
          sink->behaviour[i] = 0;
	} else {
	  g_assert_not_reached ();
	}
Benjamin Otte's avatar
Benjamin Otte committed
768
      }
769
      bytes = MIN (bytes, sink->size[i]);
770
771
    }

772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
    avail = MIN (avail, gst_alsa_bytes_to_samples (this, bytes));

    /* wait until the hw buffer has enough space */
    while (gst_element_get_state (element) == GST_STATE_PLAYING && (avail2 = gst_alsa_update_avail (this)) < avail) {
      if (avail2 <= -EPIPE) goto sink_restart;
      if (avail2 < 0) return;
      if (avail2 < avail && snd_pcm_state(this->handle) != SND_PCM_STATE_RUNNING)
	if (!gst_alsa_start (this)) return;
      if (gst_alsa_pcm_wait (this) == FALSE)
        return;
    }

    /* FIXME: lotsa stuff can have happened while fetching data. Do we need to check something? */
  
    /* put this data into alsa */
    if ((copied = this->transmit (this, &avail)) < 0)
      return;
    /* update our clock */
    this->transmitted += copied;
    /* flush the data */
    bytes = gst_alsa_samples_to_bytes (this, copied);
    for (i = 0; i < element->numpads; i++) {
      if ((sink->size[i] -= bytes) == 0) {
        gst_alsa_sink_flush_one_pad (sink, i);
        continue;
      }
      g_assert (sink->size[i] > 0);
      if (sink->behaviour[i] != 1)
        sink->data[i] += bytes;
    }
802
  }
803

804
805
  if (snd_pcm_state(this->handle) != SND_PCM_STATE_RUNNING && snd_pcm_avail_update (this->handle) == 0) {
    gst_alsa_start (this);
806
  }
807

808
}
809

810
811
static GstElementStateReturn
gst_alsa_sink_change_state (GstElement *element)
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
812
{
813
  GstAlsaSink *sink;
814

815
816
  g_return_val_if_fail (element != NULL, FALSE);
  sink = GST_ALSA_SINK (element);
817

818
819
820
821
822
823
824
825
826
827
828
829
830
  switch (GST_STATE_TRANSITION (element)) {
  case GST_STATE_NULL_TO_READY:
  case GST_STATE_READY_TO_PAUSED:
  case GST_STATE_PAUSED_TO_PLAYING:
  case GST_STATE_PLAYING_TO_PAUSED:
    break;
  case GST_STATE_PAUSED_TO_READY:
    gst_alsa_sink_flush_pads (sink);
    break;
  case GST_STATE_READY_TO_NULL:
    break;
  default:
    g_assert_not_reached();
831
832
  }

833
834
835
836
  if (GST_ELEMENT_CLASS (sink_parent_class)->change_state)
    return GST_ELEMENT_CLASS (sink_parent_class)->change_state (element);

  return GST_STATE_SUCCESS;
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
837
838
}

839
840
841
842
843
844
/*** GSTALSASRC FUNCTIONS *****************************************************/

static GstAlsa *src_parent_class = NULL;

static GstPadTemplate *
gst_alsa_src_pad_factory (void)
845
{
846
  static GstPadTemplate *template = NULL;
847

848
849
850
851
  if (!template)
    template = gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
                                     gst_alsa_caps (SND_PCM_FORMAT_UNKNOWN, -1, -1),
                                     NULL);
852

853
854
855
856
857
858
  return template;
}
static GstPadTemplate *
gst_alsa_src_request_pad_factory (void)
{
  static GstPadTemplate *template = NULL;
859

860
861
862
863
  if (!template)
    template = gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
                                     gst_alsa_caps (SND_PCM_FORMAT_UNKNOWN, -1, 1),
                                     NULL);
864

865
866
867
868
869
870
  return template;
}
GType
gst_alsa_src_get_type (void)
{
  static GType alsa_src_type = 0;
871

872
873
874
875
876
877
878
879
880
881
882
883
  if (!alsa_src_type) {
    static const GTypeInfo alsa_src_info = {
      sizeof (GstAlsaSrcClass),
      NULL,
      NULL,
      (GClassInitFunc) gst_alsa_src_class_init,
      NULL,
      NULL,
      sizeof (GstAlsaSrc),
      0,
      (GInstanceInitFunc) gst_alsa_src_init,
    };
884

885
886
887
    alsa_src_type = g_type_register_static (GST_TYPE_ALSA, "GstAlsaSrc", &alsa_src_info, 0);
  }
  return alsa_src_type;
888
}
889
890
static void
gst_alsa_src_class_init (GstAlsaSrcClass *klass)
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
891
{
892
893
894
  GObjectClass *object_class;
  GstElementClass *element_class;
  GstAlsaClass *alsa_class;
895

896
897
898
  object_class = (GObjectClass *) klass;
  element_class = (GstElementClass *) klass;
  alsa_class = (GstAlsaClass *) klass;
899

900
901
  if (src_parent_class == NULL)
    src_parent_class = g_type_class_ref (GST_TYPE_ALSA);
902

903
  alsa_class->stream		= SND_PCM_STREAM_CAPTURE;
904
905
  alsa_class->transmit_mmap	= gst_alsa_src_mmap;
  alsa_class->transmit_rw	= gst_alsa_src_read;
906

907
  element_class->change_state	= gst_alsa_src_change_state;
908
909
910
911
912
}
static void
gst_alsa_src_init (GstAlsaSrc *src)
{
  GstAlsa *this = GST_ALSA (src);
913

914
915
916
917
918
919
920
921
922
  this->pad[0] = gst_pad_new_from_template (gst_alsa_src_pad_factory (), "src");
  gst_pad_set_link_function (this->pad[0], gst_alsa_link);
  gst_pad_set_getcaps_function (this->pad[0], gst_alsa_get_caps);
  gst_element_add_pad (GST_ELEMENT (this), this->pad[0]);
  
  this->clock = gst_alsa_clock_new ("alsasrcclock", gst_alsa_src_get_time, this);
  /* we hold a ref to our clock until we're disposed */
  gst_object_ref (GST_OBJECT (this->clock));
  gst_object_sink (GST_OBJECT (this->clock));
Benjamin Otte's avatar
Benjamin Otte committed
923

924
925
  gst_element_set_loop_function (GST_ELEMENT (this), gst_alsa_src_loop);
}
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
static int
gst_alsa_src_mmap (GstAlsa *this, snd_pcm_sframes_t *avail)
{
  snd_pcm_uframes_t offset;
  snd_pcm_channel_area_t *dst;
  const snd_pcm_channel_area_t *src;
  int i, err, width = snd_pcm_format_physical_width (this->format->format);
  GstAlsaSrc *alsa_src = GST_ALSA_SRC (this);

  /* areas points to the memory areas that belong to gstreamer. */
  dst = calloc(this->format->channels, sizeof(snd_pcm_channel_area_t));

  if (((GstElement *) this)->numpads == 1) {
    /* interleaved */
    for (i = 0; i < this->format->channels; i++) {
      dst[i].addr = alsa_src->buf[0]->data;
      dst[i].first = i * width;
      dst[i].step = this->format->channels * width;
    }
  } else {
    /* noninterleaved */
    for (i = 0; i < this->format->channels; i++) {
      dst[i].addr = alsa_src->buf[i]->data;
      dst[i].first = 0;
      dst[i].step = width;
    }
  }

  if ((err = snd_pcm_mmap_begin (this->handle, &src, &offset, avail)) < 0) {
    g_warning ("gstalsa: mmap failed: %s", snd_strerror (err));
    return -1;
  }
  if (*avail > 0 && (err = snd_pcm_areas_copy (dst, 0, src, offset, this->format->channels, *avail, this->format->format)) < 0) {
    snd_pcm_mmap_commit (this->handle, offset, 0);
    g_warning ("gstalsa: data copy failed: %s", snd_strerror (err));
    return -1;
  }
  if ((err = snd_pcm_mmap_commit (this->handle, offset, *avail)) < 0) {
    g_warning ("gstalsa: mmap commit failed: %s", snd_strerror (err));
    return -1;
  }

  return err;
}
static int
gst_alsa_src_read (GstAlsa *this, snd_pcm_sframes_t *avail)
{
  void *channels[this->format->channels];
  int err, i;
  GstAlsaSrc *src = GST_ALSA_SRC (this);

  if (((GstElement *) this)->numpads == 1) {
    /* interleaved */
    err = snd_pcm_readi (this->handle, src->buf[0]->data, *avail);
  } else {
    /* noninterleaved */
    for (i = 0; i < this->format->channels; i++) {
      channels[i] = src->buf[i]->data;
    }
    err = snd_pcm_readn (this->handle, channels, *avail);
  }
  /* error handling */
  if (err < 0) {
    if (err == -EPIPE) {
      gst_alsa_xrun_recovery (this);
      return 0;
    }
    g_warning ("error on data access: %s", snd_strerror (err));
  }
  return err;
}
Benjamin Otte's avatar
Benjamin Otte committed
997
998
static inline gint
gst_alsa_adjust_rate (gint rate, gboolean aggressive)
999
{
Benjamin Otte's avatar
Benjamin Otte committed
1000
  static gint rates[] = { 96000, 48000, 44100, 22050, 8000 };
1001
  gint i;
Benjamin Otte's avatar
Benjamin Otte committed
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020

  if (aggressive)
    return rate;
  
  for (i = 0; i < G_N_ELEMENTS (rates); i--) {
    if (rate > rates[i])
      return rates[i];
  }

  return 0;
}
static gboolean
gst_alsa_src_set_caps (GstAlsaSrc *src, gboolean aggressive)
{
  GstCaps *all_caps, *caps, *walk;
  gint channels, min_channels, max_channels;
  gint rate, min_rate, max_rate;
  gint i, law, endian, width, depth;
  gboolean sign;
1021
1022
  GstAlsa *this = GST_ALSA (src);

Benjamin Otte's avatar
Benjamin Otte committed
1023
1024
1025
  all_caps = gst_alsa_get_caps (this->pad[0], NULL);
  if (all_caps == NULL) return FALSE;
  /* now intersect this with all caps of the peers... */
1026
  for (i = 0; i < GST_ELEMENT (src)->numpads; i++) {
Benjamin Otte's avatar
Benjamin Otte committed
1027
1028
1029
    all_caps = gst_caps_intersect (all_caps, gst_pad_get_caps (this->pad[i]));
    if (all_caps == NULL) {
      GST_DEBUG (GST_CAT_NEGOTIATION, "No compatible caps found in alsasrc (%s)", GST_ELEMENT_NAME (this));
1030
1031
1032
1033
      return FALSE;
    }
  }
  
Benjamin Otte's avatar
Benjamin Otte committed
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
  /* construct caps */
  caps = GST_CAPS_NEW ("alsasrc caps", "audio/raw",
                       "format",      GST_PROPS_STRING ("int"),
		       "law",         GST_PROPS_INT (0),
		       "endianness",  GST_PROPS_INT (G_BYTE_ORDER),
		       "signed",      GST_PROPS_BOOLEAN (TRUE),
		       "width",       GST_PROPS_INT (16),
		       "depth",       GST_PROPS_INT (16),
		       "rate",        GST_PROPS_INT (44100),
		       "channels",    GST_PROPS_INT (1));
  gst_caps_ref (caps);
  gst_caps_sink (caps);

  /* now try to find the best match */
  walk = all_caps;
  while (walk) {
    gst_caps_get (walk, "law", &law, "signed", &sign, "width", &width, "depth", &depth, NULL);
    if (gst_caps_has_property (walk, "endianness")) {
      gst_caps_get_int (walk, "endianness", &endian);
    } else {
      endian = G_BYTE_ORDER;
    }
    gst_caps_set (caps, "law", GST_PROPS_INT (law));
    gst_caps_set (caps, "endianness", GST_PROPS_INT (endian));
    gst_caps_set (caps, "width", GST_PROPS_INT (width));
    gst_caps_set (caps, "depth", GST_PROPS_INT (depth));
    gst_caps_set (caps, "signed", GST_PROPS_BOOLEAN (sign));
  
    gst_props_entry_get_int_range (gst_props_get_entry (GST_CAPS_PROPERTIES (walk), "rate"), &min_rate, &max_rate);
    gst_props_entry_get_int_range (gst_props_get_entry (GST_CAPS_PROPERTIES (walk), "channels"), &min_channels, &max_channels);
    for (rate = max_rate;; rate--) {
      if ((rate = gst_alsa_adjust_rate (rate, aggressive)) < min_rate)
	break;    
      gst_caps_set (caps, "rate", GST_PROPS_INT (rate));
      for (channels = aggressive ? max_channels : MIN (max_channels, 2); channels >= min_channels; channels--) {
        gst_caps_set (caps, "channels", GST_PROPS_INT (channels));
        g_print ("trying new caps: law %d, %ssigned, endianness: %d, width %d, depth %d, channels %d, rate %d\n",
                 law, sign ? "" : "un", endian, width, depth, channels, rate);
        if (gst_pad_try_set_caps (this->pad[0], caps))
          gst_alsa_link (this->pad[0], caps);
      
        if (this->format) {	  
	  /* try to set caps here */
	  return TRUE;
	}
      }
    }
    walk = GST_CAPS_NEXT (walk);
1082
1083
  }

Benjamin Otte's avatar
Benjamin Otte committed
1084
1085
1086
1087
  if (!aggressive)
    return gst_alsa_src_set_caps (src, TRUE);

  return FALSE;
1088
1089
}
/* we transmit buffers of period_size frames */
1090
1091
1092
1093
1094
1095
static void
gst_alsa_src_loop (GstElement *element)
{
  snd_pcm_sframes_t avail, copied;
  gint i;
  GstAlsa *this = GST_ALSA (element);
1096
  GstAlsaSrc *src = GST_ALSA_SRC (element);
1097

1098
1099
  /* set the caps on all pads */
  if (!this->format) {
Benjamin Otte's avatar
Benjamin Otte committed
1100
    if (!gst_alsa_src_set_caps (src, FALSE)) {
1101
1102
      gst_element_error (element, "Could not set caps");
      return;
1103
    }
1104
1105
1106
1107
1108
    /* get the bufferpool going */
    if (src->pool)
      gst_buffer_pool_unref (src->pool);
    src->pool = gst_buffer_pool_get_default (gst_alsa_samples_to_bytes (this, this->period_size), 
                                             2 * element->numpads);
1109
1110
1111
  }

  while ((avail = gst_alsa_update_avail (this)) < this->period_size) {
1112
    if (avail == -EPIPE) continue;
1113
    if (avail < 0) return;
1114
1115
1116
1117
1118
    if (snd_pcm_state(this->handle) != SND_PCM_STATE_RUNNING) {
      if (!gst_alsa_start (this))
	return;
      continue;
    };
1119
1120
1121
1122
    /* wait */
    if (gst_alsa_pcm_wait (this) == FALSE)
      return;
  }
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
  g_assert (avail >= this->period_size);
  /* make sure every pad has a buffer */
  for (i = 0; i < element->numpads; i++) {
    if (!src->buf[i]) {
      src->buf[i] = gst_buffer_new_from_pool (src->pool, 0, 0);
    }
  }
  /* fill buffer with data */
  if ((copied = this->transmit (this, &avail)) <= 0)
    return;
  /* push the buffers out and let them have fun */
  for (i = 0; i < element->numpads; i++) {
    if (!src->buf[i])
1136
      return;
1137
1138
1139
1140
1141
1142
1143
1144
    if (copied != this->period_size)
      GST_BUFFER_SIZE (src->buf[i]) = gst_alsa_samples_to_bytes (this, copied);
    GST_BUFFER_TIMESTAMP (src->buf[i]) = gst_alsa_samples_to_timestamp (this, this->transmitted);
    gst_pad_push (this->pad[i], src->buf[i]);
    src->buf[i] = NULL;
  }
  this->transmitted += copied;
}
1145

1146
1147
1148
1149
static void
gst_alsa_src_flush (GstAlsaSrc *src)
{
  gint i;
1150

1151
1152
1153
1154
  for (i = 0; i < GST_ELEMENT (src)->numpads; i++) { 
    if (src->buf[i]) {
      gst_buffer_unref (src->buf[i]);
      src->buf[i] = NULL;
Benjamin Otte's avatar
Benjamin Otte committed
1155
    }
1156
  }
1157
1158
1159
1160
1161
1162
1163
1164
1165
  if (src->pool) {
    gst_buffer_pool_unref (src->pool);
    src->pool = NULL;
  }
}
static GstElementStateReturn
gst_alsa_src_change_state (GstElement *element)
{
  GstAlsaSrc *src;
1166

1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
  g_return_val_if_fail (element != NULL, FALSE);
  src = GST_ALSA_SRC (element);

  switch (GST_STATE_TRANSITION (element)) {
  case GST_STATE_NULL_TO_READY:
  case GST_STATE_READY_TO_PAUSED:
  case GST_STATE_PAUSED_TO_PLAYING:
  case GST_STATE_PLAYING_TO_PAUSED:
    break;
  case GST_STATE_PAUSED_TO_READY:
    gst_alsa_src_flush (src);
    break;
  case GST_STATE_READY_TO_NULL:
    break;
  default:
    g_assert_not_reached();
1183
  }
1184

Benjamin Otte's avatar
Benjamin Otte committed
1185
1186
  if (GST_ELEMENT_CLASS (src_parent_class)->change_state)
    return GST_ELEMENT_CLASS (src_parent_class)->change_state (element);
1187
1188

  return GST_STATE_SUCCESS;
1189
}
1190

Benjamin Otte's avatar
Benjamin Otte committed
1191
/*** GSTREAMER PAD / QUERY / CONVERSION / STATE FUNCTIONS *********************/
1192
1193
1194
1195

static GstPad *
gst_alsa_request_new_pad (GstElement *element, GstPadTemplate *templ,
                          const gchar *name)
1196
{
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
  GstAlsa *this;
  gint channel = 0;

  g_return_val_if_fail ((this = GST_ALSA (element)), NULL);
  g_return_val_if_fail (!GST_FLAG_IS_SET (element, GST_ALSA_RUNNING), NULL);

  if (name) {
    /* locate the channel number in the requested pad name. to do so look at
       where the % (which begins the %d) is in the template name. */
    channel = (gint) strtol (name + (strchr (templ->name_template, '%') -
                            templ->name_template), NULL, 0);
    if (channel < 1 || channel >= GST_ALSA_MAX_CHANNELS) {
      g_warning ("invalid channel requested. (%d)", channel);
      return NULL;
    }
  }

  /* make sure the requested channel is free. */
  if (channel > 0 || this->pad[channel] != NULL) {
    g_warning ("requested channel %d already in use.", channel);
    return NULL;
  }
1219

1220
1221
1222
1223
1224
1225
1226
1227
1228
  /* if the user doesn't care which channel, find the lowest channel number
     that's free. */
  if (channel == 0) {
    for (channel = 1; channel < GST_ALSA_MAX_CHANNELS; channel++) {
      if (this->pad[channel] != NULL)
        goto found_channel;
    }
    return NULL;
  }
1229

1230
1231
1232
1233
1234
found_channel:
  this->pad[channel] = gst_pad_new_from_template (templ, name);
  gst_pad_set_link_function (this->pad[channel], gst_alsa_link);
  gst_pad_set_getcaps_function (this->pad[channel], gst_alsa_get_caps);
  gst_element_add_pad (GST_ELEMENT (this), this->pad[channel]);
Benjamin Otte's avatar
Benjamin Otte committed
1235
1236
1237
1238
1239
  gst_pad_set_convert_function (this->pad[channel], gst_alsa_pad_convert);
  gst_pad_set_query_function (this->pad[channel], gst_alsa_pad_query);
  gst_pad_set_query_type_function (this->pad[channel], gst_alsa_get_query_types);
  gst_pad_set_formats_function (this->pad[channel], gst_alsa_get_formats);
  
1240
  return this->pad[channel];
1241
1242
}

1243
1244
1245
/* gets the matching alsa format or NULL if none matches */
static GstAlsaFormat *
gst_alsa_get_format (GstCaps *caps)
1246
{
1247
1248
  const gchar *format_name;
  GstAlsaFormat *ret;
1249

1250
1251
  if (!(ret = g_new (GstAlsaFormat, 1)))
    return NULL;
1252

1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
  /* we have to differentiate between int and float formats */
  if (!gst_caps_get_string (caps, "format", &format_name))
    goto error;

  if (strncmp (format_name, "int", 3) == 0) {
    gboolean sign;
    gint width, depth, endianness, law;

    /* extract the needed information from the caps */
    if (!gst_caps_get (caps,
                       "width", &width,
                       "depth", &depth,
                       "law", &law,
                       "signed", &sign,
                       NULL))
        goto error;
	
    /* extract endianness if needed */
    if (width > 8) {
      if (!gst_caps_get (caps,
                         "endianness", &endianness,
                         NULL))
        goto error;
      } else {
      endianness = G_BYTE_ORDER;
Benjamin Otte's avatar
Benjamin Otte committed
1278
    }
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
    
    /* find corresponding alsa format */
    switch (law) {
      case 0: 
	ret->format = snd_pcm_build_linear_format (depth, width, sign ? 0 : 1, endianness == G_LITTLE_ENDIAN ? 0 : 1);
        break;
      case 1: 
        if (width == 8 && depth == 8 && sign == FALSE) {
          ret->format = SND_PCM_FORMAT_MU_LAW;
	  break;
        } else {
          goto error;
Benjamin Otte's avatar
Benjamin Otte committed
1291
        }
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
      case 2: 
        if (width == 8 && depth == 8 && sign == FALSE) {
          ret->format = SND_PCM_FORMAT_A_LAW;
	  break;
        } else {
          goto error;
        }
      default: 
        goto error;
    }
  } else if (strncmp (format_name, "float", 5) == 0) {
    gchar *layout;
    gfloat intercept, slope;

    /* get layout */
    if (!gst_caps_get (caps, "layout", &layout,
                             "intercept", &intercept,
                             "slope", &slope,
                             NULL))
      goto error;
    if (intercept != 0.0f || slope != 1.0f) {
      goto error;
    }
    /* match layout to format wrt to endianness */
    if (strncmp (layout, "gfloat", 6) == 0) {
      if (G_BYTE_ORDER == G_LITTLE_ENDIAN) {
	ret->format = SND_PCM_FORMAT_FLOAT_LE;
      } else if (G_BYTE_ORDER == G_BIG_ENDIAN) {
        ret->format = SND_PCM_FORMAT_FLOAT_BE;
      } else {
        ret->format = SND_PCM_FORMAT_FLOAT;
Benjamin Otte's avatar
Benjamin Otte committed
1323
      }
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
    } else if (strncmp (layout, "gdouble", 7) == 0) {
      if (G_BYTE_ORDER == G_LITTLE_ENDIAN) {
	ret->format = SND_PCM_FORMAT_FLOAT64_LE;
      } else if (G_BYTE_ORDER == G_BIG_ENDIAN) {
        ret->format = SND_PCM_FORMAT_FLOAT64_BE;
      } else {
        ret->format = SND_PCM_FORMAT_FLOAT64;
      }
    } else {
      goto error;
Benjamin Otte's avatar
Benjamin Otte committed
1334
    }
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
  }

  /* get rate and channels */
  if (!gst_caps_get (caps, "rate", &ret->rate,
                           "channels", &ret->channels,
                           NULL))
    goto error;
  
  return ret;
  
error:
  g_free (ret);
  return NULL;
}

static inline gboolean
gst_alsa_formats_match (GstAlsaFormat *one, GstAlsaFormat *two)
{
  if (one == two) return TRUE;
  if (one == NULL || two == NULL) return FALSE;
  return (one->format == two->format) && 
         (one->rate == two->rate) && 
         (one->channels == two->channels);
}
/* get props for a spec */
static GstProps *
gst_alsa_get_props (snd_pcm_format_t format)
{
  if (format == SND_PCM_FORMAT_A_LAW) {
    return gst_props_new ("format", GST_PROPS_STRING ("int"),
                          "law", GST_PROPS_INT(2),
                          "width", GST_PROPS_INT(8),
                          "depth", GST_PROPS_INT(8),
                          "signed", GST_PROPS_BOOLEAN (FALSE),
                          NULL);
  } else if (format == SND_PCM_FORMAT_MU_LAW) {
    return gst_props_new ("format", GST_PROPS_STRING ("int"),
                          "law", GST_PROPS_INT(1),
                          "width", GST_PROPS_INT(8),
                          "depth", GST_PROPS_INT(8),
                          "signed", GST_PROPS_BOOLEAN (FALSE),
                          NULL);
  } else if (snd_pcm_format_linear (format)) {
    /* int */
    GstProps *props = gst_props_new ("format", GST_PROPS_STRING ("int"),
                          "width", GST_PROPS_INT(snd_pcm_format_physical_width (format)),
                          "depth", GST_PROPS_INT(snd_pcm_format_width (format)),
                          "law", GST_PROPS_INT(0),
                          "signed", GST_PROPS_BOOLEAN (snd_pcm_format_signed (format) == 1 ? TRUE : FALSE),
                          NULL);
    /* endianness */
    if (snd_pcm_format_physical_width (format) > 8) {
      switch (snd_pcm_format_little_endian (format)) {
      case 0:
        gst_props_add_entry (props, gst_props_entry_new ("endianness", GST_PROPS_INT (G_BIG_ENDIAN)));
        break;
      case 1:
        gst_props_add_entry (props, gst_props_entry_new ("endianness", GST_PROPS_INT (G_LITTLE_ENDIAN)));
        break;
      default:
        g_warning("ALSA: Unknown byte order in sound driver. Continuing by assuming system byte order.");
        gst_props_add_entry (props, gst_props_entry_new ("endianness", GST_PROPS_INT (G_BYTE_ORDER)));
        break;
Benjamin Otte's avatar
Benjamin Otte committed
1398
      }
1399
    }
1400
1401
1402
1403
1404
    return props;
  } else if (snd_pcm_format_float (format)) {
    /* no float with non-platform endianness */
    if (!snd_pcm_format_cpu_endian (format))
      return NULL;
1405