Asterisk - The Open Source Telephony Project  21.4.1
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  <synopsis>
77  Pitch shift both tx and rx audio streams on a channel.
78  </synopsis>
79  <syntax>
80  <parameter name="channel direction" required="true">
81  <para>Direction can be either <literal>rx</literal>, <literal>tx</literal>, or
82  <literal>both</literal>. The direction can either be set to a valid floating
83  point number between 0.1 and 4.0 or one of the enum values listed below. A value
84  of 1.0 has no effect. Greater than 1 raises the pitch. Lower than 1 lowers
85  the pitch.</para>
86 
87  <para>The pitch amount can also be set by the following values</para>
88  <enumlist>
89  <enum name = "highest" />
90  <enum name = "higher" />
91  <enum name = "high" />
92  <enum name = "low" />
93  <enum name = "lower" />
94  <enum name = "lowest" />
95  </enumlist>
96  </parameter>
97  </syntax>
98  <description>
99  <para>Examples:</para>
100  <example title="Raises pitch an octave">
101  exten => 1,1,Set(PITCH_SHIFT(tx)=highest)
102  </example>
103  <example title="Raises pitch more">
104  exten => 1,1,Set(PITCH_SHIFT(rx)=higher)
105  </example>
106  <example title="Raises pitch">
107  exten => 1,1,Set(PITCH_SHIFT(both)=high)
108  </example>
109  <example title="Lowers pitch">
110  exten => 1,1,Set(PITCH_SHIFT(rx)=low)
111  </example>
112  <example title="Lowers pitch more">
113  exten => 1,1,Set(PITCH_SHIFT(tx)=lower)
114  </example>
115  <example title="Lowers pitch an octave">
116  exten => 1,1,Set(PITCH_SHIFT(both)=lowest)
117  </example>
118  <example title="Lowers pitch">
119  exten => 1,1,Set(PITCH_SHIFT(rx)=0.8)
120  </example>
121  <example title="Raises pitch">
122  exten => 1,1,Set(PITCH_SHIFT(tx)=1.5)
123  </example>
124  </description>
125  </function>
126  ***/
127 
128 #ifndef M_PI
129 #define M_PI 3.14159265358979323846
130 #endif
131 #define MAX_FRAME_LENGTH 256
132 
133 #define HIGHEST 2
134 #define HIGHER 1.5
135 #define HIGH 1.25
136 #define LOW .85
137 #define LOWER .7
138 #define LOWEST .5
139 
140 struct fft_data {
141  float in_fifo[MAX_FRAME_LENGTH];
142  float out_fifo[MAX_FRAME_LENGTH];
143  float fft_worksp[2*MAX_FRAME_LENGTH];
144  float last_phase[MAX_FRAME_LENGTH/2+1];
145  float sum_phase[MAX_FRAME_LENGTH/2+1];
146  float output_accum[2*MAX_FRAME_LENGTH];
147  float ana_freq[MAX_FRAME_LENGTH];
148  float ana_magn[MAX_FRAME_LENGTH];
149  float syn_freq[MAX_FRAME_LENGTH];
150  float sys_magn[MAX_FRAME_LENGTH];
151  long gRover;
152  float shift_amount;
153 };
154 
156  struct ast_audiohook audiohook;
157 
158  struct fft_data rx;
159  struct fft_data tx;
160 };
161 
162 static void smb_fft(float *fft_buffer, long fft_frame_size, long sign);
163 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);
164 static int pitch_shift(struct ast_frame *f, float amount, struct fft_data *fft_data);
165 
166 static void destroy_callback(void *data)
167 {
168  struct pitchshift_data *shift = data;
169 
170  ast_audiohook_destroy(&shift->audiohook);
171  ast_free(shift);
172 };
173 
174 static const struct ast_datastore_info pitchshift_datastore = {
175  .type = "pitchshift",
176  .destroy = destroy_callback
177 };
178 
179 static int pitchshift_cb(struct ast_audiohook *audiohook, struct ast_channel *chan, struct ast_frame *f, enum ast_audiohook_direction direction)
180 {
181  struct ast_datastore *datastore = NULL;
182  struct pitchshift_data *shift = NULL;
183 
184 
185  if (!f) {
186  return 0;
187  }
188  if (audiohook->status == AST_AUDIOHOOK_STATUS_DONE) {
189  return -1;
190  }
191 
192  if (!(datastore = ast_channel_datastore_find(chan, &pitchshift_datastore, NULL))) {
193  return -1;
194  }
195 
196  shift = datastore->data;
197 
198  if (direction == AST_AUDIOHOOK_DIRECTION_WRITE) {
199  pitch_shift(f, shift->tx.shift_amount, &shift->tx);
200  } else {
201  pitch_shift(f, shift->rx.shift_amount, &shift->rx);
202  }
203 
204  return 0;
205 }
206 
207 static int pitchshift_helper(struct ast_channel *chan, const char *cmd, char *data, const char *value)
208 {
209  struct ast_datastore *datastore = NULL;
210  struct pitchshift_data *shift = NULL;
211  int new = 0;
212  float amount = 0;
213 
214  if (!chan) {
215  ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
216  return -1;
217  }
218 
219  ast_channel_lock(chan);
220  if (!(datastore = ast_channel_datastore_find(chan, &pitchshift_datastore, NULL))) {
221  ast_channel_unlock(chan);
222 
223  if (!(datastore = ast_datastore_alloc(&pitchshift_datastore, NULL))) {
224  return 0;
225  }
226  if (!(shift = ast_calloc(1, sizeof(*shift)))) {
227  ast_datastore_free(datastore);
228  return 0;
229  }
230 
232  shift->audiohook.manipulate_callback = pitchshift_cb;
233  datastore->data = shift;
234  new = 1;
235  } else {
236  ast_channel_unlock(chan);
237  shift = datastore->data;
238  }
239 
240 
241  if (!strcasecmp(value, "highest")) {
242  amount = HIGHEST;
243  } else if (!strcasecmp(value, "higher")) {
244  amount = HIGHER;
245  } else if (!strcasecmp(value, "high")) {
246  amount = HIGH;
247  } else if (!strcasecmp(value, "lowest")) {
248  amount = LOWEST;
249  } else if (!strcasecmp(value, "lower")) {
250  amount = LOWER;
251  } else if (!strcasecmp(value, "low")) {
252  amount = LOW;
253  } else {
254  if (!sscanf(value, "%30f", &amount) || (amount <= 0) || (amount > 4)) {
255  goto cleanup_error;
256  }
257  }
258 
259  if (!strcasecmp(data, "rx")) {
260  shift->rx.shift_amount = amount;
261  } else if (!strcasecmp(data, "tx")) {
262  shift->tx.shift_amount = amount;
263  } else if (!strcasecmp(data, "both")) {
264  shift->rx.shift_amount = amount;
265  shift->tx.shift_amount = amount;
266  } else {
267  goto cleanup_error;
268  }
269 
270  if (new) {
271  ast_channel_lock(chan);
272  ast_channel_datastore_add(chan, datastore);
273  ast_channel_unlock(chan);
274  ast_audiohook_attach(chan, &shift->audiohook);
275  }
276 
277  return 0;
278 
279 cleanup_error:
280 
281  ast_log(LOG_ERROR, "Invalid argument provided to the %s function\n", cmd);
282  if (new) {
283  ast_datastore_free(datastore);
284  }
285  return -1;
286 }
287 
288 static void smb_fft(float *fft_buffer, long fft_frame_size, long sign)
289 {
290  float wr, wi, arg, *p1, *p2, temp;
291  float tr, ti, ur, ui, *p1r, *p1i, *p2r, *p2i;
292  long i, bitm, j, le, le2, k;
293 
294  for (i = 2; i < 2 * fft_frame_size - 2; i += 2) {
295  for (bitm = 2, j = 0; bitm < 2 * fft_frame_size; bitm <<= 1) {
296  if (i & bitm) {
297  j++;
298  }
299  j <<= 1;
300  }
301  if (i < j) {
302  p1 = fft_buffer + i; p2 = fft_buffer + j;
303  temp = *p1; *(p1++) = *p2;
304  *(p2++) = temp; temp = *p1;
305  *p1 = *p2; *p2 = temp;
306  }
307  }
308  for (k = 0, le = 2; k < (long) (log(fft_frame_size) / log(2.) + .5); k++) {
309  le <<= 1;
310  le2 = le>>1;
311  ur = 1.0;
312  ui = 0.0;
313  arg = M_PI / (le2>>1);
314  wr = cos(arg);
315  wi = sign * sin(arg);
316  for (j = 0; j < le2; j += 2) {
317  p1r = fft_buffer+j; p1i = p1r + 1;
318  p2r = p1r + le2; p2i = p2r + 1;
319  for (i = j; i < 2 * fft_frame_size; i += le) {
320  tr = *p2r * ur - *p2i * ui;
321  ti = *p2r * ui + *p2i * ur;
322  *p2r = *p1r - tr; *p2i = *p1i - ti;
323  *p1r += tr; *p1i += ti;
324  p1r += le; p1i += le;
325  p2r += le; p2i += le;
326  }
327  tr = ur * wr - ui * wi;
328  ui = ur * wi + ui * wr;
329  ur = tr;
330  }
331  }
332 }
333 
334 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)
335 {
336  float *in_fifo = fft_data->in_fifo;
337  float *out_fifo = fft_data->out_fifo;
338  float *fft_worksp = fft_data->fft_worksp;
339  float *last_phase = fft_data->last_phase;
340  float *sum_phase = fft_data->sum_phase;
341  float *output_accum = fft_data->output_accum;
342  float *ana_freq = fft_data->ana_freq;
343  float *ana_magn = fft_data->ana_magn;
344  float *syn_freq = fft_data->syn_freq;
345  float *sys_magn = fft_data->sys_magn;
346 
347  double magn, phase, tmp, window, real, imag;
348  double freq_per_bin, expect;
349  long i,k, qpd, index, in_fifo_latency, step_size, fft_frame_size2;
350 
351  /* set up some handy variables */
352  fft_frame_size2 = fft_frame_size / 2;
353  step_size = fft_frame_size / osamp;
354  freq_per_bin = sample_rate / (double) fft_frame_size;
355  expect = 2. * M_PI * (double) step_size / (double) fft_frame_size;
356  in_fifo_latency = fft_frame_size-step_size;
357 
358  if (fft_data->gRover == 0) {
359  fft_data->gRover = in_fifo_latency;
360  }
361 
362  /* main processing loop */
363  for (i = 0; i < num_samps_to_process; i++){
364 
365  /* As long as we have not yet collected enough data just read in */
366  in_fifo[fft_data->gRover] = indata[i];
367  outdata[i] = out_fifo[fft_data->gRover - in_fifo_latency];
368  fft_data->gRover++;
369 
370  /* now we have enough data for processing */
371  if (fft_data->gRover >= fft_frame_size) {
372  fft_data->gRover = in_fifo_latency;
373 
374  /* do windowing and re,im interleave */
375  for (k = 0; k < fft_frame_size;k++) {
376  window = -.5 * cos(2. * M_PI * (double) k / (double) fft_frame_size) + .5;
377  fft_worksp[2*k] = in_fifo[k] * window;
378  fft_worksp[2*k+1] = 0.;
379  }
380 
381  /* ***************** ANALYSIS ******************* */
382  /* do transform */
383  smb_fft(fft_worksp, fft_frame_size, -1);
384 
385  /* this is the analysis step */
386  for (k = 0; k <= fft_frame_size2; k++) {
387 
388  /* de-interlace FFT buffer */
389  real = fft_worksp[2*k];
390  imag = fft_worksp[2*k+1];
391 
392  /* compute magnitude and phase */
393  magn = 2. * sqrt(real * real + imag * imag);
394  phase = atan2(imag, real);
395 
396  /* compute phase difference */
397  tmp = phase - last_phase[k];
398  last_phase[k] = phase;
399 
400  /* subtract expected phase difference */
401  tmp -= (double) k * expect;
402 
403  /* map delta phase into +/- Pi interval */
404  qpd = tmp / M_PI;
405  if (qpd >= 0) {
406  qpd += qpd & 1;
407  } else {
408  qpd -= qpd & 1;
409  }
410  tmp -= M_PI * (double) qpd;
411 
412  /* get deviation from bin frequency from the +/- Pi interval */
413  tmp = osamp * tmp / (2. * M_PI);
414 
415  /* compute the k-th partials' true frequency */
416  tmp = (double) k * freq_per_bin + tmp * freq_per_bin;
417 
418  /* store magnitude and true frequency in analysis arrays */
419  ana_magn[k] = magn;
420  ana_freq[k] = tmp;
421 
422  }
423 
424  /* ***************** PROCESSING ******************* */
425  /* this does the actual pitch shifting */
426  memset(sys_magn, 0, fft_frame_size * sizeof(float));
427  memset(syn_freq, 0, fft_frame_size * sizeof(float));
428  for (k = 0; k <= fft_frame_size2; k++) {
429  index = k * pitchShift;
430  if (index <= fft_frame_size2) {
431  sys_magn[index] += ana_magn[k];
432  syn_freq[index] = ana_freq[k] * pitchShift;
433  }
434  }
435 
436  /* ***************** SYNTHESIS ******************* */
437  /* this is the synthesis step */
438  for (k = 0; k <= fft_frame_size2; k++) {
439 
440  /* get magnitude and true frequency from synthesis arrays */
441  magn = sys_magn[k];
442  tmp = syn_freq[k];
443 
444  /* subtract bin mid frequency */
445  tmp -= (double) k * freq_per_bin;
446 
447  /* get bin deviation from freq deviation */
448  tmp /= freq_per_bin;
449 
450  /* take osamp into account */
451  tmp = 2. * M_PI * tmp / osamp;
452 
453  /* add the overlap phase advance back in */
454  tmp += (double) k * expect;
455 
456  /* accumulate delta phase to get bin phase */
457  sum_phase[k] += tmp;
458  phase = sum_phase[k];
459 
460  /* get real and imag part and re-interleave */
461  fft_worksp[2*k] = magn * cos(phase);
462  fft_worksp[2*k+1] = magn * sin(phase);
463  }
464 
465  /* zero negative frequencies */
466  for (k = fft_frame_size + 2; k < 2 * fft_frame_size; k++) {
467  fft_worksp[k] = 0.;
468  }
469 
470  /* do inverse transform */
471  smb_fft(fft_worksp, fft_frame_size, 1);
472 
473  /* do windowing and add to output accumulator */
474  for (k = 0; k < fft_frame_size; k++) {
475  window = -.5 * cos(2. * M_PI * (double) k / (double) fft_frame_size) + .5;
476  output_accum[k] += 2. * window * fft_worksp[2*k] / (fft_frame_size2 * osamp);
477  }
478  for (k = 0; k < step_size; k++) {
479  out_fifo[k] = output_accum[k];
480  }
481 
482  /* shift accumulator */
483  memmove(output_accum, output_accum+step_size, fft_frame_size * sizeof(float));
484 
485  /* move input FIFO */
486  for (k = 0; k < in_fifo_latency; k++) {
487  in_fifo[k] = in_fifo[k+step_size];
488  }
489  }
490  }
491 }
492 
493 static int pitch_shift(struct ast_frame *f, float amount, struct fft_data *fft)
494 {
495  int16_t *fun = (int16_t *) f->data.ptr;
496  int samples;
497 
498  /* an amount of 1 has no effect */
499  if (!amount || amount == 1 || !fun || (f->samples % 32)) {
500  return 0;
501  }
502  for (samples = 0; samples < f->samples; samples += 32) {
503  smb_pitch_shift(amount, 32, MAX_FRAME_LENGTH, 32, ast_format_get_sample_rate(f->subclass.format), fun+samples, fun+samples, fft);
504  }
505 
506  return 0;
507 }
508 
509 static struct ast_custom_function pitch_shift_function = {
510  .name = "PITCH_SHIFT",
511  .write = pitchshift_helper,
512 };
513 
514 static int unload_module(void)
515 {
516  return ast_custom_function_unregister(&pitch_shift_function);
517 }
518 
519 static int load_module(void)
520 {
521  int res = ast_custom_function_register(&pitch_shift_function);
523 }
524 
525 AST_MODULE_INFO_STANDARD_EXTENDED(ASTERISK_GPL_KEY, "Audio Effects Dialplan Functions");
const char * name
Definition: pbx.h:119
const char * type
Definition: datastore.h:32
Main Channel structure associated with a channel.
Asterisk main include file. File version handling, generic pbx functions.
Audiohooks Architecture.
Structure for a data store type.
Definition: datastore.h:31
int ast_audiohook_attach(struct ast_channel *chan, struct ast_audiohook *audiohook)
Attach audiohook to channel.
Definition: audiohook.c:484
Structure for a data store object.
Definition: datastore.h:64
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:2399
int ast_audiohook_destroy(struct ast_audiohook *audiohook)
Destroys an audiohook structure.
Definition: audiohook.c:124
int ast_custom_function_unregister(struct ast_custom_function *acf)
Unregister a custom function.
int ast_datastore_free(struct ast_datastore *datastore)
Free a data store object.
Definition: datastore.c:68
struct ast_frame_subclass subclass
Utility functions.
ast_audiohook_manipulate_callback manipulate_callback
Definition: audiohook.h:118
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
General Asterisk PBX channel definitions.
Data structure associated with a custom dialplan function.
Definition: pbx.h:118
Core PBX routines and definitions.
static void destroy_callback(void *data)
Helper function used by datastores to destroy the speech structure upon hangup.
union ast_frame::@224 data
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:202
Module has failed to load, may be in an inconsistent state.
Definition: module.h:78
ast_audiohook_direction
Definition: audiohook.h:48
void * data
Definition: datastore.h:66
unsigned int ast_format_get_sample_rate(const struct ast_format *format)
Get the sample rate of a media format.
Definition: format.c:379
Data structure associated with a single frame of data.
enum ast_audiohook_status status
Definition: audiohook.h:108
struct ast_format * format
#define ASTERISK_GPL_KEY
The text the key() function should return.
Definition: module.h:46
Asterisk module definitions.
int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
Add a datastore to a channel.
Definition: channel.c:2385
#define ast_custom_function_register(acf)
Register a custom function.
Definition: pbx.h:1558