blob: 74d57020bc3b80e8d11c7dbe23fe7a655f626ad4 [file] [log] [blame]
Mathias Agopian0fc2cb52012-10-21 01:01:38 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "AudioResampler.h"
18#include <media/AudioBufferProvider.h>
19#include <unistd.h>
20#include <stdio.h>
21#include <stdlib.h>
22#include <fcntl.h>
23#include <string.h>
24#include <sys/mman.h>
25#include <sys/stat.h>
26#include <errno.h>
27#include <time.h>
Mathias Agopian3f717612012-11-04 18:49:14 -080028#include <math.h>
Glenn Kastenf5293642013-12-17 14:49:17 -080029#include <audio_utils/sndfile.h>
Mathias Agopian0fc2cb52012-10-21 01:01:38 -070030
31using namespace android;
32
Glenn Kastene00eefe2013-12-17 13:54:29 -080033bool gVerbose = false;
34
Mathias Agopian0fc2cb52012-10-21 01:01:38 -070035static int usage(const char* name) {
Andy Hung86eae0e2013-12-09 12:12:46 -080036 fprintf(stderr,"Usage: %s [-p] [-h] [-v] [-s] [-q {dq|lq|mq|hq|vhq|dlq|dmq|dhq}]"
Glenn Kasten56df9ff2014-02-17 14:57:27 -080037 " [-i input-sample-rate] [-o output-sample-rate] [-O #] [<input-file>]"
Andy Hung86eae0e2013-12-09 12:12:46 -080038 " <output-file>\n", name);
Mathias Agopian3f717612012-11-04 18:49:14 -080039 fprintf(stderr," -p enable profiling\n");
40 fprintf(stderr," -h create wav file\n");
Glenn Kastene00eefe2013-12-17 13:54:29 -080041 fprintf(stderr," -v verbose : log buffer provider calls\n");
Glenn Kastenbd72d222013-12-17 15:22:08 -080042 fprintf(stderr," -s stereo (ignored if input file is specified)\n");
Mathias Agopian3f717612012-11-04 18:49:14 -080043 fprintf(stderr," -q resampler quality\n");
44 fprintf(stderr," dq : default quality\n");
45 fprintf(stderr," lq : low quality\n");
46 fprintf(stderr," mq : medium quality\n");
47 fprintf(stderr," hq : high quality\n");
48 fprintf(stderr," vhq : very high quality\n");
Andy Hung86eae0e2013-12-09 12:12:46 -080049 fprintf(stderr," dlq : dynamic low quality\n");
50 fprintf(stderr," dmq : dynamic medium quality\n");
51 fprintf(stderr," dhq : dynamic high quality\n");
Glenn Kastenbd72d222013-12-17 15:22:08 -080052 fprintf(stderr," -i input file sample rate (ignored if input file is specified)\n");
Mathias Agopian3f717612012-11-04 18:49:14 -080053 fprintf(stderr," -o output file sample rate\n");
Glenn Kasten56df9ff2014-02-17 14:57:27 -080054 fprintf(stderr," -O # frames output per call to resample()\n");
Mathias Agopian0fc2cb52012-10-21 01:01:38 -070055 return -1;
56}
57
58int main(int argc, char* argv[]) {
59
Mathias Agopian3f717612012-11-04 18:49:14 -080060 const char* const progname = argv[0];
Andy Hung6582f2b2014-01-03 12:30:41 -080061 bool profileResample = false;
62 bool profileFilter = false;
Mathias Agopian0fc2cb52012-10-21 01:01:38 -070063 bool writeHeader = false;
Mathias Agopian3f717612012-11-04 18:49:14 -080064 int channels = 1;
Mathias Agopian0fc2cb52012-10-21 01:01:38 -070065 int input_freq = 0;
66 int output_freq = 0;
67 AudioResampler::src_quality quality = AudioResampler::DEFAULT_QUALITY;
Glenn Kasten56df9ff2014-02-17 14:57:27 -080068 size_t framesPerCall = 0;
Mathias Agopian0fc2cb52012-10-21 01:01:38 -070069
70 int ch;
Glenn Kasten56df9ff2014-02-17 14:57:27 -080071 while ((ch = getopt(argc, argv, "pfhvsq:i:o:O:")) != -1) {
Mathias Agopian0fc2cb52012-10-21 01:01:38 -070072 switch (ch) {
73 case 'p':
Andy Hung6582f2b2014-01-03 12:30:41 -080074 profileResample = true;
75 break;
76 case 'f':
77 profileFilter = true;
Mathias Agopian0fc2cb52012-10-21 01:01:38 -070078 break;
79 case 'h':
80 writeHeader = true;
81 break;
Glenn Kastene00eefe2013-12-17 13:54:29 -080082 case 'v':
83 gVerbose = true;
84 break;
Mathias Agopian3f717612012-11-04 18:49:14 -080085 case 's':
86 channels = 2;
87 break;
Mathias Agopian0fc2cb52012-10-21 01:01:38 -070088 case 'q':
89 if (!strcmp(optarg, "dq"))
90 quality = AudioResampler::DEFAULT_QUALITY;
91 else if (!strcmp(optarg, "lq"))
92 quality = AudioResampler::LOW_QUALITY;
93 else if (!strcmp(optarg, "mq"))
94 quality = AudioResampler::MED_QUALITY;
95 else if (!strcmp(optarg, "hq"))
96 quality = AudioResampler::HIGH_QUALITY;
97 else if (!strcmp(optarg, "vhq"))
98 quality = AudioResampler::VERY_HIGH_QUALITY;
Andy Hung86eae0e2013-12-09 12:12:46 -080099 else if (!strcmp(optarg, "dlq"))
100 quality = AudioResampler::DYN_LOW_QUALITY;
101 else if (!strcmp(optarg, "dmq"))
102 quality = AudioResampler::DYN_MED_QUALITY;
103 else if (!strcmp(optarg, "dhq"))
104 quality = AudioResampler::DYN_HIGH_QUALITY;
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700105 else {
Mathias Agopian3f717612012-11-04 18:49:14 -0800106 usage(progname);
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700107 return -1;
108 }
109 break;
110 case 'i':
111 input_freq = atoi(optarg);
112 break;
113 case 'o':
114 output_freq = atoi(optarg);
115 break;
Glenn Kasten56df9ff2014-02-17 14:57:27 -0800116 case 'O':
117 framesPerCall = atoi(optarg);
118 break;
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700119 case '?':
120 default:
Mathias Agopian3f717612012-11-04 18:49:14 -0800121 usage(progname);
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700122 return -1;
123 }
124 }
125 argc -= optind;
Mathias Agopian3f717612012-11-04 18:49:14 -0800126 argv += optind;
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700127
Mathias Agopian3f717612012-11-04 18:49:14 -0800128 const char* file_in = NULL;
129 const char* file_out = NULL;
130 if (argc == 1) {
131 file_out = argv[0];
132 } else if (argc == 2) {
133 file_in = argv[0];
134 file_out = argv[1];
135 } else {
136 usage(progname);
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700137 return -1;
138 }
139
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700140 // ----------------------------------------------------------
141
Mathias Agopian3f717612012-11-04 18:49:14 -0800142 size_t input_size;
143 void* input_vaddr;
144 if (argc == 2) {
Glenn Kastenbd72d222013-12-17 15:22:08 -0800145 SF_INFO info;
146 info.format = 0;
147 SNDFILE *sf = sf_open(file_in, SFM_READ, &info);
148 if (sf == NULL) {
149 perror(file_in);
150 return EXIT_FAILURE;
Mathias Agopian3f717612012-11-04 18:49:14 -0800151 }
Glenn Kastenbd72d222013-12-17 15:22:08 -0800152 input_size = info.frames * info.channels * sizeof(short);
153 input_vaddr = malloc(input_size);
154 (void) sf_readf_short(sf, (short *) input_vaddr, info.frames);
155 sf_close(sf);
156 channels = info.channels;
157 input_freq = info.samplerate;
Mathias Agopian3f717612012-11-04 18:49:14 -0800158 } else {
Andy Hung86eae0e2013-12-09 12:12:46 -0800159 // data for testing is exactly (input sampling rate/1000)/2 seconds
160 // so 44.1khz input is 22.05 seconds
Mathias Agopian3f717612012-11-04 18:49:14 -0800161 double k = 1000; // Hz / s
162 double time = (input_freq / 2) / k;
163 size_t input_frames = size_t(input_freq * time);
164 input_size = channels * sizeof(int16_t) * input_frames;
165 input_vaddr = malloc(input_size);
166 int16_t* in = (int16_t*)input_vaddr;
167 for (size_t i=0 ; i<input_frames ; i++) {
168 double t = double(i) / input_freq;
169 double y = sin(M_PI * k * t * t);
170 int16_t yi = floor(y * 32767.0 + 0.5);
Glenn Kastenb26e3e92012-11-14 08:32:08 -0800171 for (size_t j=0 ; j<(size_t)channels ; j++) {
Andy Hung86eae0e2013-12-09 12:12:46 -0800172 in[i*channels + j] = yi / (1+j); // right ch. 1/2 left ch.
Mathias Agopian3f717612012-11-04 18:49:14 -0800173 }
174 }
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700175 }
176
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700177 // ----------------------------------------------------------
178
179 class Provider: public AudioBufferProvider {
Glenn Kastene00eefe2013-12-17 13:54:29 -0800180 int16_t* const mAddr; // base address
181 const size_t mNumFrames; // total frames
182 const int mChannels;
183 size_t mNextFrame; // index of next frame to provide
184 size_t mUnrel; // number of frames not yet released
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700185 public:
Glenn Kastene00eefe2013-12-17 13:54:29 -0800186 Provider(const void* addr, size_t size, int channels)
187 : mAddr((int16_t*) addr),
188 mNumFrames(size / (channels*sizeof(int16_t))),
189 mChannels(channels),
190 mNextFrame(0), mUnrel(0) {
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700191 }
192 virtual status_t getNextBuffer(Buffer* buffer,
193 int64_t pts = kInvalidPTS) {
Andy Hung86eae0e2013-12-09 12:12:46 -0800194 (void)pts; // suppress warning
Glenn Kastene00eefe2013-12-17 13:54:29 -0800195 size_t requestedFrames = buffer->frameCount;
196 if (requestedFrames > mNumFrames - mNextFrame) {
197 buffer->frameCount = mNumFrames - mNextFrame;
198 }
199 if (gVerbose) {
200 printf("getNextBuffer() requested %u frames out of %u frames available,"
201 " and returned %u frames\n",
202 requestedFrames, mNumFrames - mNextFrame, buffer->frameCount);
203 }
204 mUnrel = buffer->frameCount;
205 if (buffer->frameCount > 0) {
206 buffer->i16 = &mAddr[mChannels * mNextFrame];
207 return NO_ERROR;
208 } else {
209 buffer->i16 = NULL;
210 return NOT_ENOUGH_DATA;
211 }
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700212 }
213 virtual void releaseBuffer(Buffer* buffer) {
Glenn Kastene00eefe2013-12-17 13:54:29 -0800214 if (buffer->frameCount > mUnrel) {
215 fprintf(stderr, "ERROR releaseBuffer() released %u frames but only %u available "
216 "to release\n", buffer->frameCount, mUnrel);
217 mNextFrame += mUnrel;
218 mUnrel = 0;
219 } else {
220 if (gVerbose) {
221 printf("releaseBuffer() released %u frames out of %u frames available "
222 "to release\n", buffer->frameCount, mUnrel);
223 }
224 mNextFrame += buffer->frameCount;
225 mUnrel -= buffer->frameCount;
226 }
Glenn Kasten47f3f5a2013-12-17 16:14:04 -0800227 buffer->frameCount = 0;
228 buffer->i16 = NULL;
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700229 }
Andy Hung86eae0e2013-12-09 12:12:46 -0800230 void reset() {
231 mNextFrame = 0;
232 }
Mathias Agopian3f717612012-11-04 18:49:14 -0800233 } provider(input_vaddr, input_size, channels);
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700234
Mathias Agopian3f717612012-11-04 18:49:14 -0800235 size_t input_frames = input_size / (channels * sizeof(int16_t));
Glenn Kastene00eefe2013-12-17 13:54:29 -0800236 if (gVerbose) {
237 printf("%u input frames\n", input_frames);
238 }
Mathias Agopian3f717612012-11-04 18:49:14 -0800239 size_t output_size = 2 * 4 * ((int64_t) input_frames * output_freq) / input_freq;
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700240 output_size &= ~7; // always stereo, 32-bits
241
Andy Hung6582f2b2014-01-03 12:30:41 -0800242 if (profileFilter) {
243 // Check how fast sample rate changes are that require filter changes.
244 // The delta sample rate changes must indicate a downsampling ratio,
245 // and must be larger than 10% changes.
246 //
247 // On fast devices, filters should be generated between 0.1ms - 1ms.
248 // (single threaded).
249 AudioResampler* resampler = AudioResampler::create(16, channels,
250 8000, quality);
251 int looplimit = 100;
Andy Hung86eae0e2013-12-09 12:12:46 -0800252 timespec start, end;
253 clock_gettime(CLOCK_MONOTONIC, &start);
254 for (int i = 0; i < looplimit; ++i) {
Andy Hung6582f2b2014-01-03 12:30:41 -0800255 resampler->setSampleRate(9000);
256 resampler->setSampleRate(12000);
257 resampler->setSampleRate(20000);
258 resampler->setSampleRate(30000);
Andy Hung86eae0e2013-12-09 12:12:46 -0800259 }
260 clock_gettime(CLOCK_MONOTONIC, &end);
261 int64_t start_ns = start.tv_sec * 1000000000LL + start.tv_nsec;
262 int64_t end_ns = end.tv_sec * 1000000000LL + end.tv_nsec;
263 int64_t time = end_ns - start_ns;
Andy Hung6582f2b2014-01-03 12:30:41 -0800264 printf("%.2f sample rate changes with filter calculation/sec\n",
265 looplimit * 4 / (time / 1e9));
266
267 // Check how fast sample rate changes are without filter changes.
268 // This should be very fast, probably 0.1us - 1us per sample rate
269 // change.
270 resampler->setSampleRate(1000);
271 looplimit = 1000;
272 clock_gettime(CLOCK_MONOTONIC, &start);
273 for (int i = 0; i < looplimit; ++i) {
274 resampler->setSampleRate(1000+i);
275 }
276 clock_gettime(CLOCK_MONOTONIC, &end);
277 start_ns = start.tv_sec * 1000000000LL + start.tv_nsec;
278 end_ns = end.tv_sec * 1000000000LL + end.tv_nsec;
279 time = end_ns - start_ns;
280 printf("%.2f sample rate changes without filter calculation/sec\n",
281 looplimit / (time / 1e9));
282 resampler->reset();
283 delete resampler;
284 }
285
286 void* output_vaddr = malloc(output_size);
287 AudioResampler* resampler = AudioResampler::create(16, channels,
288 output_freq, quality);
289 size_t out_frames = output_size/8;
290
291 /* set volume precision to 12 bits, so the volume scale is 1<<12.
292 * This means the "integer" part fits in the Q19.12 precision
293 * representation of output int32_t.
294 *
295 * Generally 0 < volumePrecision <= 14 (due to the limits of
296 * int16_t values for Volume). volumePrecision cannot be 0 due
297 * to rounding and shifts.
298 */
299 const int volumePrecision = 12; // in bits
300
301 resampler->setSampleRate(input_freq);
302 resampler->setVolume(1 << volumePrecision, 1 << volumePrecision);
303
304 if (profileResample) {
305 /*
306 * For profiling on mobile devices, upon experimentation
307 * it is better to run a few trials with a shorter loop limit,
308 * and take the minimum time.
309 *
310 * Long tests can cause CPU temperature to build up and thermal throttling
311 * to reduce CPU frequency.
312 *
313 * For frequency checks (index=0, or 1, etc.):
314 * "cat /sys/devices/system/cpu/cpu${index}/cpufreq/scaling_*_freq"
315 *
316 * For temperature checks (index=0, or 1, etc.):
317 * "cat /sys/class/thermal/thermal_zone${index}/temp"
318 *
319 * Another way to avoid thermal throttling is to fix the CPU frequency
320 * at a lower level which prevents excessive temperatures.
321 */
322 const int trials = 4;
323 const int looplimit = 4;
324 timespec start, end;
325 int64_t time;
326
327 for (int n = 0; n < trials; ++n) {
328 clock_gettime(CLOCK_MONOTONIC, &start);
329 for (int i = 0; i < looplimit; ++i) {
330 resampler->resample((int*) output_vaddr, out_frames, &provider);
331 provider.reset(); // during benchmarking reset only the provider
332 }
333 clock_gettime(CLOCK_MONOTONIC, &end);
334 int64_t start_ns = start.tv_sec * 1000000000LL + start.tv_nsec;
335 int64_t end_ns = end.tv_sec * 1000000000LL + end.tv_nsec;
336 int64_t diff_ns = end_ns - start_ns;
337 if (n == 0 || diff_ns < time) {
338 time = diff_ns; // save the best out of our trials.
339 }
340 }
341 // Mfrms/s is "Millions of output frames per second".
342 printf("quality: %d channels: %d msec: %lld Mfrms/s: %.2lf\n",
343 quality, channels, time/1000000, out_frames * looplimit / (time / 1e9) / 1e6);
Andy Hung86eae0e2013-12-09 12:12:46 -0800344 resampler->reset();
345 }
346
Mathias Agopian3f717612012-11-04 18:49:14 -0800347 memset(output_vaddr, 0, output_size);
Glenn Kastene00eefe2013-12-17 13:54:29 -0800348 if (gVerbose) {
349 printf("resample() %u output frames\n", out_frames);
350 }
Glenn Kasten56df9ff2014-02-17 14:57:27 -0800351 if (framesPerCall == 0 || framesPerCall > out_frames) {
352 framesPerCall = out_frames;
353 }
354 for (size_t i = 0; i < out_frames; ) {
355 size_t thisFrames = framesPerCall <= out_frames - i ? framesPerCall : out_frames - i;
356 resampler->resample((int*) output_vaddr + 2*i, thisFrames, &provider);
357 i += thisFrames;
358 }
Glenn Kastene00eefe2013-12-17 13:54:29 -0800359 if (gVerbose) {
360 printf("resample() complete\n");
361 }
362 resampler->reset();
363 if (gVerbose) {
364 printf("reset() complete\n");
365 }
Andy Hung6582f2b2014-01-03 12:30:41 -0800366 delete resampler;
367 resampler = NULL;
Mathias Agopian3f717612012-11-04 18:49:14 -0800368
Andy Hung86eae0e2013-12-09 12:12:46 -0800369 // mono takes left channel only
370 // stereo right channel is half amplitude of stereo left channel (due to input creation)
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700371 int32_t* out = (int32_t*) output_vaddr;
Mathias Agopian3f717612012-11-04 18:49:14 -0800372 int16_t* convert = (int16_t*) malloc(out_frames * channels * sizeof(int16_t));
Andy Hung86eae0e2013-12-09 12:12:46 -0800373
Andy Hung6582f2b2014-01-03 12:30:41 -0800374 // round to half towards zero and saturate at int16 (non-dithered)
375 const int roundVal = (1<<(volumePrecision-1)) - 1; // volumePrecision > 0
376
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700377 for (size_t i = 0; i < out_frames; i++) {
Andy Hung86eae0e2013-12-09 12:12:46 -0800378 for (int j = 0; j < channels; j++) {
Andy Hung6582f2b2014-01-03 12:30:41 -0800379 int32_t s = out[i * 2 + j] + roundVal; // add offset here
380 if (s < 0) {
381 s = (s + 1) >> volumePrecision; // round to 0
382 if (s < -32768) {
383 s = -32768;
384 }
385 } else {
386 s = s >> volumePrecision;
387 if (s > 32767) {
388 s = 32767;
389 }
390 }
Mathias Agopian3f717612012-11-04 18:49:14 -0800391 convert[i * channels + j] = int16_t(s);
392 }
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700393 }
394
395 // write output to disk
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700396 if (writeHeader) {
Glenn Kastenf5293642013-12-17 14:49:17 -0800397 SF_INFO info;
398 info.frames = 0;
399 info.samplerate = output_freq;
400 info.channels = channels;
401 info.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
402 SNDFILE *sf = sf_open(file_out, SFM_WRITE, &info);
403 if (sf == NULL) {
404 perror(file_out);
405 return EXIT_FAILURE;
406 }
407 (void) sf_writef_short(sf, convert, out_frames);
408 sf_close(sf);
409 } else {
410 int output_fd = open(file_out, O_WRONLY | O_CREAT | O_TRUNC,
411 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
412 if (output_fd < 0) {
413 perror(file_out);
414 return EXIT_FAILURE;
415 }
416 write(output_fd, convert, out_frames * channels * sizeof(int16_t));
417 close(output_fd);
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700418 }
419
Glenn Kastenf5293642013-12-17 14:49:17 -0800420 return EXIT_SUCCESS;
Mathias Agopian0fc2cb52012-10-21 01:01:38 -0700421}