Asterisk - The Open Source Telephony Project GIT-master-754dea3
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros Modules Pages
func_pitchshift.c
Go to the documentation of this file.
1/*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 2010, Digium, Inc.
5 *
6 * David Vossel <dvossel@digium.com>
7 *
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
13 *
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
17 */
18
19/*! \file
20 *
21 * \brief Pitch Shift Audio Effect
22 *
23 * \author David Vossel <dvossel@digium.com>
24 *
25 * \ingroup functions
26 */
27
28/************************* SMB FUNCTION LICENSE *********************************
29*
30* SYNOPSIS: Routine for doing pitch shifting while maintaining
31* duration using the Short Time Fourier Transform.
32*
33* DESCRIPTION: The routine takes a pitchShift factor value which is between 0.5
34* (one octave down) and 2. (one octave up). A value of exactly 1 does not change
35* the pitch. num_samps_to_process tells the routine how many samples in indata[0...
36* num_samps_to_process-1] should be pitch shifted and moved to outdata[0 ...
37* num_samps_to_process-1]. The two buffers can be identical (ie. it can process the
38* data in-place). fft_frame_size defines the FFT frame size used for the
39* processing. Typical values are 1024, 2048 and 4096. It may be any value <=
40* MAX_FRAME_LENGTH but it MUST be a power of 2. osamp is the STFT
41* oversampling factor which also determines the overlap between adjacent STFT
42* frames. It should at least be 4 for moderate scaling ratios. A value of 32 is
43* recommended for best quality. sampleRate takes the sample rate for the signal
44* in unit Hz, ie. 44100 for 44.1 kHz audio. The data passed to the routine in
45* indata[] should be in the range [-1.0, 1.0), which is also the output range
46* for the data, make sure you scale the data accordingly (for 16bit signed integers
47* you would have to divide (and multiply) by 32768).
48*
49* COPYRIGHT 1999-2009 Stephan M. Bernsee <smb [AT] dspdimension [DOT] com>
50*
51* The Wide Open License (WOL)
52*
53* Permission to use, copy, modify, distribute and sell this software and its
54* documentation for any purpose is hereby granted without fee, provided that
55* the above copyright notice and this license appear in all source copies.
56* THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF
57* ANY KIND. See http://www.dspguru.com/wol.htm for more information.
58*
59*****************************************************************************/
60
61/*** MODULEINFO
62 <support_level>extended</support_level>
63 ***/
64
65#include "asterisk.h"
66
67#include "asterisk/module.h"
68#include "asterisk/channel.h"
69#include "asterisk/pbx.h"
70#include "asterisk/utils.h"
71#include "asterisk/audiohook.h"
72#include <math.h>
73
74/*** DOCUMENTATION
75 <function name="PITCH_SHIFT" language="en_US">
76 <since>
77 <version>1.8.0</version>
78 </since>
79 <synopsis>
80 Pitch shift both tx and rx audio streams on a channel.
81 </synopsis>
82 <syntax>
83 <parameter name="channel direction" required="true">
84 <para>Direction can be either <literal>rx</literal>, <literal>tx</literal>, or
85 <literal>both</literal>. The direction can either be set to a valid floating
86 point number between 0.1 and 4.0 or one of the enum values listed below. A value
87 of 1.0 has no effect. Greater than 1 raises the pitch. Lower than 1 lowers
88 the pitch.</para>
89
90 <para>The pitch amount can also be set by the following values</para>
91 <enumlist>
92 <enum name = "highest" />
93 <enum name = "higher" />
94 <enum name = "high" />
95 <enum name = "low" />
96 <enum name = "lower" />
97 <enum name = "lowest" />
98 </enumlist>
99 </parameter>
100 </syntax>
101 <description>
102 <para>Examples:</para>
103 <example title="Raises pitch an octave">
104 exten => 1,1,Set(PITCH_SHIFT(tx)=highest)
105 </example>
106 <example title="Raises pitch more">
107 exten => 1,1,Set(PITCH_SHIFT(rx)=higher)
108 </example>
109 <example title="Raises pitch">
110 exten => 1,1,Set(PITCH_SHIFT(both)=high)
111 </example>
112 <example title="Lowers pitch">
113 exten => 1,1,Set(PITCH_SHIFT(rx)=low)
114 </example>
115 <example title="Lowers pitch more">
116 exten => 1,1,Set(PITCH_SHIFT(tx)=lower)
117 </example>
118 <example title="Lowers pitch an octave">
119 exten => 1,1,Set(PITCH_SHIFT(both)=lowest)
120 </example>
121 <example title="Lowers pitch">
122 exten => 1,1,Set(PITCH_SHIFT(rx)=0.8)
123 </example>
124 <example title="Raises pitch">
125 exten => 1,1,Set(PITCH_SHIFT(tx)=1.5)
126 </example>
127 </description>
128 </function>
129 ***/
130
131#ifndef M_PI
132#define M_PI 3.14159265358979323846
133#endif
134#define MAX_FRAME_LENGTH 256
135
136#define HIGHEST 2
137#define HIGHER 1.5
138#define HIGH 1.25
139#define LOW .85
140#define LOWER .7
141#define LOWEST .5
142
143struct fft_data {
154 long gRover;
156};
157
160
161 struct fft_data rx;
162 struct fft_data tx;
163};
164
165static void smb_fft(float *fft_buffer, long fft_frame_size, long sign);
166static void smb_pitch_shift(float pitchShift, long num_samps_to_process, long fft_frame_size, long osamp, float sample_rate, int16_t *indata, int16_t *outdata, struct fft_data *fft_data);
167static int pitch_shift(struct ast_frame *f, float amount, struct fft_data *fft_data);
168
169static void destroy_callback(void *data)
170{
171 struct pitchshift_data *shift = data;
172
174 ast_free(shift);
175};
176
178 .type = "pitchshift",
179 .destroy = destroy_callback
180};
181
182static int pitchshift_cb(struct ast_audiohook *audiohook, struct ast_channel *chan, struct ast_frame *f, enum ast_audiohook_direction direction)
183{
184 struct ast_datastore *datastore = NULL;
185 struct pitchshift_data *shift = NULL;
186
187
188 if (!f) {
189 return 0;
190 }
192 return -1;
193 }
194
195 if (!(datastore = ast_channel_datastore_find(chan, &pitchshift_datastore, NULL))) {
196 return -1;
197 }
198
199 shift = datastore->data;
200
202 pitch_shift(f, shift->tx.shift_amount, &shift->tx);
203 } else {
204 pitch_shift(f, shift->rx.shift_amount, &shift->rx);
205 }
206
207 return 0;
208}
209
210static int pitchshift_helper(struct ast_channel *chan, const char *cmd, char *data, const char *value)
211{
212 struct ast_datastore *datastore = NULL;
213 struct pitchshift_data *shift = NULL;
214 int new = 0;
215 float amount = 0;
216
217 if (!chan) {
218 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
219 return -1;
220 }
221
222 ast_channel_lock(chan);
223 if (!(datastore = ast_channel_datastore_find(chan, &pitchshift_datastore, NULL))) {
224 ast_channel_unlock(chan);
225
226 if (!(datastore = ast_datastore_alloc(&pitchshift_datastore, NULL))) {
227 return 0;
228 }
229 if (!(shift = ast_calloc(1, sizeof(*shift)))) {
230 ast_datastore_free(datastore);
231 return 0;
232 }
233
236 datastore->data = shift;
237 new = 1;
238 } else {
239 ast_channel_unlock(chan);
240 shift = datastore->data;
241 }
242
243
244 if (!strcasecmp(value, "highest")) {
245 amount = HIGHEST;
246 } else if (!strcasecmp(value, "higher")) {
247 amount = HIGHER;
248 } else if (!strcasecmp(value, "high")) {
249 amount = HIGH;
250 } else if (!strcasecmp(value, "lowest")) {
251 amount = LOWEST;
252 } else if (!strcasecmp(value, "lower")) {
253 amount = LOWER;
254 } else if (!strcasecmp(value, "low")) {
255 amount = LOW;
256 } else {
257 if (!sscanf(value, "%30f", &amount) || (amount <= 0) || (amount > 4)) {
258 goto cleanup_error;
259 }
260 }
261
262 if (!strcasecmp(data, "rx")) {
263 shift->rx.shift_amount = amount;
264 } else if (!strcasecmp(data, "tx")) {
265 shift->tx.shift_amount = amount;
266 } else if (!strcasecmp(data, "both")) {
267 shift->rx.shift_amount = amount;
268 shift->tx.shift_amount = amount;
269 } else {
270 goto cleanup_error;
271 }
272
273 if (new) {
274 ast_channel_lock(chan);
275 ast_channel_datastore_add(chan, datastore);
276 ast_channel_unlock(chan);
277 ast_audiohook_attach(chan, &shift->audiohook);
278 }
279
280 return 0;
281
282cleanup_error:
283
284 ast_log(LOG_ERROR, "Invalid argument provided to the %s function\n", cmd);
285 if (new) {
286 ast_datastore_free(datastore);
287 }
288 return -1;
289}
290
291static void smb_fft(float *fft_buffer, long fft_frame_size, long sign)
292{
293 float wr, wi, arg, *p1, *p2, temp;
294 float tr, ti, ur, ui, *p1r, *p1i, *p2r, *p2i;
295 long i, bitm, j, le, le2, k;
296
297 for (i = 2; i < 2 * fft_frame_size - 2; i += 2) {
298 for (bitm = 2, j = 0; bitm < 2 * fft_frame_size; bitm <<= 1) {
299 if (i & bitm) {
300 j++;
301 }
302 j <<= 1;
303 }
304 if (i < j) {
305 p1 = fft_buffer + i; p2 = fft_buffer + j;
306 temp = *p1; *(p1++) = *p2;
307 *(p2++) = temp; temp = *p1;
308 *p1 = *p2; *p2 = temp;
309 }
310 }
311 for (k = 0, le = 2; k < (long) (log(fft_frame_size) / log(2.) + .5); k++) {
312 le <<= 1;
313 le2 = le>>1;
314 ur = 1.0;
315 ui = 0.0;
316 arg = M_PI / (le2>>1);
317 wr = cos(arg);
318 wi = sign * sin(arg);
319 for (j = 0; j < le2; j += 2) {
320 p1r = fft_buffer+j; p1i = p1r + 1;
321 p2r = p1r + le2; p2i = p2r + 1;
322 for (i = j; i < 2 * fft_frame_size; i += le) {
323 tr = *p2r * ur - *p2i * ui;
324 ti = *p2r * ui + *p2i * ur;
325 *p2r = *p1r - tr; *p2i = *p1i - ti;
326 *p1r += tr; *p1i += ti;
327 p1r += le; p1i += le;
328 p2r += le; p2i += le;
329 }
330 tr = ur * wr - ui * wi;
331 ui = ur * wi + ui * wr;
332 ur = tr;
333 }
334 }
335}
336
337static void smb_pitch_shift(float pitchShift, long num_samps_to_process, long fft_frame_size, long osamp, float sample_rate, int16_t *indata, int16_t *outdata, struct fft_data *fft_data)
338{
339 float *in_fifo = fft_data->in_fifo;
340 float *out_fifo = fft_data->out_fifo;
341 float *fft_worksp = fft_data->fft_worksp;
342 float *last_phase = fft_data->last_phase;
343 float *sum_phase = fft_data->sum_phase;
344 float *output_accum = fft_data->output_accum;
345 float *ana_freq = fft_data->ana_freq;
346 float *ana_magn = fft_data->ana_magn;
347 float *syn_freq = fft_data->syn_freq;
348 float *sys_magn = fft_data->sys_magn;
349
350 double magn, phase, tmp, window, real, imag;
351 double freq_per_bin, expect;
352 long i,k, qpd, index, in_fifo_latency, step_size, fft_frame_size2;
353
354 /* set up some handy variables */
355 fft_frame_size2 = fft_frame_size / 2;
356 step_size = fft_frame_size / osamp;
357 freq_per_bin = sample_rate / (double) fft_frame_size;
358 expect = 2. * M_PI * (double) step_size / (double) fft_frame_size;
359 in_fifo_latency = fft_frame_size-step_size;
360
361 if (fft_data->gRover == 0) {
362 fft_data->gRover = in_fifo_latency;
363 }
364
365 /* main processing loop */
366 for (i = 0; i < num_samps_to_process; i++){
367
368 /* As long as we have not yet collected enough data just read in */
369 in_fifo[fft_data->gRover] = indata[i];
370 outdata[i] = out_fifo[fft_data->gRover - in_fifo_latency];
371 fft_data->gRover++;
372
373 /* now we have enough data for processing */
374 if (fft_data->gRover >= fft_frame_size) {
375 fft_data->gRover = in_fifo_latency;
376
377 /* do windowing and re,im interleave */
378 for (k = 0; k < fft_frame_size;k++) {
379 window = -.5 * cos(2. * M_PI * (double) k / (double) fft_frame_size) + .5;
380 fft_worksp[2*k] = in_fifo[k] * window;
381 fft_worksp[2*k+1] = 0.;
382 }
383
384 /* ***************** ANALYSIS ******************* */
385 /* do transform */
386 smb_fft(fft_worksp, fft_frame_size, -1);
387
388 /* this is the analysis step */
389 for (k = 0; k <= fft_frame_size2; k++) {
390
391 /* de-interlace FFT buffer */
392 real = fft_worksp[2*k];
393 imag = fft_worksp[2*k+1];
394
395 /* compute magnitude and phase */
396 magn = 2. * sqrt(real * real + imag * imag);
397 phase = atan2(imag, real);
398
399 /* compute phase difference */
400 tmp = phase - last_phase[k];
401 last_phase[k] = phase;
402
403 /* subtract expected phase difference */
404 tmp -= (double) k * expect;
405
406 /* map delta phase into +/- Pi interval */
407 qpd = tmp / M_PI;
408 if (qpd >= 0) {
409 qpd += qpd & 1;
410 } else {
411 qpd -= qpd & 1;
412 }
413 tmp -= M_PI * (double) qpd;
414
415 /* get deviation from bin frequency from the +/- Pi interval */
416 tmp = osamp * tmp / (2. * M_PI);
417
418 /* compute the k-th partials' true frequency */
419 tmp = (double) k * freq_per_bin + tmp * freq_per_bin;
420
421 /* store magnitude and true frequency in analysis arrays */
422 ana_magn[k] = magn;
423 ana_freq[k] = tmp;
424
425 }
426
427 /* ***************** PROCESSING ******************* */
428 /* this does the actual pitch shifting */
429 memset(sys_magn, 0, fft_frame_size * sizeof(float));
430 memset(syn_freq, 0, fft_frame_size * sizeof(float));
431 for (k = 0; k <= fft_frame_size2; k++) {
432 index = k * pitchShift;
433 if (index <= fft_frame_size2) {
434 sys_magn[index] += ana_magn[k];
435 syn_freq[index] = ana_freq[k] * pitchShift;
436 }
437 }
438
439 /* ***************** SYNTHESIS ******************* */
440 /* this is the synthesis step */
441 for (k = 0; k <= fft_frame_size2; k++) {
442
443 /* get magnitude and true frequency from synthesis arrays */
444 magn = sys_magn[k];
445 tmp = syn_freq[k];
446
447 /* subtract bin mid frequency */
448 tmp -= (double) k * freq_per_bin;
449
450 /* get bin deviation from freq deviation */
451 tmp /= freq_per_bin;
452
453 /* take osamp into account */
454 tmp = 2. * M_PI * tmp / osamp;
455
456 /* add the overlap phase advance back in */
457 tmp += (double) k * expect;
458
459 /* accumulate delta phase to get bin phase */
460 sum_phase[k] += tmp;
461 phase = sum_phase[k];
462
463 /* get real and imag part and re-interleave */
464 fft_worksp[2*k] = magn * cos(phase);
465 fft_worksp[2*k+1] = magn * sin(phase);
466 }
467
468 /* zero negative frequencies */
469 for (k = fft_frame_size + 2; k < 2 * fft_frame_size; k++) {
470 fft_worksp[k] = 0.;
471 }
472
473 /* do inverse transform */
474 smb_fft(fft_worksp, fft_frame_size, 1);
475
476 /* do windowing and add to output accumulator */
477 for (k = 0; k < fft_frame_size; k++) {
478 window = -.5 * cos(2. * M_PI * (double) k / (double) fft_frame_size) + .5;
479 output_accum[k] += 2. * window * fft_worksp[2*k] / (fft_frame_size2 * osamp);
480 }
481 for (k = 0; k < step_size; k++) {
482 out_fifo[k] = output_accum[k];
483 }
484
485 /* shift accumulator */
486 memmove(output_accum, output_accum+step_size, fft_frame_size * sizeof(float));
487
488 /* move input FIFO */
489 for (k = 0; k < in_fifo_latency; k++) {
490 in_fifo[k] = in_fifo[k+step_size];
491 }
492 }
493 }
494}
495
496static int pitch_shift(struct ast_frame *f, float amount, struct fft_data *fft)
497{
498 int16_t *fun = (int16_t *) f->data.ptr;
499 int samples;
500
501 /* an amount of 1 has no effect */
502 if (!amount || amount == 1 || !fun || (f->samples % 32)) {
503 return 0;
504 }
505 for (samples = 0; samples < f->samples; samples += 32) {
506 smb_pitch_shift(amount, 32, MAX_FRAME_LENGTH, 32, ast_format_get_sample_rate(f->subclass.format), fun+samples, fun+samples, fft);
507 }
508
509 return 0;
510}
511
513 .name = "PITCH_SHIFT",
514 .write = pitchshift_helper,
515};
516
517static int unload_module(void)
518{
520}
521
522static int load_module(void)
523{
526}
527
528AST_MODULE_INFO_STANDARD_EXTENDED(ASTERISK_GPL_KEY, "Audio Effects Dialplan Functions");
if(!yyg->yy_init)
Definition: ast_expr2f.c:854
Asterisk main include file. File version handling, generic pbx functions.
#define ast_free(a)
Definition: astmm.h:180
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:202
#define ast_log
Definition: astobj2.c:42
Audiohooks Architecture.
@ AST_AUDIOHOOK_MANIPULATE_ALL_RATES
Definition: audiohook.h:75
int ast_audiohook_init(struct ast_audiohook *audiohook, enum ast_audiohook_type type, const char *source, enum ast_audiohook_init_flags flags)
Initialize an audiohook structure.
Definition: audiohook.c:100
ast_audiohook_direction
Definition: audiohook.h:48
@ AST_AUDIOHOOK_DIRECTION_WRITE
Definition: audiohook.h:50
int ast_audiohook_attach(struct ast_channel *chan, struct ast_audiohook *audiohook)
Attach audiohook to channel.
Definition: audiohook.c:512
int ast_audiohook_destroy(struct ast_audiohook *audiohook)
Destroys an audiohook structure.
Definition: audiohook.c:124
@ AST_AUDIOHOOK_TYPE_MANIPULATE
Definition: audiohook.h:38
@ AST_AUDIOHOOK_STATUS_DONE
Definition: audiohook.h:45
unsigned int cos
Definition: chan_iax2.c:380
General Asterisk PBX channel definitions.
int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
Add a datastore to a channel.
Definition: channel.c:2414
#define ast_channel_lock(chan)
Definition: channel.h:2970
#define ast_channel_unlock(chan)
Definition: channel.h:2971
struct ast_datastore * ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
Find a datastore on a channel.
Definition: channel.c:2428
static int step_size(struct g726_state *state_ptr)
Definition: codec_g726.c:247
#define ast_datastore_alloc(info, uid)
Definition: datastore.h:85
int ast_datastore_free(struct ast_datastore *datastore)
Free a data store object.
Definition: datastore.c:68
char window[WINSIZE]
Definition: eagi_proxy.c:69
unsigned int ast_format_get_sample_rate(const struct ast_format *format)
Get the sample rate of a media format.
Definition: format.c:379
direction
#define LOWEST
static void smb_pitch_shift(float pitchShift, long num_samps_to_process, long fft_frame_size, long osamp, float sample_rate, int16_t *indata, int16_t *outdata, struct fft_data *fft_data)
#define HIGHER
static struct ast_custom_function pitch_shift_function
#define HIGH
#define HIGHEST
static const struct ast_datastore_info pitchshift_datastore
static void smb_fft(float *fft_buffer, long fft_frame_size, long sign)
#define LOWER
#define LOW
AST_MODULE_INFO_STANDARD_EXTENDED(ASTERISK_GPL_KEY, "Audio Effects Dialplan Functions")
static void destroy_callback(void *data)
static int load_module(void)
static int unload_module(void)
static int pitchshift_cb(struct ast_audiohook *audiohook, struct ast_channel *chan, struct ast_frame *f, enum ast_audiohook_direction direction)
static int pitch_shift(struct ast_frame *f, float amount, struct fft_data *fft_data)
#define M_PI
static int pitchshift_helper(struct ast_channel *chan, const char *cmd, char *data, const char *value)
#define MAX_FRAME_LENGTH
#define LOG_ERROR
#define LOG_WARNING
float real
Definition: lpc10.h:79
Asterisk module definitions.
#define ASTERISK_GPL_KEY
The text the key() function should return.
Definition: module.h:46
@ AST_MODULE_LOAD_SUCCESS
Definition: module.h:70
@ AST_MODULE_LOAD_DECLINE
Module has failed to load, may be in an inconsistent state.
Definition: module.h:78
Core PBX routines and definitions.
#define ast_custom_function_register(acf)
Register a custom function.
Definition: pbx.h:1559
int ast_custom_function_unregister(struct ast_custom_function *acf)
Unregister a custom function.
#define NULL
Definition: resample.c:96
ast_audiohook_manipulate_callback manipulate_callback
Definition: audiohook.h:118
enum ast_audiohook_status status
Definition: audiohook.h:108
Main Channel structure associated with a channel.
Data structure associated with a custom dialplan function.
Definition: pbx.h:118
const char * name
Definition: pbx.h:119
Structure for a data store type.
Definition: datastore.h:31
const char * type
Definition: datastore.h:32
Structure for a data store object.
Definition: datastore.h:64
void * data
Definition: datastore.h:66
struct ast_format * format
Data structure associated with a single frame of data.
union ast_frame::@228 data
struct ast_frame_subclass subclass
float output_accum[2 *MAX_FRAME_LENGTH]
float out_fifo[MAX_FRAME_LENGTH]
float ana_freq[MAX_FRAME_LENGTH]
float sum_phase[MAX_FRAME_LENGTH/2+1]
float in_fifo[MAX_FRAME_LENGTH]
float shift_amount
float sys_magn[MAX_FRAME_LENGTH]
float fft_worksp[2 *MAX_FRAME_LENGTH]
float ana_magn[MAX_FRAME_LENGTH]
float syn_freq[MAX_FRAME_LENGTH]
float last_phase[MAX_FRAME_LENGTH/2+1]
struct fft_data tx
struct fft_data rx
struct ast_audiohook audiohook
int value
Definition: syslog.c:37
Utility functions.