[MOVED FROM GST-P-FARSIGHT] Take rate from the peers caps if possible
[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 named events.
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>2</entry>
95  * <entry>The method used for sending event, this element will react if this
96  * field 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, 1,
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 1
143 #define DEFAULT_PACKET_INTERVAL  50 /* ms */
144 #define MIN_PACKET_INTERVAL      10 /* ms */
145 #define MAX_PACKET_INTERVAL      50 /* ms */
146 #define DEFAULT_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) " G_STRINGIFY (G_BYTE_ORDER) ", "
229         "signed = (bool) true, "
230         "rate = (int) 8000, "
231         "channels = (int) 1")
232     );
233
234 GST_BOILERPLATE (GstDTMFSrc, gst_dtmf_src, GstBaseSrc, GST_TYPE_BASE_SRC);
235
236 static void gst_dtmf_src_finalize (GObject * object);
237
238 static void gst_dtmf_src_set_property (GObject * object, guint prop_id,
239     const GValue * value, GParamSpec * pspec);
240 static void gst_dtmf_src_get_property (GObject * object, guint prop_id,
241     GValue * value, GParamSpec * pspec);
242 static gboolean gst_dtmf_src_handle_event (GstBaseSrc *src, GstEvent * event);
243 static GstStateChangeReturn gst_dtmf_src_change_state (GstElement * element,
244     GstStateChange transition);
245 static GstFlowReturn gst_dtmf_src_create (GstBaseSrc * basesrc,
246     guint64 offset, guint length, GstBuffer ** buffer);
247 static void gst_dtmf_src_add_start_event (GstDTMFSrc *dtmfsrc,
248     gint event_number, gint event_volume);
249 static void gst_dtmf_src_add_stop_event (GstDTMFSrc *dtmfsrc);
250
251 static gboolean gst_dtmf_src_unlock (GstBaseSrc *src);
252
253 static gboolean gst_dtmf_src_unlock_stop (GstBaseSrc *src);
254 static gboolean gst_dtmf_src_negotiate (GstBaseSrc * basesrc);
255
256 static void
257 gst_dtmf_src_base_init (gpointer g_class)
258 {
259   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
260
261   GST_DEBUG_CATEGORY_INIT (gst_dtmf_src_debug,
262           "dtmfsrc", 0, "dtmfsrc element");
263
264   gst_element_class_add_pad_template (element_class,
265       gst_static_pad_template_get (&gst_dtmf_src_template));
266
267   gst_element_class_set_details (element_class, &gst_dtmf_src_details);
268 }
269
270 static void
271 gst_dtmf_src_class_init (GstDTMFSrcClass * klass)
272 {
273   GObjectClass *gobject_class;
274   GstBaseSrcClass *gstbasesrc_class;
275   GstElementClass *gstelement_class;
276
277   gobject_class = G_OBJECT_CLASS (klass);
278   gstbasesrc_class = GST_BASE_SRC_CLASS (klass);
279   gstelement_class = GST_ELEMENT_CLASS (klass);
280
281
282   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_dtmf_src_finalize);
283   gobject_class->set_property =
284       GST_DEBUG_FUNCPTR (gst_dtmf_src_set_property);
285   gobject_class->get_property =
286       GST_DEBUG_FUNCPTR (gst_dtmf_src_get_property);
287
288   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_INTERVAL,
289       g_param_spec_uint ("interval", "Interval between tone packets",
290           "Interval in ms between two tone packets", MIN_PACKET_INTERVAL,
291           MAX_PACKET_INTERVAL, DEFAULT_PACKET_INTERVAL, G_PARAM_READWRITE));
292
293   gstelement_class->change_state =
294       GST_DEBUG_FUNCPTR (gst_dtmf_src_change_state);
295   gstbasesrc_class->unlock =
296       GST_DEBUG_FUNCPTR (gst_dtmf_src_unlock);
297   gstbasesrc_class->unlock_stop =
298       GST_DEBUG_FUNCPTR (gst_dtmf_src_unlock_stop);
299
300   gstbasesrc_class->event =
301       GST_DEBUG_FUNCPTR (gst_dtmf_src_handle_event);
302   gstbasesrc_class->create =
303       GST_DEBUG_FUNCPTR (gst_dtmf_src_create);
304   gstbasesrc_class->negotiate =
305       GST_DEBUG_FUNCPTR (gst_dtmf_src_negotiate);
306 }
307
308
309 static void
310 gst_dtmf_src_init (GstDTMFSrc * dtmfsrc, GstDTMFSrcClass *g_class)
311 {
312   /* we operate in time */
313   gst_base_src_set_format (GST_BASE_SRC (dtmfsrc), GST_FORMAT_TIME);
314   gst_base_src_set_live (GST_BASE_SRC (dtmfsrc), TRUE);
315
316   dtmfsrc->interval = DEFAULT_PACKET_INTERVAL;
317
318   dtmfsrc->event_queue = g_async_queue_new ();
319   dtmfsrc->last_event = NULL;
320
321   dtmfsrc->sample_rate = DEFAULT_SAMPLE_RATE;
322
323   GST_DEBUG_OBJECT (dtmfsrc, "init done");
324 }
325
326 static void
327 gst_dtmf_src_finalize (GObject * object)
328 {
329   GstDTMFSrc *dtmfsrc;
330
331   dtmfsrc = GST_DTMF_SRC (object);
332
333   if (dtmfsrc->event_queue) {
334     g_async_queue_unref (dtmfsrc->event_queue);
335     dtmfsrc->event_queue = NULL;
336   }
337
338   G_OBJECT_CLASS (parent_class)->finalize (object);
339 }
340
341 static gboolean
342 gst_dtmf_src_handle_dtmf_event (GstDTMFSrc *dtmfsrc,
343         const GstStructure * event_structure)
344 {
345   gint event_type;
346   gboolean start;
347   gint method;
348
349   if (!gst_structure_get_int (event_structure, "type", &event_type) ||
350       !gst_structure_get_boolean (event_structure, "start", &start) ||
351       (start == TRUE && event_type != GST_TONE_DTMF_TYPE_EVENT))
352     goto failure;
353
354   if (gst_structure_get_int (event_structure, "method", &method)) {
355     if (method != 2) {
356       goto failure;
357     }
358   }
359
360   if (start) {
361     gint event_number;
362     gint event_volume;
363
364     if (!gst_structure_get_int (event_structure, "number", &event_number) ||
365             !gst_structure_get_int (event_structure, "volume", &event_volume))
366       goto failure;
367
368     GST_DEBUG_OBJECT (dtmfsrc, "Received start event %d with volume %d",
369             event_number, event_volume);
370     gst_dtmf_src_add_start_event (dtmfsrc, event_number, event_volume);
371   }
372
373   else {
374     GST_DEBUG_OBJECT (dtmfsrc, "Received stop event");
375     gst_dtmf_src_add_stop_event (dtmfsrc);
376   }
377
378   return TRUE;
379 failure:
380   return FALSE;
381 }
382
383 static gboolean
384 gst_dtmf_src_handle_custom_upstream (GstDTMFSrc *dtmfsrc,
385     GstEvent * event)
386 {
387   gboolean result = FALSE;
388   const GstStructure *structure;
389   GstState state;
390   GstStateChangeReturn ret;
391
392   ret = gst_element_get_state (GST_ELEMENT (dtmfsrc), &state, NULL, 0);
393   if (ret != GST_STATE_CHANGE_SUCCESS || state != GST_STATE_PLAYING) {
394     GST_DEBUG_OBJECT (dtmfsrc, "Received event while not in PLAYING state");
395     goto ret;
396   }
397
398   GST_DEBUG_OBJECT (dtmfsrc, "Received event is of our interest");
399   structure = gst_event_get_structure (event);
400   if (structure && gst_structure_has_name (structure, "dtmf-event"))
401     result = gst_dtmf_src_handle_dtmf_event (dtmfsrc, structure);
402
403 ret:
404   return result;
405 }
406
407 static gboolean
408 gst_dtmf_src_handle_event (GstBaseSrc * src, GstEvent * event)
409 {
410   GstDTMFSrc *dtmfsrc;
411   gboolean result = FALSE;
412
413   dtmfsrc = GST_DTMF_SRC (src);
414
415   GST_DEBUG_OBJECT (dtmfsrc, "Received an event on the src pad");
416   if (GST_EVENT_TYPE (event) == GST_EVENT_CUSTOM_UPSTREAM) {
417     result = gst_dtmf_src_handle_custom_upstream (dtmfsrc, event);
418   }
419
420   return result;
421 }
422
423 static void
424 gst_dtmf_src_set_property (GObject * object, guint prop_id,
425     const GValue * value, GParamSpec * pspec)
426 {
427   GstDTMFSrc *dtmfsrc;
428
429   dtmfsrc = GST_DTMF_SRC (object);
430
431   switch (prop_id) {
432     case PROP_INTERVAL:
433       dtmfsrc->interval = g_value_get_uint (value);
434       break;
435     default:
436       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
437       break;
438   }
439 }
440
441 static void
442 gst_dtmf_src_get_property (GObject * object, guint prop_id, GValue * value,
443     GParamSpec * pspec)
444 {
445   GstDTMFSrc *dtmfsrc;
446
447   dtmfsrc = GST_DTMF_SRC (object);
448
449   switch (prop_id) {
450     case PROP_INTERVAL:
451       g_value_set_uint (value, dtmfsrc->interval);
452       break;
453     default:
454       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
455       break;
456   }
457 }
458
459 static void
460 gst_dtmf_src_set_stream_lock (GstDTMFSrc *dtmfsrc, gboolean lock)
461 {
462    GstPad *srcpad = GST_BASE_SRC_PAD (dtmfsrc);
463    GstEvent *event;
464    GstStructure *structure;
465
466    structure = gst_structure_new ("stream-lock",
467                       "lock", G_TYPE_BOOLEAN, lock, NULL);
468
469    event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_OOB, structure);
470    if (!gst_pad_push_event (srcpad, event)) {
471      GST_WARNING_OBJECT (dtmfsrc, "stream-lock event not handled");
472    }
473 }
474
475 static void
476 gst_dtmf_prepare_timestamps (GstDTMFSrc *dtmfsrc)
477 {
478   GstClock *clock;
479   GstClockTime base_time;
480
481   base_time = gst_element_get_base_time (GST_ELEMENT (dtmfsrc));
482
483   clock = gst_element_get_clock (GST_ELEMENT (dtmfsrc));
484   if (clock != NULL) {
485 #ifdef MAEMO_BROKEN
486     dtmfsrc->timestamp = gst_clock_get_time (clock);
487 #else
488     dtmfsrc->timestamp = gst_clock_get_time (clock) - base_time;
489 #endif
490     gst_object_unref (clock);
491   } else {
492     gchar *dtmf_name = gst_element_get_name (dtmfsrc);
493     GST_ERROR_OBJECT (dtmfsrc, "No clock set for element %s", dtmf_name);
494     dtmfsrc->timestamp = GST_CLOCK_TIME_NONE;
495     g_free (dtmf_name);
496   }
497 }
498
499 static void
500 gst_dtmf_src_add_start_event (GstDTMFSrc *dtmfsrc, gint event_number,
501     gint event_volume)
502 {
503
504   GstDTMFSrcEvent * event = g_malloc (sizeof(GstDTMFSrcEvent));
505   event->event_type = DTMF_EVENT_TYPE_START;
506   event->sample = 0;
507   event->event_number = CLAMP (event_number, MIN_EVENT, MAX_EVENT);
508   event->volume = CLAMP (event_volume, MIN_VOLUME, MAX_VOLUME);
509
510   g_async_queue_push (dtmfsrc->event_queue, event);
511 }
512
513 static void
514 gst_dtmf_src_add_stop_event (GstDTMFSrc *dtmfsrc)
515 {
516
517   GstDTMFSrcEvent * event = g_malloc (sizeof(GstDTMFSrcEvent));
518   event->event_type = DTMF_EVENT_TYPE_STOP;
519   event->sample = 0;
520   event->event_number = 0;
521   event->volume = 0;
522
523   g_async_queue_push (dtmfsrc->event_queue, event);
524 }
525
526 static void
527 gst_dtmf_src_generate_silence(GstBuffer * buffer, float duration,
528     gint sample_rate)
529 {
530   gint buf_size;
531
532   /* Create a buffer with data set to 0 */
533   buf_size = ((duration/1000)*sample_rate*SAMPLE_SIZE*CHANNELS)/8;
534   GST_BUFFER_SIZE (buffer) = buf_size;
535   GST_BUFFER_MALLOCDATA (buffer) = g_malloc0(buf_size);
536   GST_BUFFER_DATA (buffer) = GST_BUFFER_MALLOCDATA (buffer);
537
538 }
539
540 static void
541 gst_dtmf_src_generate_tone(GstDTMFSrcEvent *event, DTMF_KEY key, float duration,
542     GstBuffer * buffer, gint sample_rate)
543 {
544   gint16 *p;
545   gint tone_size;
546   double i = 0;
547   double amplitude, f1, f2;
548   double volume_factor;
549
550   /* Create a buffer for the tone */
551   tone_size = ((duration/1000)*sample_rate*SAMPLE_SIZE*CHANNELS)/8;
552   GST_BUFFER_SIZE (buffer) = tone_size;
553   GST_BUFFER_MALLOCDATA (buffer) = g_malloc(tone_size);
554   GST_BUFFER_DATA (buffer) = GST_BUFFER_MALLOCDATA (buffer);
555
556   p = (gint16 *) GST_BUFFER_MALLOCDATA (buffer);
557
558   volume_factor = pow (10, (-event->volume) / 20);
559
560   /*
561    * For each sample point we calculate 'x' as the
562    * the amplitude value.
563    */
564   for (i = 0; i < (tone_size / (SAMPLE_SIZE/8)); i++) {
565     /*
566      * We add the fundamental frequencies together.
567      */
568     f1 = sin(2 * M_PI * key.low_frequency * (event->sample / sample_rate));
569     f2 = sin(2 * M_PI * key.high_frequency * (event->sample / sample_rate));
570
571     amplitude = (f1 + f2) / 2;
572
573     /* Adjust the volume */
574     amplitude *= volume_factor;
575
576     /* Make the [-1:1] interval into a [-32767:32767] interval */
577     amplitude *= 32767;
578
579     /* Store it in the data buffer */
580     *(p++) = (gint16) amplitude;
581
582     (event->sample)++;
583   }
584 }
585
586
587
588 static GstBuffer *
589 gst_dtmf_src_create_next_tone_packet (GstDTMFSrc *dtmfsrc,
590     GstDTMFSrcEvent *event)
591 {
592   GstBuffer *buf = NULL;
593   gboolean send_silence = FALSE;
594   GstPad *srcpad = GST_BASE_SRC_PAD (dtmfsrc);
595
596   GST_DEBUG_OBJECT (dtmfsrc, "Creating buffer for tone %s",
597       DTMF_KEYS[event->event_number].event_name);
598
599   /* create buffer to hold the tone */
600   buf = gst_buffer_new ();
601
602   if (event->packet_count * dtmfsrc->interval < MIN_INTER_DIGIT_INTERVAL) {
603     send_silence = TRUE;
604   }
605
606   if (send_silence) {
607     GST_DEBUG_OBJECT (dtmfsrc,  "Generating silence");
608     gst_dtmf_src_generate_silence (buf, dtmfsrc->interval,
609         dtmfsrc->sample_rate);
610   } else {
611     GST_DEBUG_OBJECT (dtmfsrc,  "Generating tone");
612     gst_dtmf_src_generate_tone(event, DTMF_KEYS[event->event_number],
613         dtmfsrc->interval, buf, dtmfsrc->sample_rate);
614   }
615   event->packet_count++;
616
617
618   /* timestamp and duration of GstBuffer */
619   GST_BUFFER_DURATION (buf) = dtmfsrc->interval * GST_MSECOND;
620   GST_BUFFER_TIMESTAMP (buf) = dtmfsrc->timestamp;
621   dtmfsrc->timestamp += GST_BUFFER_DURATION (buf);
622
623   /* Set caps on the buffer before pushing it */
624   gst_buffer_set_caps (buf, GST_PAD_CAPS (srcpad));
625
626   return buf;
627 }
628
629 static GstFlowReturn
630 gst_dtmf_src_create (GstBaseSrc * basesrc, guint64 offset,
631     guint length, GstBuffer ** buffer)
632 {
633   GstBuffer *buf = NULL;
634   GstDTMFSrcEvent *event;
635   GstDTMFSrc * dtmfsrc;
636   GstClock *clock;
637   GstClockID *clockid;
638   GstClockReturn clockret;
639
640   dtmfsrc = GST_DTMF_SRC (basesrc);
641
642   do {
643
644     if (dtmfsrc->last_event == NULL) {
645       GST_DEBUG_OBJECT (dtmfsrc, "popping");
646       event = g_async_queue_pop (dtmfsrc->event_queue);
647
648       GST_DEBUG_OBJECT (dtmfsrc, "popped %d", event->event_type);
649
650       switch (event->event_type) {
651         case DTMF_EVENT_TYPE_STOP:
652           GST_WARNING_OBJECT (dtmfsrc,
653               "Received a DTMF stop event when already stopped");
654           break;
655         case DTMF_EVENT_TYPE_START:
656           gst_dtmf_prepare_timestamps (dtmfsrc);
657
658           /* Don't forget to get exclusive access to the stream */
659           gst_dtmf_src_set_stream_lock (dtmfsrc, TRUE);
660
661           event->packet_count = 0;
662           dtmfsrc->last_event = event;
663           event = NULL;
664           break;
665         case DTMF_EVENT_TYPE_PAUSE_TASK:
666           /*
667            * We're pushing it back because it has to stay in there until
668            * the task is really paused (and the queue will then be flushed)
669            */
670           GST_DEBUG_OBJECT (dtmfsrc, "pushing pause_task...");
671           GST_OBJECT_LOCK (dtmfsrc);
672           if (dtmfsrc->paused) {
673             g_async_queue_push (dtmfsrc->event_queue, event);
674             goto paused_locked;
675           }
676           GST_OBJECT_UNLOCK (dtmfsrc);
677           break;
678       }
679       if (event)
680         g_free (event);
681     } else if (dtmfsrc->last_event->packet_count  * dtmfsrc->interval >=
682         MIN_DUTY_CYCLE) {
683       event = g_async_queue_try_pop (dtmfsrc->event_queue);
684
685       if (event != NULL) {
686
687         switch (event->event_type) {
688           case DTMF_EVENT_TYPE_START:
689             GST_WARNING_OBJECT (dtmfsrc,
690                 "Received two consecutive DTMF start events");
691             break;
692           case DTMF_EVENT_TYPE_STOP:
693             gst_dtmf_src_set_stream_lock (dtmfsrc, FALSE);
694
695             g_free (dtmfsrc->last_event);
696             dtmfsrc->last_event = NULL;
697             break;
698           case DTMF_EVENT_TYPE_PAUSE_TASK:
699             /*
700              * We're pushing it back because it has to stay in there until
701              * the task is really paused (and the queue will then be flushed)
702              */
703             GST_DEBUG_OBJECT (dtmfsrc, "pushing pause_task...");
704
705             GST_OBJECT_LOCK (dtmfsrc);
706             if (dtmfsrc->paused) {
707               g_async_queue_push (dtmfsrc->event_queue, event);
708               goto paused_locked;
709             }
710             GST_OBJECT_UNLOCK (dtmfsrc);
711
712             break;
713         }
714         g_free (event);
715       }
716     }
717   } while (dtmfsrc->last_event == NULL);
718
719   GST_DEBUG_OBJECT (dtmfsrc, "end event check, now wait for the proper time");
720
721   clock = gst_element_get_clock (GST_ELEMENT (basesrc));
722
723 #ifdef MAEMO_BROKEN
724   clockid = gst_clock_new_single_shot_id (clock, dtmfsrc->timestamp);
725 #else
726   clockid = gst_clock_new_single_shot_id (clock, dtmfsrc->timestamp +
727       gst_element_get_base_time (GST_ELEMENT (dtmfsrc)));
728 #endif
729   gst_object_unref (clock);
730
731   GST_OBJECT_LOCK (dtmfsrc);
732   if (!dtmfsrc->paused) {
733     dtmfsrc->clockid = clockid;
734     GST_OBJECT_UNLOCK (dtmfsrc);
735
736     clockret = gst_clock_id_wait (clockid, NULL);
737
738     GST_OBJECT_LOCK (dtmfsrc);
739     if (dtmfsrc->paused)
740       clockret = GST_CLOCK_UNSCHEDULED;
741   } else  {
742     clockret = GST_CLOCK_UNSCHEDULED;
743   }
744   gst_clock_id_unref (clockid);
745   dtmfsrc->clockid = NULL;
746   GST_OBJECT_UNLOCK (dtmfsrc);
747
748   if (clockret == GST_CLOCK_UNSCHEDULED) {
749     goto paused;
750   }
751
752   buf = gst_dtmf_src_create_next_tone_packet (dtmfsrc, dtmfsrc->last_event);
753
754   GST_DEBUG_OBJECT (dtmfsrc, "Created buffer of size %d", GST_BUFFER_SIZE (buf));
755   *buffer = buf;
756
757   GST_DEBUG_OBJECT (dtmfsrc, "returning a buffer");
758   return GST_FLOW_OK;
759
760  paused_locked:
761   GST_OBJECT_UNLOCK (dtmfsrc);
762
763  paused:
764
765   if (dtmfsrc->last_event) {
766     GST_DEBUG_OBJECT (dtmfsrc, "Stopping current event");
767     /* Don't forget to release the stream lock */
768     gst_dtmf_src_set_stream_lock (dtmfsrc, FALSE);
769     g_free (dtmfsrc->last_event);
770     dtmfsrc->last_event = NULL;
771   }
772
773   return GST_FLOW_WRONG_STATE;
774
775 }
776
777 static gboolean
778 gst_dtmf_src_unlock (GstBaseSrc *src) {
779   GstDTMFSrc *dtmfsrc = GST_DTMF_SRC (src);
780   GstDTMFSrcEvent *event = NULL;
781
782   GST_DEBUG_OBJECT (dtmfsrc, "Called unlock");
783
784   GST_OBJECT_LOCK (dtmfsrc);
785   dtmfsrc->paused = TRUE;
786   if (dtmfsrc->clockid) {
787     gst_clock_id_unschedule (dtmfsrc->clockid);
788   }
789   GST_OBJECT_UNLOCK (dtmfsrc);
790
791   GST_DEBUG_OBJECT (dtmfsrc, "Pushing the PAUSE_TASK event on unlock request");
792   event = g_malloc (sizeof(GstDTMFSrcEvent));
793   event->event_type = DTMF_EVENT_TYPE_PAUSE_TASK;
794   g_async_queue_push (dtmfsrc->event_queue, event);
795
796   return TRUE;
797 }
798
799
800 static gboolean
801 gst_dtmf_src_unlock_stop (GstBaseSrc *src) {
802   GstDTMFSrc *dtmfsrc = GST_DTMF_SRC (src);
803
804   GST_DEBUG_OBJECT (dtmfsrc, "Unlock stopped");
805
806   GST_OBJECT_LOCK (dtmfsrc);
807   dtmfsrc->paused = FALSE;
808   GST_OBJECT_UNLOCK (dtmfsrc);
809
810   return TRUE;
811 }
812
813
814 static gboolean
815 gst_dtmf_src_negotiate (GstBaseSrc * basesrc)
816 {
817   GstCaps *srccaps, *peercaps;
818   GstDTMFSrc *dtmfsrc = GST_DTMF_SRC (basesrc);
819   gboolean ret = FALSE;
820
821   srccaps = gst_caps_new_simple ("audio/x-raw-int",
822       "width", G_TYPE_INT, 16,
823       "depth", G_TYPE_INT, 16,
824       "endianness", G_TYPE_INT, G_BYTE_ORDER,
825       "signed", G_TYPE_BOOLEAN, TRUE,
826       "channels", G_TYPE_INT, 1,
827       NULL);
828
829   peercaps = gst_pad_peer_get_caps (GST_BASE_SRC_PAD (basesrc));
830
831   if (peercaps == NULL) {
832     /* no peer caps, just add the other properties */
833     gst_caps_set_simple (srccaps,
834         "rate", G_TYPE_INT, dtmfsrc->sample_rate,
835         NULL);
836   } else {
837     GstStructure *s;
838     gint sample_rate;
839     GstCaps *temp = NULL;
840
841     g_debug ("HAS PEERCAPS %s", gst_caps_to_string (peercaps));
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   g_warning ("negotiated %s", gst_caps_to_string (srccaps));
883
884
885
886   gst_caps_unref (srccaps);
887
888   return ret;
889 }
890
891 static GstStateChangeReturn
892 gst_dtmf_src_change_state (GstElement * element, GstStateChange transition)
893 {
894   GstDTMFSrc *dtmfsrc;
895   GstStateChangeReturn result;
896   gboolean no_preroll = FALSE;
897   GstDTMFSrcEvent *event = NULL;
898
899   dtmfsrc = GST_DTMF_SRC (element);
900
901   switch (transition) {
902     case GST_STATE_CHANGE_READY_TO_PAUSED:
903       /* Flushing the event queue */
904       event = g_async_queue_try_pop (dtmfsrc->event_queue);
905
906       while (event != NULL) {
907         g_free (event);
908         event = g_async_queue_try_pop (dtmfsrc->event_queue);
909       }
910       no_preroll = TRUE;
911       break;
912     default:
913       break;
914   }
915
916   if ((result =
917           GST_ELEMENT_CLASS (parent_class)->change_state (element,
918               transition)) == GST_STATE_CHANGE_FAILURE)
919     goto failure;
920
921   switch (transition) {
922     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
923       no_preroll = TRUE;
924       break;
925     case GST_STATE_CHANGE_PAUSED_TO_READY:
926       GST_DEBUG_OBJECT (dtmfsrc, "Flushing event queue");
927       /* Flushing the event queue */
928       event = g_async_queue_try_pop (dtmfsrc->event_queue);
929
930       while (event != NULL) {
931         g_free (event);
932         event = g_async_queue_try_pop (dtmfsrc->event_queue);
933       }
934
935       break;
936     default:
937       break;
938   }
939
940   if (no_preroll && result == GST_STATE_CHANGE_SUCCESS)
941     result = GST_STATE_CHANGE_NO_PREROLL;
942
943   return result;
944
945   /* ERRORS */
946 failure:
947   {
948     GST_ERROR_OBJECT (dtmfsrc, "parent failed state change");
949     return result;
950   }
951 }
952
953 gboolean
954 gst_dtmf_src_plugin_init (GstPlugin * plugin)
955 {
956   return gst_element_register (plugin, "dtmfsrc",
957       GST_RANK_NONE, GST_TYPE_DTMF_SRC);
958 }
959