[MOVED FROM GST-P-FARSIGHT] Clarify the documentation of the "event-type" field when...
[platform/upstream/gstreamer.git] / gst / dtmf / gstdtmfsrc.c
1 /* GStreamer DTMF source
2  *
3  * gstdtmfsrc.c:
4  *
5  * Copyright (C) <2007> Collabora.
6  *   Contact: Youness Alaoui <youness.alaoui@collabora.co.uk>
7  * Copyright (C) <2007> Nokia Corporation.
8  *   Contact: Zeeshan Ali <zeeshan.ali@nokia.com>
9  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
10  *               2000,2005 Wim Taymans <wim@fluendo.com>
11  *
12  * This library is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Library General Public
14  * License as published by the Free Software Foundation; either
15  * version 2 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Library General Public License for more details.
21  *
22  * You should have received a copy of the GNU Library General Public
23  * License along with this library; if not, write to the
24  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25  * Boston, MA 02111-1307, USA.
26  */
27
28 /**
29  * SECTION:element-dtmfsrc
30  * @short_description: Generates DTMF packets
31  *
32  * <refsect2>
33  *
34  * <para>
35  * The DTMFSrc element generates DTMF (ITU-T Q.23 Specification) tone packets on request
36  * from application. The application communicates the beginning and end of a
37  * DTMF event using custom upstream gstreamer events. To report a DTMF event, an
38  * application must send an event of type GST_EVENT_CUSTOM_UPSTREAM, having a
39  * structure of name "dtmf-event" with fields set according to the following
40  * table:
41  * </para>
42  *
43  * <para>
44  * <informaltable>
45  * <tgroup cols='4'>
46  * <colspec colname='Name' />
47  * <colspec colname='Type' />
48  * <colspec colname='Possible values' />
49  * <colspec colname='Purpose' />
50  *
51  * <thead>
52  * <row>
53  * <entry>Name</entry>
54  * <entry>GType</entry>
55  * <entry>Possible values</entry>
56  * <entry>Purpose</entry>
57  * </row>
58  * </thead>
59  *
60  * <tbody>
61  * <row>
62  * <entry>type</entry>
63  * <entry>G_TYPE_INT</entry>
64  * <entry>0-1</entry>
65  * <entry>The application uses this field to specify which of the two methods
66  * specified in RFC 2833 to use. The value should be 0 for tones and 1 for
67  * named events. Tones are specified by their frequencies and events are specied
68  * by their number. This element can only take events as input. Do not confuse
69  * with "method" which specified the output.
70  * </entry>
71  * </row>
72  * <row>
73  * <entry>number</entry>
74  * <entry>G_TYPE_INT</entry>
75  * <entry>0-16</entry>
76  * <entry>The event number.</entry>
77  * </row>
78  * <row>
79  * <entry>volume</entry>
80  * <entry>G_TYPE_INT</entry>
81  * <entry>0-36</entry>
82  * <entry>This field describes the power level of the tone, expressed in dBm0
83  * after dropping the sign. Power levels range from 0 to -63 dBm0. The range of
84  * valid DTMF is from 0 to -36 dBm0. Can be omitted if start is set to FALSE.
85  * </entry>
86  * </row>
87  * <row>
88  * <entry>start</entry>
89  * <entry>G_TYPE_BOOLEAN</entry>
90  * <entry>True or False</entry>
91  * <entry>Whether the event is starting or ending.</entry>
92  * </row>
93  * <row>
94  * <entry>method</entry>
95  * <entry>G_TYPE_INT</entry>
96  * <entry>2</entry>
97  * <entry>The method used for sending event, this element will react if this
98  * field is absent or 2.
99  * </entry>
100  * </row>
101  * </tbody>
102  * </tgroup>
103  * </informaltable>
104  * </para>
105  *
106  * <para>For example, the following code informs the pipeline (and in turn, the
107  * DTMFSrc element inside the pipeline) about the start of a DTMF named
108  * event '1' of volume -25 dBm0:
109  * </para>
110  *
111  * <para>
112  * <programlisting>
113  * structure = gst_structure_new ("dtmf-event",
114  *                    "type", G_TYPE_INT, 1,
115  *                    "number", G_TYPE_INT, 1,
116  *                    "volume", G_TYPE_INT, 25,
117  *                    "start", G_TYPE_BOOLEAN, TRUE, NULL);
118  *
119  * event = gst_event_new_custom (GST_EVENT_CUSTOM_UPSTREAM, structure);
120  * gst_element_send_event (pipeline, event);
121  * </programlisting>
122  * </para>
123  *
124  * </refsect2>
125  */
126
127 #ifdef HAVE_CONFIG_H
128 #  include "config.h"
129 #endif
130
131 #include <stdlib.h>
132 #include <string.h>
133 #include <math.h>
134
135 #include <glib.h>
136
137 #ifndef M_PI
138 # define M_PI           3.14159265358979323846  /* pi */
139 #endif
140
141
142 #include "gstdtmfsrc.h"
143
144 #define GST_TONE_DTMF_TYPE_EVENT 1
145 #define DEFAULT_PACKET_INTERVAL  50 /* ms */
146 #define MIN_PACKET_INTERVAL      10 /* ms */
147 #define MAX_PACKET_INTERVAL      50 /* ms */
148 #define DEFAULT_SAMPLE_RATE      8000
149 #define SAMPLE_SIZE              16
150 #define CHANNELS                 1
151 #define MIN_EVENT                0
152 #define MAX_EVENT                16
153 #define MIN_VOLUME               0
154 #define MAX_VOLUME               36
155 #define MIN_INTER_DIGIT_INTERVAL 100
156 #define MIN_PULSE_DURATION       250
157 #define MIN_DUTY_CYCLE           (MIN_INTER_DIGIT_INTERVAL + MIN_PULSE_DURATION)
158
159
160 typedef struct st_dtmf_key {
161         char *event_name;
162         int event_encoding;
163         float low_frequency;
164         float high_frequency;
165 } DTMF_KEY;
166
167 static const DTMF_KEY DTMF_KEYS[] = {
168         {"DTMF_KEY_EVENT_0",  0, 941, 1336},
169         {"DTMF_KEY_EVENT_1",  1, 697, 1209},
170         {"DTMF_KEY_EVENT_2",  2, 697, 1336},
171         {"DTMF_KEY_EVENT_3",  3, 697, 1477},
172         {"DTMF_KEY_EVENT_4",  4, 770, 1209},
173         {"DTMF_KEY_EVENT_5",  5, 770, 1336},
174         {"DTMF_KEY_EVENT_6",  6, 770, 1477},
175         {"DTMF_KEY_EVENT_7",  7, 852, 1209},
176         {"DTMF_KEY_EVENT_8",  8, 852, 1336},
177         {"DTMF_KEY_EVENT_9",  9, 852, 1477},
178         {"DTMF_KEY_EVENT_S", 10, 941, 1209},
179         {"DTMF_KEY_EVENT_P", 11, 941, 1477},
180         {"DTMF_KEY_EVENT_A", 12, 697, 1633},
181         {"DTMF_KEY_EVENT_B", 13, 770, 1633},
182         {"DTMF_KEY_EVENT_C", 14, 852, 1633},
183         {"DTMF_KEY_EVENT_D", 15, 941, 1633},
184 };
185
186 #define MAX_DTMF_EVENTS 16
187
188 enum {
189 DTMF_KEY_EVENT_1 = 1,
190 DTMF_KEY_EVENT_2 = 2,
191 DTMF_KEY_EVENT_3 = 3,
192 DTMF_KEY_EVENT_4 = 4,
193 DTMF_KEY_EVENT_5 = 5,
194 DTMF_KEY_EVENT_6 = 6,
195 DTMF_KEY_EVENT_7 = 7,
196 DTMF_KEY_EVENT_8 = 8,
197 DTMF_KEY_EVENT_9 = 9,
198 DTMF_KEY_EVENT_0 = 0,
199 DTMF_KEY_EVENT_STAR = 10,
200 DTMF_KEY_EVENT_POUND = 11,
201 DTMF_KEY_EVENT_A = 12,
202 DTMF_KEY_EVENT_B = 13,
203 DTMF_KEY_EVENT_C = 14,
204 DTMF_KEY_EVENT_D = 15,
205 };
206
207 /* elementfactory information */
208 static const GstElementDetails gst_dtmf_src_details =
209 GST_ELEMENT_DETAILS ("DTMF tone generator",
210     "Source/Audio",
211     "Generates DTMF tones",
212     "Youness Alaoui <youness.alaoui@collabora.co.uk>");
213
214 GST_DEBUG_CATEGORY_STATIC (gst_dtmf_src_debug);
215 #define GST_CAT_DEFAULT gst_dtmf_src_debug
216
217 enum
218 {
219   PROP_0,
220   PROP_INTERVAL,
221 };
222
223 static GstStaticPadTemplate gst_dtmf_src_template =
224 GST_STATIC_PAD_TEMPLATE ("src",
225     GST_PAD_SRC,
226     GST_PAD_ALWAYS,
227     GST_STATIC_CAPS ("audio/x-raw-int, "
228         "width = (int) 16, "
229         "depth = (int) 16, "
230         "endianness = (int) " G_STRINGIFY (G_BYTE_ORDER) ", "
231         "signed = (bool) true, "
232         "rate = (int) 8000, "
233         "channels = (int) 1")
234     );
235
236 GST_BOILERPLATE (GstDTMFSrc, gst_dtmf_src, GstBaseSrc, GST_TYPE_BASE_SRC);
237
238 static void gst_dtmf_src_finalize (GObject * object);
239
240 static void gst_dtmf_src_set_property (GObject * object, guint prop_id,
241     const GValue * value, GParamSpec * pspec);
242 static void gst_dtmf_src_get_property (GObject * object, guint prop_id,
243     GValue * value, GParamSpec * pspec);
244 static gboolean gst_dtmf_src_handle_event (GstBaseSrc *src, GstEvent * event);
245 static GstStateChangeReturn gst_dtmf_src_change_state (GstElement * element,
246     GstStateChange transition);
247 static GstFlowReturn gst_dtmf_src_create (GstBaseSrc * basesrc,
248     guint64 offset, guint length, GstBuffer ** buffer);
249 static void gst_dtmf_src_add_start_event (GstDTMFSrc *dtmfsrc,
250     gint event_number, gint event_volume);
251 static void gst_dtmf_src_add_stop_event (GstDTMFSrc *dtmfsrc);
252
253 static gboolean gst_dtmf_src_unlock (GstBaseSrc *src);
254
255 static gboolean gst_dtmf_src_unlock_stop (GstBaseSrc *src);
256 static gboolean gst_dtmf_src_negotiate (GstBaseSrc * basesrc);
257
258 static void
259 gst_dtmf_src_base_init (gpointer g_class)
260 {
261   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
262
263   GST_DEBUG_CATEGORY_INIT (gst_dtmf_src_debug,
264           "dtmfsrc", 0, "dtmfsrc element");
265
266   gst_element_class_add_pad_template (element_class,
267       gst_static_pad_template_get (&gst_dtmf_src_template));
268
269   gst_element_class_set_details (element_class, &gst_dtmf_src_details);
270 }
271
272 static void
273 gst_dtmf_src_class_init (GstDTMFSrcClass * klass)
274 {
275   GObjectClass *gobject_class;
276   GstBaseSrcClass *gstbasesrc_class;
277   GstElementClass *gstelement_class;
278
279   gobject_class = G_OBJECT_CLASS (klass);
280   gstbasesrc_class = GST_BASE_SRC_CLASS (klass);
281   gstelement_class = GST_ELEMENT_CLASS (klass);
282
283
284   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_dtmf_src_finalize);
285   gobject_class->set_property =
286       GST_DEBUG_FUNCPTR (gst_dtmf_src_set_property);
287   gobject_class->get_property =
288       GST_DEBUG_FUNCPTR (gst_dtmf_src_get_property);
289
290   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_INTERVAL,
291       g_param_spec_uint ("interval", "Interval between tone packets",
292           "Interval in ms between two tone packets", MIN_PACKET_INTERVAL,
293           MAX_PACKET_INTERVAL, DEFAULT_PACKET_INTERVAL, G_PARAM_READWRITE));
294
295   gstelement_class->change_state =
296       GST_DEBUG_FUNCPTR (gst_dtmf_src_change_state);
297   gstbasesrc_class->unlock =
298       GST_DEBUG_FUNCPTR (gst_dtmf_src_unlock);
299   gstbasesrc_class->unlock_stop =
300       GST_DEBUG_FUNCPTR (gst_dtmf_src_unlock_stop);
301
302   gstbasesrc_class->event =
303       GST_DEBUG_FUNCPTR (gst_dtmf_src_handle_event);
304   gstbasesrc_class->create =
305       GST_DEBUG_FUNCPTR (gst_dtmf_src_create);
306   gstbasesrc_class->negotiate =
307       GST_DEBUG_FUNCPTR (gst_dtmf_src_negotiate);
308 }
309
310
311 static void
312 gst_dtmf_src_init (GstDTMFSrc * dtmfsrc, GstDTMFSrcClass *g_class)
313 {
314   /* we operate in time */
315   gst_base_src_set_format (GST_BASE_SRC (dtmfsrc), GST_FORMAT_TIME);
316   gst_base_src_set_live (GST_BASE_SRC (dtmfsrc), TRUE);
317
318   dtmfsrc->interval = DEFAULT_PACKET_INTERVAL;
319
320   dtmfsrc->event_queue = g_async_queue_new ();
321   dtmfsrc->last_event = NULL;
322
323   dtmfsrc->sample_rate = DEFAULT_SAMPLE_RATE;
324
325   GST_DEBUG_OBJECT (dtmfsrc, "init done");
326 }
327
328 static void
329 gst_dtmf_src_finalize (GObject * object)
330 {
331   GstDTMFSrc *dtmfsrc;
332
333   dtmfsrc = GST_DTMF_SRC (object);
334
335   if (dtmfsrc->event_queue) {
336     g_async_queue_unref (dtmfsrc->event_queue);
337     dtmfsrc->event_queue = NULL;
338   }
339
340   G_OBJECT_CLASS (parent_class)->finalize (object);
341 }
342
343 static gboolean
344 gst_dtmf_src_handle_dtmf_event (GstDTMFSrc *dtmfsrc,
345         const GstStructure * event_structure)
346 {
347   gint event_type;
348   gboolean start;
349   gint method;
350
351   if (!gst_structure_get_int (event_structure, "type", &event_type) ||
352       !gst_structure_get_boolean (event_structure, "start", &start) ||
353       (start == TRUE && event_type != GST_TONE_DTMF_TYPE_EVENT))
354     goto failure;
355
356   if (gst_structure_get_int (event_structure, "method", &method)) {
357     if (method != 2) {
358       goto failure;
359     }
360   }
361
362   if (start) {
363     gint event_number;
364     gint event_volume;
365
366     if (!gst_structure_get_int (event_structure, "number", &event_number) ||
367             !gst_structure_get_int (event_structure, "volume", &event_volume))
368       goto failure;
369
370     GST_DEBUG_OBJECT (dtmfsrc, "Received start event %d with volume %d",
371             event_number, event_volume);
372     gst_dtmf_src_add_start_event (dtmfsrc, event_number, event_volume);
373   }
374
375   else {
376     GST_DEBUG_OBJECT (dtmfsrc, "Received stop event");
377     gst_dtmf_src_add_stop_event (dtmfsrc);
378   }
379
380   return TRUE;
381 failure:
382   return FALSE;
383 }
384
385 static gboolean
386 gst_dtmf_src_handle_custom_upstream (GstDTMFSrc *dtmfsrc,
387     GstEvent * event)
388 {
389   gboolean result = FALSE;
390   const GstStructure *structure;
391   GstState state;
392   GstStateChangeReturn ret;
393
394   ret = gst_element_get_state (GST_ELEMENT (dtmfsrc), &state, NULL, 0);
395   if (ret != GST_STATE_CHANGE_SUCCESS || state != GST_STATE_PLAYING) {
396     GST_DEBUG_OBJECT (dtmfsrc, "Received event while not in PLAYING state");
397     goto ret;
398   }
399
400   GST_DEBUG_OBJECT (dtmfsrc, "Received event is of our interest");
401   structure = gst_event_get_structure (event);
402   if (structure && gst_structure_has_name (structure, "dtmf-event"))
403     result = gst_dtmf_src_handle_dtmf_event (dtmfsrc, structure);
404
405 ret:
406   return result;
407 }
408
409 static gboolean
410 gst_dtmf_src_handle_event (GstBaseSrc * src, GstEvent * event)
411 {
412   GstDTMFSrc *dtmfsrc;
413   gboolean result = FALSE;
414
415   dtmfsrc = GST_DTMF_SRC (src);
416
417   GST_DEBUG_OBJECT (dtmfsrc, "Received an event on the src pad");
418   if (GST_EVENT_TYPE (event) == GST_EVENT_CUSTOM_UPSTREAM) {
419     result = gst_dtmf_src_handle_custom_upstream (dtmfsrc, event);
420   }
421
422   return result;
423 }
424
425 static void
426 gst_dtmf_src_set_property (GObject * object, guint prop_id,
427     const GValue * value, GParamSpec * pspec)
428 {
429   GstDTMFSrc *dtmfsrc;
430
431   dtmfsrc = GST_DTMF_SRC (object);
432
433   switch (prop_id) {
434     case PROP_INTERVAL:
435       dtmfsrc->interval = g_value_get_uint (value);
436       break;
437     default:
438       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
439       break;
440   }
441 }
442
443 static void
444 gst_dtmf_src_get_property (GObject * object, guint prop_id, GValue * value,
445     GParamSpec * pspec)
446 {
447   GstDTMFSrc *dtmfsrc;
448
449   dtmfsrc = GST_DTMF_SRC (object);
450
451   switch (prop_id) {
452     case PROP_INTERVAL:
453       g_value_set_uint (value, dtmfsrc->interval);
454       break;
455     default:
456       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
457       break;
458   }
459 }
460
461 static void
462 gst_dtmf_src_set_stream_lock (GstDTMFSrc *dtmfsrc, gboolean lock)
463 {
464    GstPad *srcpad = GST_BASE_SRC_PAD (dtmfsrc);
465    GstEvent *event;
466    GstStructure *structure;
467
468    structure = gst_structure_new ("stream-lock",
469                       "lock", G_TYPE_BOOLEAN, lock, NULL);
470
471    event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_OOB, structure);
472    if (!gst_pad_push_event (srcpad, event)) {
473      GST_WARNING_OBJECT (dtmfsrc, "stream-lock event not handled");
474    }
475 }
476
477 static void
478 gst_dtmf_prepare_timestamps (GstDTMFSrc *dtmfsrc)
479 {
480   GstClock *clock;
481   GstClockTime base_time;
482
483   base_time = gst_element_get_base_time (GST_ELEMENT (dtmfsrc));
484
485   clock = gst_element_get_clock (GST_ELEMENT (dtmfsrc));
486   if (clock != NULL) {
487 #ifdef MAEMO_BROKEN
488     dtmfsrc->timestamp = gst_clock_get_time (clock);
489 #else
490     dtmfsrc->timestamp = gst_clock_get_time (clock) - base_time;
491 #endif
492     gst_object_unref (clock);
493   } else {
494     gchar *dtmf_name = gst_element_get_name (dtmfsrc);
495     GST_ERROR_OBJECT (dtmfsrc, "No clock set for element %s", dtmf_name);
496     dtmfsrc->timestamp = GST_CLOCK_TIME_NONE;
497     g_free (dtmf_name);
498   }
499 }
500
501 static void
502 gst_dtmf_src_add_start_event (GstDTMFSrc *dtmfsrc, gint event_number,
503     gint event_volume)
504 {
505
506   GstDTMFSrcEvent * event = g_malloc (sizeof(GstDTMFSrcEvent));
507   event->event_type = DTMF_EVENT_TYPE_START;
508   event->sample = 0;
509   event->event_number = CLAMP (event_number, MIN_EVENT, MAX_EVENT);
510   event->volume = CLAMP (event_volume, MIN_VOLUME, MAX_VOLUME);
511
512   g_async_queue_push (dtmfsrc->event_queue, event);
513 }
514
515 static void
516 gst_dtmf_src_add_stop_event (GstDTMFSrc *dtmfsrc)
517 {
518
519   GstDTMFSrcEvent * event = g_malloc (sizeof(GstDTMFSrcEvent));
520   event->event_type = DTMF_EVENT_TYPE_STOP;
521   event->sample = 0;
522   event->event_number = 0;
523   event->volume = 0;
524
525   g_async_queue_push (dtmfsrc->event_queue, event);
526 }
527
528 static void
529 gst_dtmf_src_generate_silence(GstBuffer * buffer, float duration,
530     gint sample_rate)
531 {
532   gint buf_size;
533
534   /* Create a buffer with data set to 0 */
535   buf_size = ((duration/1000)*sample_rate*SAMPLE_SIZE*CHANNELS)/8;
536   GST_BUFFER_SIZE (buffer) = buf_size;
537   GST_BUFFER_MALLOCDATA (buffer) = g_malloc0(buf_size);
538   GST_BUFFER_DATA (buffer) = GST_BUFFER_MALLOCDATA (buffer);
539
540 }
541
542 static void
543 gst_dtmf_src_generate_tone(GstDTMFSrcEvent *event, DTMF_KEY key, float duration,
544     GstBuffer * buffer, gint sample_rate)
545 {
546   gint16 *p;
547   gint tone_size;
548   double i = 0;
549   double amplitude, f1, f2;
550   double volume_factor;
551
552   /* Create a buffer for the tone */
553   tone_size = ((duration/1000)*sample_rate*SAMPLE_SIZE*CHANNELS)/8;
554   GST_BUFFER_SIZE (buffer) = tone_size;
555   GST_BUFFER_MALLOCDATA (buffer) = g_malloc(tone_size);
556   GST_BUFFER_DATA (buffer) = GST_BUFFER_MALLOCDATA (buffer);
557
558   p = (gint16 *) GST_BUFFER_MALLOCDATA (buffer);
559
560   volume_factor = pow (10, (-event->volume) / 20);
561
562   /*
563    * For each sample point we calculate 'x' as the
564    * the amplitude value.
565    */
566   for (i = 0; i < (tone_size / (SAMPLE_SIZE/8)); i++) {
567     /*
568      * We add the fundamental frequencies together.
569      */
570     f1 = sin(2 * M_PI * key.low_frequency * (event->sample / sample_rate));
571     f2 = sin(2 * M_PI * key.high_frequency * (event->sample / sample_rate));
572
573     amplitude = (f1 + f2) / 2;
574
575     /* Adjust the volume */
576     amplitude *= volume_factor;
577
578     /* Make the [-1:1] interval into a [-32767:32767] interval */
579     amplitude *= 32767;
580
581     /* Store it in the data buffer */
582     *(p++) = (gint16) amplitude;
583
584     (event->sample)++;
585   }
586 }
587
588
589
590 static GstBuffer *
591 gst_dtmf_src_create_next_tone_packet (GstDTMFSrc *dtmfsrc,
592     GstDTMFSrcEvent *event)
593 {
594   GstBuffer *buf = NULL;
595   gboolean send_silence = FALSE;
596   GstPad *srcpad = GST_BASE_SRC_PAD (dtmfsrc);
597
598   GST_DEBUG_OBJECT (dtmfsrc, "Creating buffer for tone %s",
599       DTMF_KEYS[event->event_number].event_name);
600
601   /* create buffer to hold the tone */
602   buf = gst_buffer_new ();
603
604   if (event->packet_count * dtmfsrc->interval < MIN_INTER_DIGIT_INTERVAL) {
605     send_silence = TRUE;
606   }
607
608   if (send_silence) {
609     GST_DEBUG_OBJECT (dtmfsrc,  "Generating silence");
610     gst_dtmf_src_generate_silence (buf, dtmfsrc->interval,
611         dtmfsrc->sample_rate);
612   } else {
613     GST_DEBUG_OBJECT (dtmfsrc,  "Generating tone");
614     gst_dtmf_src_generate_tone(event, DTMF_KEYS[event->event_number],
615         dtmfsrc->interval, buf, dtmfsrc->sample_rate);
616   }
617   event->packet_count++;
618
619
620   /* timestamp and duration of GstBuffer */
621   GST_BUFFER_DURATION (buf) = dtmfsrc->interval * GST_MSECOND;
622   GST_BUFFER_TIMESTAMP (buf) = dtmfsrc->timestamp;
623   dtmfsrc->timestamp += GST_BUFFER_DURATION (buf);
624
625   /* Set caps on the buffer before pushing it */
626   gst_buffer_set_caps (buf, GST_PAD_CAPS (srcpad));
627
628   return buf;
629 }
630
631 static GstFlowReturn
632 gst_dtmf_src_create (GstBaseSrc * basesrc, guint64 offset,
633     guint length, GstBuffer ** buffer)
634 {
635   GstBuffer *buf = NULL;
636   GstDTMFSrcEvent *event;
637   GstDTMFSrc * dtmfsrc;
638   GstClock *clock;
639   GstClockID *clockid;
640   GstClockReturn clockret;
641
642   dtmfsrc = GST_DTMF_SRC (basesrc);
643
644   do {
645
646     if (dtmfsrc->last_event == NULL) {
647       GST_DEBUG_OBJECT (dtmfsrc, "popping");
648       event = g_async_queue_pop (dtmfsrc->event_queue);
649
650       GST_DEBUG_OBJECT (dtmfsrc, "popped %d", event->event_type);
651
652       switch (event->event_type) {
653         case DTMF_EVENT_TYPE_STOP:
654           GST_WARNING_OBJECT (dtmfsrc,
655               "Received a DTMF stop event when already stopped");
656           break;
657         case DTMF_EVENT_TYPE_START:
658           gst_dtmf_prepare_timestamps (dtmfsrc);
659
660           /* Don't forget to get exclusive access to the stream */
661           gst_dtmf_src_set_stream_lock (dtmfsrc, TRUE);
662
663           event->packet_count = 0;
664           dtmfsrc->last_event = event;
665           event = NULL;
666           break;
667         case DTMF_EVENT_TYPE_PAUSE_TASK:
668           /*
669            * We're pushing it back because it has to stay in there until
670            * the task is really paused (and the queue will then be flushed)
671            */
672           GST_DEBUG_OBJECT (dtmfsrc, "pushing pause_task...");
673           GST_OBJECT_LOCK (dtmfsrc);
674           if (dtmfsrc->paused) {
675             g_async_queue_push (dtmfsrc->event_queue, event);
676             goto paused_locked;
677           }
678           GST_OBJECT_UNLOCK (dtmfsrc);
679           break;
680       }
681       if (event)
682         g_free (event);
683     } else if (dtmfsrc->last_event->packet_count  * dtmfsrc->interval >=
684         MIN_DUTY_CYCLE) {
685       event = g_async_queue_try_pop (dtmfsrc->event_queue);
686
687       if (event != NULL) {
688
689         switch (event->event_type) {
690           case DTMF_EVENT_TYPE_START:
691             GST_WARNING_OBJECT (dtmfsrc,
692                 "Received two consecutive DTMF start events");
693             break;
694           case DTMF_EVENT_TYPE_STOP:
695             gst_dtmf_src_set_stream_lock (dtmfsrc, FALSE);
696
697             g_free (dtmfsrc->last_event);
698             dtmfsrc->last_event = NULL;
699             break;
700           case DTMF_EVENT_TYPE_PAUSE_TASK:
701             /*
702              * We're pushing it back because it has to stay in there until
703              * the task is really paused (and the queue will then be flushed)
704              */
705             GST_DEBUG_OBJECT (dtmfsrc, "pushing pause_task...");
706
707             GST_OBJECT_LOCK (dtmfsrc);
708             if (dtmfsrc->paused) {
709               g_async_queue_push (dtmfsrc->event_queue, event);
710               goto paused_locked;
711             }
712             GST_OBJECT_UNLOCK (dtmfsrc);
713
714             break;
715         }
716         g_free (event);
717       }
718     }
719   } while (dtmfsrc->last_event == NULL);
720
721   GST_DEBUG_OBJECT (dtmfsrc, "end event check, now wait for the proper time");
722
723   clock = gst_element_get_clock (GST_ELEMENT (basesrc));
724
725 #ifdef MAEMO_BROKEN
726   clockid = gst_clock_new_single_shot_id (clock, dtmfsrc->timestamp);
727 #else
728   clockid = gst_clock_new_single_shot_id (clock, dtmfsrc->timestamp +
729       gst_element_get_base_time (GST_ELEMENT (dtmfsrc)));
730 #endif
731   gst_object_unref (clock);
732
733   GST_OBJECT_LOCK (dtmfsrc);
734   if (!dtmfsrc->paused) {
735     dtmfsrc->clockid = clockid;
736     GST_OBJECT_UNLOCK (dtmfsrc);
737
738     clockret = gst_clock_id_wait (clockid, NULL);
739
740     GST_OBJECT_LOCK (dtmfsrc);
741     if (dtmfsrc->paused)
742       clockret = GST_CLOCK_UNSCHEDULED;
743   } else  {
744     clockret = GST_CLOCK_UNSCHEDULED;
745   }
746   gst_clock_id_unref (clockid);
747   dtmfsrc->clockid = NULL;
748   GST_OBJECT_UNLOCK (dtmfsrc);
749
750   if (clockret == GST_CLOCK_UNSCHEDULED) {
751     goto paused;
752   }
753
754   buf = gst_dtmf_src_create_next_tone_packet (dtmfsrc, dtmfsrc->last_event);
755
756   GST_DEBUG_OBJECT (dtmfsrc, "Created buffer of size %d", GST_BUFFER_SIZE (buf));
757   *buffer = buf;
758
759   GST_DEBUG_OBJECT (dtmfsrc, "returning a buffer");
760   return GST_FLOW_OK;
761
762  paused_locked:
763   GST_OBJECT_UNLOCK (dtmfsrc);
764
765  paused:
766
767   if (dtmfsrc->last_event) {
768     GST_DEBUG_OBJECT (dtmfsrc, "Stopping current event");
769     /* Don't forget to release the stream lock */
770     gst_dtmf_src_set_stream_lock (dtmfsrc, FALSE);
771     g_free (dtmfsrc->last_event);
772     dtmfsrc->last_event = NULL;
773   }
774
775   return GST_FLOW_WRONG_STATE;
776
777 }
778
779 static gboolean
780 gst_dtmf_src_unlock (GstBaseSrc *src) {
781   GstDTMFSrc *dtmfsrc = GST_DTMF_SRC (src);
782   GstDTMFSrcEvent *event = NULL;
783
784   GST_DEBUG_OBJECT (dtmfsrc, "Called unlock");
785
786   GST_OBJECT_LOCK (dtmfsrc);
787   dtmfsrc->paused = TRUE;
788   if (dtmfsrc->clockid) {
789     gst_clock_id_unschedule (dtmfsrc->clockid);
790   }
791   GST_OBJECT_UNLOCK (dtmfsrc);
792
793   GST_DEBUG_OBJECT (dtmfsrc, "Pushing the PAUSE_TASK event on unlock request");
794   event = g_malloc (sizeof(GstDTMFSrcEvent));
795   event->event_type = DTMF_EVENT_TYPE_PAUSE_TASK;
796   g_async_queue_push (dtmfsrc->event_queue, event);
797
798   return TRUE;
799 }
800
801
802 static gboolean
803 gst_dtmf_src_unlock_stop (GstBaseSrc *src) {
804   GstDTMFSrc *dtmfsrc = GST_DTMF_SRC (src);
805
806   GST_DEBUG_OBJECT (dtmfsrc, "Unlock stopped");
807
808   GST_OBJECT_LOCK (dtmfsrc);
809   dtmfsrc->paused = FALSE;
810   GST_OBJECT_UNLOCK (dtmfsrc);
811
812   return TRUE;
813 }
814
815
816 static gboolean
817 gst_dtmf_src_negotiate (GstBaseSrc * basesrc)
818 {
819   GstCaps *srccaps, *peercaps;
820   GstDTMFSrc *dtmfsrc = GST_DTMF_SRC (basesrc);
821   gboolean ret = FALSE;
822
823   srccaps = gst_caps_new_simple ("audio/x-raw-int",
824       "width", G_TYPE_INT, 16,
825       "depth", G_TYPE_INT, 16,
826       "endianness", G_TYPE_INT, G_BYTE_ORDER,
827       "signed", G_TYPE_BOOLEAN, TRUE,
828       "channels", G_TYPE_INT, 1,
829       NULL);
830
831   peercaps = gst_pad_peer_get_caps (GST_BASE_SRC_PAD (basesrc));
832
833   if (peercaps == NULL) {
834     /* no peer caps, just add the other properties */
835     gst_caps_set_simple (srccaps,
836         "rate", G_TYPE_INT, dtmfsrc->sample_rate,
837         NULL);
838   } else {
839     GstStructure *s;
840     gint sample_rate;
841     GstCaps *temp = NULL;
842
843     /* peer provides caps we can use to fixate, intersect. This always returns a
844      * writable caps. */
845     temp = gst_caps_intersect (srccaps, peercaps);
846     gst_caps_unref (srccaps);
847     gst_caps_unref (peercaps);
848
849     if (!temp) {
850       GST_DEBUG_OBJECT (dtmfsrc, "Could not get intersection with peer caps");
851       return FALSE;
852     }
853
854     if (gst_caps_is_empty (temp)) {
855       GST_DEBUG_OBJECT (dtmfsrc, "Intersection with peer caps is empty");
856       gst_caps_unref (temp);
857       return FALSE;
858     }
859
860     /* now fixate, start by taking the first caps */
861     gst_caps_truncate (temp);
862     srccaps = temp;
863
864     /* get first structure */
865     s = gst_caps_get_structure (srccaps, 0);
866
867     if (gst_structure_get_int (s, "rate", &sample_rate))
868     {
869       dtmfsrc->sample_rate = sample_rate;
870       GST_LOG_OBJECT (dtmfsrc, "using rate from caps %d",
871           dtmfsrc->sample_rate);
872     } else {
873       GST_LOG_OBJECT (dtmfsrc, "using existing rate %d",
874           dtmfsrc->sample_rate);
875     }
876     gst_structure_set (s, "rate", G_TYPE_INT, dtmfsrc->sample_rate,
877         NULL);
878   }
879
880   ret = gst_pad_set_caps (GST_BASE_SRC_PAD (basesrc), srccaps);
881
882   gst_caps_unref (srccaps);
883
884   return ret;
885 }
886
887 static GstStateChangeReturn
888 gst_dtmf_src_change_state (GstElement * element, GstStateChange transition)
889 {
890   GstDTMFSrc *dtmfsrc;
891   GstStateChangeReturn result;
892   gboolean no_preroll = FALSE;
893   GstDTMFSrcEvent *event = NULL;
894
895   dtmfsrc = GST_DTMF_SRC (element);
896
897   switch (transition) {
898     case GST_STATE_CHANGE_READY_TO_PAUSED:
899       /* Flushing the event queue */
900       event = g_async_queue_try_pop (dtmfsrc->event_queue);
901
902       while (event != NULL) {
903         g_free (event);
904         event = g_async_queue_try_pop (dtmfsrc->event_queue);
905       }
906       no_preroll = TRUE;
907       break;
908     default:
909       break;
910   }
911
912   if ((result =
913           GST_ELEMENT_CLASS (parent_class)->change_state (element,
914               transition)) == GST_STATE_CHANGE_FAILURE)
915     goto failure;
916
917   switch (transition) {
918     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
919       no_preroll = TRUE;
920       break;
921     case GST_STATE_CHANGE_PAUSED_TO_READY:
922       GST_DEBUG_OBJECT (dtmfsrc, "Flushing event queue");
923       /* Flushing the event queue */
924       event = g_async_queue_try_pop (dtmfsrc->event_queue);
925
926       while (event != NULL) {
927         g_free (event);
928         event = g_async_queue_try_pop (dtmfsrc->event_queue);
929       }
930
931       break;
932     default:
933       break;
934   }
935
936   if (no_preroll && result == GST_STATE_CHANGE_SUCCESS)
937     result = GST_STATE_CHANGE_NO_PREROLL;
938
939   return result;
940
941   /* ERRORS */
942 failure:
943   {
944     GST_ERROR_OBJECT (dtmfsrc, "parent failed state change");
945     return result;
946   }
947 }
948
949 gboolean
950 gst_dtmf_src_plugin_init (GstPlugin * plugin)
951 {
952   return gst_element_register (plugin, "dtmfsrc",
953       GST_RANK_NONE, GST_TYPE_DTMF_SRC);
954 }
955