1 /* $NetBSD: dtmf.c,v 1.2 2010/09/01 21:54:00 jmcneill Exp $ */ 2 3 /* 4 * Copyright (c) 2010 Jared D. McNeill <jmcneill@invisible.ca> 5 * All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 16 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 17 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 18 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 20 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 * POSSIBILITY OF SUCH DAMAGE. 27 */ 28 29 #include <sys/endian.h> 30 31 #include <fcntl.h> 32 #include <math.h> 33 #include <stdio.h> 34 #include <stdint.h> 35 #include <string.h> 36 #include <stdlib.h> 37 #include <unistd.h> 38 39 #include "dtmf.h" 40 41 #define PI2 (3.14159265358979323846f * 2) 42 43 static void 44 dtmf_create(int16_t *buf, unsigned int sample_rate, 45 unsigned short sample_length, unsigned short channels, 46 unsigned int chanmask, float freq1, float freq2) 47 { 48 int c, i; 49 size_t sample_count = sample_rate * sample_length; 50 51 for (i = 0; i < sample_count; i++) { 52 for (c = 0; c < channels; c++) { 53 if ((chanmask & (1 << c)) == 0) 54 continue; 55 buf[c] = htole16( 56 (sin(i * PI2 * (freq1 / sample_rate)) + 57 sin(i * PI2 * (freq2 / sample_rate))) * 16383 58 ); 59 } 60 buf += channels; 61 } 62 } 63 64 void 65 dtmf_new(int16_t **buf, size_t *buflen, unsigned int sample_rate, 66 unsigned short sample_length, unsigned short channels, 67 unsigned int chanmask, float rate1, float rate2) 68 { 69 *buflen = sample_rate * sizeof(int16_t) * sample_length * channels; 70 *buf = calloc(1, *buflen); 71 if (*buf == NULL) { 72 perror("calloc"); 73 return; 74 } 75 76 dtmf_create(*buf, sample_rate, sample_length, channels, chanmask, 77 rate1, rate2); 78 } 79