[MOVED FROM GST-P-FARSIGHT] Cleaned up the code a bit, no use of GST_* and return...
[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. This element is only capable of generating tones.
68  * </entry>
69  * </row>
70  * <row>
71  * <entry>number</entry>
72  * <entry>G_TYPE_INT</entry>
73  * <entry>0-16</entry>
74  * <entry>The event number.</entry>
75  * </row>
76  * <row>
77  * <entry>volume</entry>
78  * <entry>G_TYPE_INT</entry>
79  * <entry>0-36</entry>
80  * <entry>This field describes the power level of the tone, expressed in dBm0
81  * after dropping the sign. Power levels range from 0 to -63 dBm0. The range of
82  * valid DTMF is from 0 to -36 dBm0. Can be omitted if start is set to FALSE.
83  * </entry>
84  * </row>
85  * <row>
86  * <entry>start</entry>
87  * <entry>G_TYPE_BOOLEAN</entry>
88  * <entry>True or False</entry>
89  * <entry>Whether the event is starting or ending.</entry>
90  * </row>
91  * <row>
92  * <entry>method</entry>
93  * <entry>G_TYPE_INT</entry>
94  * <entry>1</entry>
95  * <entry>The method used for sending event, this element will react if this field
96  * is absent or 2.
97  * </entry>
98  * </row>
99  * </tbody>
100  * </tgroup>
101  * </informaltable>
102  * </para>
103  *
104  * <para>For example, the following code informs the pipeline (and in turn, the
105  * DTMFSrc element inside the pipeline) about the start of a DTMF named
106  * event '1' of volume -25 dBm0:
107  * </para>
108  *
109  * <para>
110  * <programlisting>
111  * structure = gst_structure_new ("dtmf-event",
112  *                    "type", G_TYPE_INT, 0,
113  *                    "number", G_TYPE_INT, 1,
114  *                    "volume", G_TYPE_INT, 25,
115  *                    "start", G_TYPE_BOOLEAN, TRUE, NULL);
116  *
117  * event = gst_event_new_custom (GST_EVENT_CUSTOM_UPSTREAM, structure);
118  * gst_element_send_event (pipeline, event);
119  * </programlisting>
120  * </para>
121  *
122  * </refsect2>
123  */
124
125 #ifdef HAVE_CONFIG_H
126 #  include "config.h"
127 #endif
128
129 #include <stdlib.h>
130 #include <string.h>
131 #include <math.h>
132
133 #include <glib.h>
134
135 #ifndef M_PI
136 # define M_PI           3.14159265358979323846  /* pi */
137 #endif
138
139
140 #include "gstdtmfsrc.h"
141
142 #define GST_TONE_DTMF_TYPE_EVENT 0
143 #define DEFAULT_PACKET_INTERVAL  50 /* ms */
144 #define MIN_PACKET_INTERVAL      10 /* ms */
145 #define MAX_PACKET_INTERVAL      50 /* ms */
146 #define SAMPLE_RATE              8000
147 #define SAMPLE_SIZE              16
148 #define CHANNELS                 1
149 #define MIN_EVENT                0
150 #define MAX_EVENT                16
151 #define MIN_VOLUME               0
152 #define MAX_VOLUME               36
153 #define MIN_INTER_DIGIT_INTERVAL 100
154 #define MIN_PULSE_DURATION       250
155 #define MIN_DUTY_CYCLE           (MIN_INTER_DIGIT_INTERVAL + MIN_PULSE_DURATION)
156
157
158 typedef struct st_dtmf_key {
159         char *event_name;
160         int event_encoding;
161         float low_frequency;
162         float high_frequency;
163 } DTMF_KEY;
164
165 static const DTMF_KEY DTMF_KEYS[] = {
166         {"DTMF_KEY_EVENT_0",  0, 941, 1336},
167         {"DTMF_KEY_EVENT_1",  1, 697, 1209},
168         {"DTMF_KEY_EVENT_2",  2, 697, 1336},
169         {"DTMF_KEY_EVENT_3",  3, 697, 1477},
170         {"DTMF_KEY_EVENT_4",  4, 770, 1209},
171         {"DTMF_KEY_EVENT_5",  5, 770, 1336},
172         {"DTMF_KEY_EVENT_6",  6, 770, 1477},
173         {"DTMF_KEY_EVENT_7",  7, 852, 1209},
174         {"DTMF_KEY_EVENT_8",  8, 852, 1336},
175         {"DTMF_KEY_EVENT_9",  9, 852, 1477},
176         {"DTMF_KEY_EVENT_S", 10, 941, 1209},
177         {"DTMF_KEY_EVENT_P", 11, 941, 1477},
178         {"DTMF_KEY_EVENT_A", 12, 697, 1633},
179         {"DTMF_KEY_EVENT_B", 13, 770, 1633},
180         {"DTMF_KEY_EVENT_C", 14, 852, 1633},
181         {"DTMF_KEY_EVENT_D", 15, 941, 1633},
182 };
183
184 #define MAX_DTMF_EVENTS 16
185
186 enum {
187 DTMF_KEY_EVENT_1 = 1,
188 DTMF_KEY_EVENT_2 = 2,
189 DTMF_KEY_EVENT_3 = 3,
190 DTMF_KEY_EVENT_4 = 4,
191 DTMF_KEY_EVENT_5 = 5,
192 DTMF_KEY_EVENT_6 = 6,
193 DTMF_KEY_EVENT_7 = 7,
194 DTMF_KEY_EVENT_8 = 8,
195 DTMF_KEY_EVENT_9 = 9,
196 DTMF_KEY_EVENT_0 = 0,
197 DTMF_KEY_EVENT_STAR = 10,
198 DTMF_KEY_EVENT_POUND = 11,
199 DTMF_KEY_EVENT_A = 12,
200 DTMF_KEY_EVENT_B = 13,
201 DTMF_KEY_EVENT_C = 14,
202 DTMF_KEY_EVENT_D = 15,
203 };
204
205 /* elementfactory information */
206 static const GstElementDetails gst_dtmf_src_details =
207 GST_ELEMENT_DETAILS ("DTMF tone generator",
208     "Source/Audio",
209     "Generates DTMF tones",
210     "Youness Alaoui <youness.alaoui@collabora.co.uk>");
211
212 GST_DEBUG_CATEGORY_STATIC (gst_dtmf_src_debug);
213 #define GST_CAT_DEFAULT gst_dtmf_src_debug
214
215 enum
216 {
217   PROP_0,
218   PROP_INTERVAL,
219 };
220
221 static GstStaticPadTemplate gst_dtmf_src_template =
222 GST_STATIC_PAD_TEMPLATE ("src",
223     GST_PAD_SRC,
224     GST_PAD_ALWAYS,
225     GST_STATIC_CAPS ("audio/x-raw-int, "
226         "width = (int) 16, "
227         "depth = (int) 16, "
228         "endianness = (int) 1234, "
229         "signed = (bool) true, "
230         "rate = (int) 8000, "
231         "channels = (int) 1")
232     );
233
234 static GstElementClass *parent_class = NULL;
235
236 static void gst_dtmf_src_base_init (gpointer g_class);
237 static void gst_dtmf_src_class_init (GstDTMFSrcClass * klass);
238 static void gst_dtmf_src_init (GstDTMFSrc * dtmfsrc, gpointer g_class);
239 static void gst_dtmf_src_finalize (GObject * object);
240
241 GType
242 gst_dtmf_src_get_type (void)
243 {
244   static GType base_src_type = 0;
245
246   if (G_UNLIKELY (base_src_type == 0)) {
247     static const GTypeInfo base_src_info = {
248       sizeof (GstDTMFSrcClass),
249       (GBaseInitFunc) gst_dtmf_src_base_init,
250       NULL,
251       (GClassInitFunc) gst_dtmf_src_class_init,
252       NULL,
253       NULL,
254       sizeof (GstDTMFSrc),
255       0,
256       (GInstanceInitFunc) gst_dtmf_src_init,
257     };
258
259     base_src_type = g_type_register_static (GST_TYPE_ELEMENT,
260         "GstDTMFSrc", &base_src_info, 0);
261   }
262   return base_src_type;
263 }
264
265 static void gst_dtmf_src_set_property (GObject * object, guint prop_id,
266     const GValue * value, GParamSpec * pspec);
267 static void gst_dtmf_src_get_property (GObject * object, guint prop_id,
268     GValue * value, GParamSpec * pspec);
269 static gboolean gst_dtmf_src_handle_event (GstPad * pad, GstEvent * event);
270 static GstStateChangeReturn gst_dtmf_src_change_state (GstElement * element,
271     GstStateChange transition);
272 static void gst_dtmf_src_generate_tone(GstDTMFSrcEvent *event, DTMF_KEY key,
273     float duration, GstBuffer * buffer);
274 static void gst_dtmf_src_push_next_tone_packet (GstDTMFSrc *dtmfsrc);
275 static void gst_dtmf_src_start (GstDTMFSrc *dtmfsrc);
276 static void gst_dtmf_src_stop (GstDTMFSrc *dtmfsrc);
277 static void gst_dtmf_src_add_start_event (GstDTMFSrc *dtmfsrc,
278     gint event_number, gint event_volume);
279 static void gst_dtmf_src_add_stop_event (GstDTMFSrc *dtmfsrc);
280
281 static void
282 gst_dtmf_src_base_init (gpointer g_class)
283 {
284   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
285
286   GST_DEBUG_CATEGORY_INIT (gst_dtmf_src_debug,
287           "dtmfsrc", 0, "dtmfsrc element");
288
289   gst_element_class_add_pad_template (element_class,
290       gst_static_pad_template_get (&gst_dtmf_src_template));
291
292   gst_element_class_set_details (element_class, &gst_dtmf_src_details);
293 }
294
295 static void
296 gst_dtmf_src_class_init (GstDTMFSrcClass * klass)
297 {
298   GObjectClass *gobject_class;
299   GstElementClass *gstelement_class;
300
301   gobject_class = G_OBJECT_CLASS (klass);
302   gstelement_class = GST_ELEMENT_CLASS (klass);
303
304   parent_class = g_type_class_peek_parent (klass);
305
306   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_dtmf_src_finalize);
307   gobject_class->set_property =
308       GST_DEBUG_FUNCPTR (gst_dtmf_src_set_property);
309   gobject_class->get_property =
310       GST_DEBUG_FUNCPTR (gst_dtmf_src_get_property);
311
312   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_INTERVAL,
313       g_param_spec_int ("interval", "Interval between tone packets",
314           "Interval in ms between two tone packets", MIN_PACKET_INTERVAL,
315           MAX_PACKET_INTERVAL, DEFAULT_PACKET_INTERVAL, G_PARAM_READWRITE));
316
317   gstelement_class->change_state =
318       GST_DEBUG_FUNCPTR (gst_dtmf_src_change_state);
319 }
320
321 static void
322 gst_dtmf_src_init (GstDTMFSrc * dtmfsrc, gpointer g_class)
323 {
324   dtmfsrc->srcpad =
325       gst_pad_new_from_static_template (&gst_dtmf_src_template, "src");
326   GST_DEBUG_OBJECT (dtmfsrc, "adding src pad");
327   gst_element_add_pad (GST_ELEMENT (dtmfsrc), dtmfsrc->srcpad);
328
329   gst_pad_set_event_function (dtmfsrc->srcpad, gst_dtmf_src_handle_event);
330
331   dtmfsrc->interval = DEFAULT_PACKET_INTERVAL;
332
333   dtmfsrc->event_queue = g_async_queue_new ();
334   dtmfsrc->last_event = NULL;
335
336   GST_DEBUG_OBJECT (dtmfsrc, "init done");
337 }
338
339 static void
340 gst_dtmf_src_finalize (GObject * object)
341 {
342   GstDTMFSrc *dtmfsrc;
343
344   dtmfsrc = GST_DTMF_SRC (object);
345
346
347   gst_dtmf_src_stop (dtmfsrc);
348
349   if (dtmfsrc->event_queue) {
350     g_async_queue_unref (dtmfsrc->event_queue);
351     dtmfsrc->event_queue = NULL;
352   }
353
354   G_OBJECT_CLASS (parent_class)->finalize (object);
355 }
356
357 static gboolean
358 gst_dtmf_src_handle_dtmf_event (GstDTMFSrc *dtmfsrc,
359         const GstStructure * event_structure)
360 {
361   gint event_type;
362   gboolean start;
363   gint method;
364
365   if (!gst_structure_get_int (event_structure, "type", &event_type) ||
366       !gst_structure_get_boolean (event_structure, "start", &start) ||
367       (start == TRUE && event_type != GST_TONE_DTMF_TYPE_EVENT))
368     goto failure;
369
370   if (gst_structure_get_int (event_structure, "method", &method)) {
371     if (method != 2) {
372       goto failure;
373     }
374   }
375
376   if (start) {
377     gint event_number;
378     gint event_volume;
379
380     if (!gst_structure_get_int (event_structure, "number", &event_number) ||
381             !gst_structure_get_int (event_structure, "volume", &event_volume))
382       goto failure;
383
384     GST_DEBUG_OBJECT (dtmfsrc, "Received start event %d with volume %d",
385             event_number, event_volume);
386     gst_dtmf_src_add_start_event (dtmfsrc, event_number, event_volume);
387   }
388
389   else {
390     GST_DEBUG_OBJECT (dtmfsrc, "Received stop event");
391     gst_dtmf_src_add_stop_event (dtmfsrc);
392   }
393
394   return TRUE;
395 failure:
396   return FALSE;
397 }
398
399 static gboolean
400 gst_dtmf_src_handle_custom_upstream (GstDTMFSrc *dtmfsrc,
401     GstEvent * event)
402 {
403   gboolean result = FALSE;
404   const GstStructure *structure;
405   GstState state;
406   GstStateChangeReturn ret;
407
408   ret = gst_element_get_state (dtmfsrc, &state, NULL, 0);
409   if (ret != GST_STATE_CHANGE_SUCCESS || state != GST_STATE_PLAYING) {
410     GST_DEBUG_OBJECT (dtmfsrc, "Received event while not in PLAYING state");
411     goto ret;
412   }
413
414   GST_DEBUG_OBJECT (dtmfsrc, "Received event is of our interest");
415   structure = gst_event_get_structure (event);
416   if (structure && gst_structure_has_name (structure, "dtmf-event"))
417     result = gst_dtmf_src_handle_dtmf_event (dtmfsrc, structure);
418
419 ret:
420   return result;
421 }
422
423 static gboolean
424 gst_dtmf_src_handle_event (GstPad * pad, GstEvent * event)
425 {
426   GstDTMFSrc *dtmfsrc;
427   gboolean result = FALSE;
428   GstElement *parent = gst_pad_get_parent_element (pad);
429   dtmfsrc = GST_DTMF_SRC (parent);
430
431   GST_DEBUG_OBJECT (dtmfsrc, "Received an event on the src pad");
432   switch (GST_EVENT_TYPE (event)) {
433     case GST_EVENT_CUSTOM_UPSTREAM:
434     {
435       result = gst_dtmf_src_handle_custom_upstream (dtmfsrc, event);
436       break;
437     }
438     /* Ideally this element should not be flushed but let's handle the event
439      * just in case it is */
440     case GST_EVENT_FLUSH_START:
441       gst_dtmf_src_stop (dtmfsrc);
442       result = TRUE;
443       break;
444     case GST_EVENT_FLUSH_STOP:
445       gst_segment_init (&dtmfsrc->segment, GST_FORMAT_TIME);
446       break;
447     case GST_EVENT_NEWSEGMENT:
448       {
449         gboolean update;
450         gdouble rate;
451         GstFormat fmt;
452         gint64 start, stop, position;
453
454         gst_event_parse_new_segment (event, &update, &rate, &fmt, &start,
455             &stop, &position);
456         gst_segment_set_newsegment (&dtmfsrc->segment, update, rate, fmt,
457             start, stop, position);
458       }
459       /* fallthrough */
460     default:
461       result = gst_pad_event_default (pad, event);
462       break;
463   }
464
465   gst_object_unref (parent);
466   gst_event_unref (event);
467   return result;
468 }
469
470 static void
471 gst_dtmf_src_set_property (GObject * object, guint prop_id,
472     const GValue * value, GParamSpec * pspec)
473 {
474   GstDTMFSrc *dtmfsrc;
475
476   dtmfsrc = GST_DTMF_SRC (object);
477
478   switch (prop_id) {
479     case PROP_INTERVAL:
480       dtmfsrc->interval = g_value_get_int (value);
481       break;
482     default:
483       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
484       break;
485   }
486 }
487
488 static void
489 gst_dtmf_src_get_property (GObject * object, guint prop_id, GValue * value,
490     GParamSpec * pspec)
491 {
492   GstDTMFSrc *dtmfsrc;
493
494   dtmfsrc = GST_DTMF_SRC (object);
495
496   switch (prop_id) {
497     case PROP_INTERVAL:
498       g_value_set_uint (value, dtmfsrc->interval);
499       break;
500     default:
501       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
502       break;
503   }
504 }
505
506 static void
507 gst_dtmf_src_set_stream_lock (GstDTMFSrc *dtmfsrc, gboolean lock)
508 {
509    GstEvent *event;
510    GstStructure *structure;
511
512    structure = gst_structure_new ("stream-lock",
513                       "lock", G_TYPE_BOOLEAN, lock, NULL);
514
515    event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_OOB, structure);
516    if (!gst_pad_push_event (dtmfsrc->srcpad, event)) {
517      GST_WARNING_OBJECT (dtmfsrc, "stream-lock event not handled");
518    }
519 }
520
521 static void
522 gst_dtmf_prepare_timestamps (GstDTMFSrc *dtmfsrc)
523 {
524   GstClock *clock;
525
526   clock = gst_element_get_clock (dtmfsrc);
527   if (clock != NULL) {
528     dtmfsrc->timestamp = gst_clock_get_time (clock);
529     gst_object_unref (clock);
530   } else {
531     gchar *dtmf_name = gst_element_get_name (dtmfsrc);
532     GST_ERROR_OBJECT (dtmfsrc, "No clock set for element %s", dtmf_name);
533     dtmfsrc->timestamp = GST_CLOCK_TIME_NONE;
534     g_free (dtmf_name);
535   }
536 }
537
538 static void
539 gst_dtmf_src_start (GstDTMFSrc *dtmfsrc)
540 {
541   GstCaps * caps = gst_pad_get_pad_template_caps (dtmfsrc->srcpad);
542
543   if (!gst_pad_set_caps (dtmfsrc->srcpad, caps))
544     GST_ERROR_OBJECT (dtmfsrc,
545             "Failed to set caps %" GST_PTR_FORMAT " on src pad", caps);
546   else
547     GST_DEBUG_OBJECT (dtmfsrc,
548             "caps %" GST_PTR_FORMAT " set on src pad", caps);
549
550
551   if (!gst_pad_start_task (dtmfsrc->srcpad,
552       (GstTaskFunction) gst_dtmf_src_push_next_tone_packet, dtmfsrc)) {
553     GST_ERROR_OBJECT (dtmfsrc, "Failed to start task on src pad");
554   }
555 }
556
557 static void
558 gst_dtmf_src_stop (GstDTMFSrc *dtmfsrc)
559 {
560   /* Don't forget to release the stream lock */
561   gst_dtmf_src_set_stream_lock (dtmfsrc, FALSE);
562
563
564   /* Flushing the event queue */
565   GstDTMFSrcEvent *event = g_async_queue_try_pop (dtmfsrc->event_queue);
566
567   while (event != NULL) {
568     g_free (event);
569     event = g_async_queue_try_pop (dtmfsrc->event_queue);
570   }
571
572   if (dtmfsrc->last_event) {
573     g_free (dtmfsrc->last_event);
574     dtmfsrc->last_event = NULL;
575   }
576
577   if (!gst_pad_pause_task (dtmfsrc->srcpad)) {
578     GST_ERROR_OBJECT (dtmfsrc, "Failed to pause task on src pad");
579     return;
580   }
581
582 }
583
584 static void
585 gst_dtmf_src_add_start_event (GstDTMFSrc *dtmfsrc, gint event_number,
586     gint event_volume)
587 {
588
589   GstDTMFSrcEvent * event = g_malloc (sizeof(GstDTMFSrcEvent));
590   event->event_type = DTMF_EVENT_TYPE_START;
591   event->sample = 0;
592   event->event_number = CLAMP (event_number, MIN_EVENT, MAX_EVENT);
593   event->volume = CLAMP (event_volume, MIN_VOLUME, MAX_VOLUME);
594
595   g_async_queue_push (dtmfsrc->event_queue, event);
596 }
597
598 static void
599 gst_dtmf_src_add_stop_event (GstDTMFSrc *dtmfsrc)
600 {
601
602   GstDTMFSrcEvent * event = g_malloc (sizeof(GstDTMFSrcEvent));
603   event->event_type = DTMF_EVENT_TYPE_STOP;
604   event->sample = 0;
605   event->event_number = 0;
606   event->volume = 0;
607
608   g_async_queue_push (dtmfsrc->event_queue, event);
609 }
610
611 static void
612 gst_dtmf_src_generate_silence(GstBuffer * buffer, float duration)
613 {
614   gint buf_size;
615
616   /* Create a buffer with data set to 0 */
617   buf_size = ((duration/1000)*SAMPLE_RATE*SAMPLE_SIZE*CHANNELS)/8;
618   GST_BUFFER_SIZE (buffer) = buf_size;
619   GST_BUFFER_MALLOCDATA (buffer) = g_malloc0(buf_size);
620   GST_BUFFER_DATA (buffer) = GST_BUFFER_MALLOCDATA (buffer);
621
622 }
623
624 static void
625 gst_dtmf_src_generate_tone(GstDTMFSrcEvent *event, DTMF_KEY key, float duration,
626     GstBuffer * buffer)
627 {
628   gint16 *p;
629   gint tone_size;
630   double i = 0;
631   double amplitude, f1, f2;
632   double volume_factor;
633
634   /* Create a buffer for the tone */
635   tone_size = ((duration/1000)*SAMPLE_RATE*SAMPLE_SIZE*CHANNELS)/8;
636   GST_BUFFER_SIZE (buffer) = tone_size;
637   GST_BUFFER_MALLOCDATA (buffer) = g_malloc(tone_size);
638   GST_BUFFER_DATA (buffer) = GST_BUFFER_MALLOCDATA (buffer);
639
640   p = (gint16 *) GST_BUFFER_MALLOCDATA (buffer);
641
642   volume_factor = pow (10, (-event->volume) / 20);
643
644   /*
645    * For each sample point we calculate 'x' as the
646    * the amplitude value.
647    */
648   for (i = 0; i < (tone_size / (SAMPLE_SIZE/8)); i++) {
649     /*
650      * We add the fundamental frequencies together.
651      */
652     f1 = sin(2 * M_PI * key.low_frequency * (event->sample / SAMPLE_RATE));
653     f2 = sin(2 * M_PI * key.high_frequency * (event->sample / SAMPLE_RATE));
654
655     amplitude = (f1 + f2) / 2;
656
657     /* Adjust the volume */
658     amplitude *= volume_factor;
659
660     /* Make the [-1:1] interval into a [-32767:32767] interval */
661     amplitude *= 32767;
662
663     /* Store it in the data buffer */
664     *(p++) = (gint16) amplitude;
665
666     (event->sample)++;
667   }
668 }
669
670 static void
671 gst_dtmf_src_wait_for_buffer_ts (GstDTMFSrc *dtmfsrc, GstBuffer * buf)
672 {
673   GstClock *clock;
674
675   clock = gst_element_get_clock (dtmfsrc);
676   if (clock != NULL) {
677     GstClockID clock_id;
678     GstClockReturn clock_ret;
679
680     clock_id = gst_clock_new_single_shot_id (clock, GST_BUFFER_TIMESTAMP (buf));
681     clock_ret = gst_clock_id_wait (clock_id, NULL);
682     if (clock_ret != GST_CLOCK_OK && clock_ret != GST_CLOCK_EARLY) {
683       gchar *clock_name = gst_element_get_name (clock);
684       GST_ERROR_OBJECT (dtmfsrc, "Failed to wait on clock %s", clock_name);
685       g_free (clock_name);
686     }
687     gst_clock_id_unref (clock_id);
688     gst_object_unref (clock);
689   }
690
691   else {
692     gchar *dtmf_name = gst_element_get_name (dtmfsrc);
693     GST_ERROR_OBJECT (dtmfsrc, "No clock set for element %s", dtmf_name);
694     g_free (dtmf_name);
695   }
696 }
697
698
699 static GstBuffer *
700 gst_dtmf_src_create_next_tone_packet (GstDTMFSrc *dtmfsrc,
701     GstDTMFSrcEvent *event)
702 {
703   GstBuffer *buf = NULL;
704   gboolean send_silence = FALSE;
705
706   GST_DEBUG_OBJECT (dtmfsrc, "Creating buffer for tone %s",
707       DTMF_KEYS[event->event_number].event_name);
708
709   /* create buffer to hold the tone */
710   buf = gst_buffer_new ();
711
712   if (event->packet_count * dtmfsrc->interval < MIN_INTER_DIGIT_INTERVAL) {
713     send_silence = TRUE;
714   }
715
716   if (send_silence) {
717     GST_DEBUG_OBJECT (dtmfsrc,  "Generating silence");
718     gst_dtmf_src_generate_silence (buf, dtmfsrc->interval);
719   } else {
720     GST_DEBUG_OBJECT (dtmfsrc,  "Generating tone");
721     gst_dtmf_src_generate_tone(event, DTMF_KEYS[event->event_number],
722         dtmfsrc->interval, buf);
723   }
724   event->packet_count++;
725
726
727   /* timestamp and duration of GstBuffer */
728   GST_BUFFER_DURATION (buf) = dtmfsrc->interval * GST_MSECOND;
729   GST_BUFFER_TIMESTAMP (buf) = dtmfsrc->timestamp;
730   dtmfsrc->timestamp += GST_BUFFER_DURATION (buf);
731
732   /* FIXME: Should we sync to clock ourselves or leave it to sink */
733   gst_dtmf_src_wait_for_buffer_ts (dtmfsrc, buf);
734
735   /* Set caps on the buffer before pushing it */
736   gst_buffer_set_caps (buf, GST_PAD_CAPS (dtmfsrc->srcpad));
737
738   return buf;
739 }
740
741 static void
742 gst_dtmf_src_push_next_tone_packet (GstDTMFSrc *dtmfsrc)
743 {
744   GstBuffer *buf = NULL;
745   GstFlowReturn ret;
746   GstDTMFSrcEvent *event;
747
748   g_async_queue_ref (dtmfsrc->event_queue);
749
750   if (dtmfsrc->last_event == NULL) {
751     event = g_async_queue_pop (dtmfsrc->event_queue);
752
753     if (event->event_type == DTMF_EVENT_TYPE_STOP) {
754       GST_WARNING_OBJECT (dtmfsrc,
755           "Received a DTMF stop event when already stopped");
756     } else if (event->event_type == DTMF_EVENT_TYPE_START) {
757       gst_dtmf_prepare_timestamps (dtmfsrc);
758
759       /* Don't forget to get exclusive access to the stream */
760       gst_dtmf_src_set_stream_lock (dtmfsrc, TRUE);
761
762       event->packet_count = 0;
763       dtmfsrc->last_event = event;
764     }
765   } else if (dtmfsrc->last_event->packet_count  * dtmfsrc->interval >=
766       MIN_DUTY_CYCLE) {
767     event = g_async_queue_try_pop (dtmfsrc->event_queue);
768
769     if (event != NULL) {
770       if (event->event_type == DTMF_EVENT_TYPE_START) {
771         GST_WARNING_OBJECT (dtmfsrc,
772             "Received two consecutive DTMF start events");
773       } else if (event->event_type == DTMF_EVENT_TYPE_STOP) {
774         gst_dtmf_src_set_stream_lock (dtmfsrc, FALSE);
775         g_free (dtmfsrc->last_event);
776         dtmfsrc->last_event = NULL;
777       }
778     }
779   }
780   g_async_queue_unref (dtmfsrc->event_queue);
781
782   if (dtmfsrc->last_event) {
783     buf = gst_dtmf_src_create_next_tone_packet (dtmfsrc, dtmfsrc->last_event);
784
785     gst_buffer_ref(buf);
786
787     GST_DEBUG_OBJECT (dtmfsrc,
788         "pushing buffer on src pad of size %d", GST_BUFFER_SIZE (buf));
789     ret = gst_pad_push (dtmfsrc->srcpad, buf);
790     if (ret != GST_FLOW_OK) {
791       GST_ERROR_OBJECT (dtmfsrc, "Failed to push buffer on src pad");
792     }
793
794     gst_buffer_unref(buf);
795     GST_DEBUG_OBJECT (dtmfsrc, "pushed DTMF tone on src pad");
796   }
797
798 }
799
800 static GstStateChangeReturn
801 gst_dtmf_src_change_state (GstElement * element, GstStateChange transition)
802 {
803   GstDTMFSrc *dtmfsrc;
804   GstStateChangeReturn result;
805   gboolean no_preroll = FALSE;
806
807   dtmfsrc = GST_DTMF_SRC (element);
808
809   switch (transition) {
810     case GST_STATE_CHANGE_READY_TO_PAUSED:
811       gst_segment_init (&dtmfsrc->segment, GST_FORMAT_TIME);
812       gst_pad_push_event (dtmfsrc->srcpad, gst_event_new_new_segment (FALSE,
813               dtmfsrc->segment.rate, dtmfsrc->segment.format,
814               dtmfsrc->segment.start, dtmfsrc->segment.stop,
815               dtmfsrc->segment.time));
816       /* Indicate that we don't do PRE_ROLL */
817       no_preroll = TRUE;
818       break;
819     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
820       gst_dtmf_src_start (dtmfsrc);
821       break;
822     default:
823       break;
824   }
825
826   if ((result =
827           GST_ELEMENT_CLASS (parent_class)->change_state (element,
828               transition)) == GST_STATE_CHANGE_FAILURE)
829     goto failure;
830
831   switch (transition) {
832     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
833       /* Indicate that we don't do PRE_ROLL */
834       gst_dtmf_src_stop (dtmfsrc);
835       no_preroll = TRUE;
836       break;
837     default:
838       break;
839   }
840
841   if (no_preroll && result == GST_STATE_CHANGE_SUCCESS)
842     result = GST_STATE_CHANGE_NO_PREROLL;
843
844   return result;
845
846   /* ERRORS */
847 failure:
848   {
849     GST_ERROR_OBJECT (dtmfsrc, "parent failed state change");
850     return result;
851   }
852 }
853
854 gboolean
855 gst_dtmf_src_plugin_init (GstPlugin * plugin)
856 {
857   return gst_element_register (plugin, "dtmfsrc",
858       GST_RANK_NONE, GST_TYPE_DTMF_SRC);
859 }
860