test-resample.cpp revision e00eefe64e3bad166c672db96c9c35992766e819
1/*
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>
28#include <math.h>
29
30using namespace android;
31
32bool gVerbose = false;
33
34struct HeaderWav {
35    HeaderWav(size_t size, int nc, int sr, int bits) {
36        strncpy(RIFF, "RIFF", 4);
37        chunkSize = size + sizeof(HeaderWav);
38        strncpy(WAVE, "WAVE", 4);
39        strncpy(fmt,  "fmt ", 4);
40        fmtSize = 16;
41        audioFormat = 1;
42        numChannels = nc;
43        samplesRate = sr;
44        byteRate = sr * numChannels * (bits/8);
45        align = nc*(bits/8);
46        bitsPerSample = bits;
47        strncpy(data, "data", 4);
48        dataSize = size;
49    }
50
51    char RIFF[4];           // RIFF
52    uint32_t chunkSize;     // File size
53    char WAVE[4];        // WAVE
54    char fmt[4];            // fmt\0
55    uint32_t fmtSize;       // fmt size
56    uint16_t audioFormat;   // 1=PCM
57    uint16_t numChannels;   // num channels
58    uint32_t samplesRate;   // sample rate in hz
59    uint32_t byteRate;      // Bps
60    uint16_t align;         // 2=16-bit mono, 4=16-bit stereo
61    uint16_t bitsPerSample; // bits per sample
62    char data[4];           // "data"
63    uint32_t dataSize;      // size
64};
65
66static int usage(const char* name) {
67    fprintf(stderr,"Usage: %s [-p] [-h] [-v] [-s] [-q {dq|lq|mq|hq|vhq}] [-i input-sample-rate] "
68                   "[-o output-sample-rate] [<input-file>] <output-file>\n", name);
69    fprintf(stderr,"    -p    enable profiling\n");
70    fprintf(stderr,"    -h    create wav file\n");
71    fprintf(stderr,"    -v    verbose : log buffer provider calls\n");
72    fprintf(stderr,"    -s    stereo\n");
73    fprintf(stderr,"    -q    resampler quality\n");
74    fprintf(stderr,"              dq  : default quality\n");
75    fprintf(stderr,"              lq  : low quality\n");
76    fprintf(stderr,"              mq  : medium quality\n");
77    fprintf(stderr,"              hq  : high quality\n");
78    fprintf(stderr,"              vhq : very high quality\n");
79    fprintf(stderr,"    -i    input file sample rate\n");
80    fprintf(stderr,"    -o    output file sample rate\n");
81    return -1;
82}
83
84int main(int argc, char* argv[]) {
85
86    const char* const progname = argv[0];
87    bool profiling = false;
88    bool writeHeader = false;
89    int channels = 1;
90    int input_freq = 0;
91    int output_freq = 0;
92    AudioResampler::src_quality quality = AudioResampler::DEFAULT_QUALITY;
93
94    int ch;
95    while ((ch = getopt(argc, argv, "phvsq:i:o:")) != -1) {
96        switch (ch) {
97        case 'p':
98            profiling = true;
99            break;
100        case 'h':
101            writeHeader = true;
102            break;
103        case 'v':
104            gVerbose = true;
105            break;
106        case 's':
107            channels = 2;
108            break;
109        case 'q':
110            if (!strcmp(optarg, "dq"))
111                quality = AudioResampler::DEFAULT_QUALITY;
112            else if (!strcmp(optarg, "lq"))
113                quality = AudioResampler::LOW_QUALITY;
114            else if (!strcmp(optarg, "mq"))
115                quality = AudioResampler::MED_QUALITY;
116            else if (!strcmp(optarg, "hq"))
117                quality = AudioResampler::HIGH_QUALITY;
118            else if (!strcmp(optarg, "vhq"))
119                quality = AudioResampler::VERY_HIGH_QUALITY;
120            else {
121                usage(progname);
122                return -1;
123            }
124            break;
125        case 'i':
126            input_freq = atoi(optarg);
127            break;
128        case 'o':
129            output_freq = atoi(optarg);
130            break;
131        case '?':
132        default:
133            usage(progname);
134            return -1;
135        }
136    }
137    argc -= optind;
138    argv += optind;
139
140    const char* file_in = NULL;
141    const char* file_out = NULL;
142    if (argc == 1) {
143        file_out = argv[0];
144    } else if (argc == 2) {
145        file_in = argv[0];
146        file_out = argv[1];
147    } else {
148        usage(progname);
149        return -1;
150    }
151
152    // ----------------------------------------------------------
153
154    size_t input_size;
155    void* input_vaddr;
156    if (argc == 2) {
157        struct stat st;
158        if (stat(file_in, &st) < 0) {
159            fprintf(stderr, "stat: %s\n", strerror(errno));
160            return -1;
161        }
162
163        int input_fd = open(file_in, O_RDONLY);
164        if (input_fd < 0) {
165            fprintf(stderr, "open: %s\n", strerror(errno));
166            return -1;
167        }
168
169        input_size = st.st_size;
170        input_vaddr = mmap(0, input_size, PROT_READ, MAP_PRIVATE, input_fd, 0);
171        if (input_vaddr == MAP_FAILED ) {
172            fprintf(stderr, "mmap: %s\n", strerror(errno));
173            return -1;
174        }
175    } else {
176        double k = 1000; // Hz / s
177        double time = (input_freq / 2) / k;
178        size_t input_frames = size_t(input_freq * time);
179        input_size = channels * sizeof(int16_t) * input_frames;
180        input_vaddr = malloc(input_size);
181        int16_t* in = (int16_t*)input_vaddr;
182        for (size_t i=0 ; i<input_frames ; i++) {
183            double t = double(i) / input_freq;
184            double y = sin(M_PI * k * t * t);
185            int16_t yi = floor(y * 32767.0 + 0.5);
186            for (size_t j=0 ; j<(size_t)channels ; j++) {
187                in[i*channels + j] = yi / (1+j);
188            }
189        }
190    }
191
192    // ----------------------------------------------------------
193
194    class Provider: public AudioBufferProvider {
195        int16_t* const  mAddr;      // base address
196        const size_t    mNumFrames; // total frames
197        const int       mChannels;
198        size_t          mNextFrame; // index of next frame to provide
199        size_t          mUnrel;     // number of frames not yet released
200    public:
201        Provider(const void* addr, size_t size, int channels)
202          : mAddr((int16_t*) addr),
203            mNumFrames(size / (channels*sizeof(int16_t))),
204            mChannels(channels),
205            mNextFrame(0), mUnrel(0) {
206        }
207        virtual status_t getNextBuffer(Buffer* buffer,
208                int64_t pts = kInvalidPTS) {
209            size_t requestedFrames = buffer->frameCount;
210            if (requestedFrames > mNumFrames - mNextFrame) {
211                buffer->frameCount = mNumFrames - mNextFrame;
212            }
213            if (gVerbose) {
214                printf("getNextBuffer() requested %u frames out of %u frames available,"
215                        " and returned %u frames\n",
216                        requestedFrames, mNumFrames - mNextFrame, buffer->frameCount);
217            }
218            mUnrel = buffer->frameCount;
219            if (buffer->frameCount > 0) {
220                buffer->i16 = &mAddr[mChannels * mNextFrame];
221                return NO_ERROR;
222            } else {
223                buffer->i16 = NULL;
224                return NOT_ENOUGH_DATA;
225            }
226        }
227        virtual void releaseBuffer(Buffer* buffer) {
228            if (buffer->frameCount > mUnrel) {
229                fprintf(stderr, "ERROR releaseBuffer() released %u frames but only %u available "
230                        "to release\n", buffer->frameCount, mUnrel);
231                mNextFrame += mUnrel;
232                mUnrel = 0;
233            } else {
234                if (gVerbose) {
235                    printf("releaseBuffer() released %u frames out of %u frames available "
236                            "to release\n", buffer->frameCount, mUnrel);
237                }
238                mNextFrame += buffer->frameCount;
239                mUnrel -= buffer->frameCount;
240            }
241        }
242    } provider(input_vaddr, input_size, channels);
243
244    size_t input_frames = input_size / (channels * sizeof(int16_t));
245    if (gVerbose) {
246        printf("%u input frames\n", input_frames);
247    }
248    size_t output_size = 2 * 4 * ((int64_t) input_frames * output_freq) / input_freq;
249    output_size &= ~7; // always stereo, 32-bits
250
251    void* output_vaddr = malloc(output_size);
252
253    if (profiling) {
254        AudioResampler* resampler = AudioResampler::create(16, channels,
255                output_freq, quality);
256
257        size_t out_frames = output_size/8;
258        resampler->setSampleRate(input_freq);
259        resampler->setVolume(0x1000, 0x1000);
260
261        memset(output_vaddr, 0, output_size);
262        timespec start, end;
263        clock_gettime(CLOCK_MONOTONIC, &start);
264        resampler->resample((int*) output_vaddr, out_frames, &provider);
265        resampler->resample((int*) output_vaddr, out_frames, &provider);
266        resampler->resample((int*) output_vaddr, out_frames, &provider);
267        resampler->resample((int*) output_vaddr, out_frames, &provider);
268        clock_gettime(CLOCK_MONOTONIC, &end);
269        int64_t start_ns = start.tv_sec * 1000000000LL + start.tv_nsec;
270        int64_t end_ns = end.tv_sec * 1000000000LL + end.tv_nsec;
271        int64_t time = (end_ns - start_ns)/4;
272        printf("%f Mspl/s\n", out_frames/(time/1e9)/1e6);
273
274        delete resampler;
275    }
276
277    AudioResampler* resampler = AudioResampler::create(16, channels,
278            output_freq, quality);
279    size_t out_frames = output_size/8;
280    resampler->setSampleRate(input_freq);
281    resampler->setVolume(0x1000, 0x1000);
282
283    memset(output_vaddr, 0, output_size);
284    if (gVerbose) {
285        printf("resample() %u output frames\n", out_frames);
286    }
287    resampler->resample((int*) output_vaddr, out_frames, &provider);
288    if (gVerbose) {
289        printf("resample() complete\n");
290    }
291    resampler->reset();
292    if (gVerbose) {
293        printf("reset() complete\n");
294    }
295
296    // down-mix (we just truncate and keep the left channel)
297    int32_t* out = (int32_t*) output_vaddr;
298    int16_t* convert = (int16_t*) malloc(out_frames * channels * sizeof(int16_t));
299    for (size_t i = 0; i < out_frames; i++) {
300        for (int j=0 ; j<channels ; j++) {
301            int32_t s = out[i * 2 + j] >> 12;
302            if (s > 32767)       s =  32767;
303            else if (s < -32768) s = -32768;
304            convert[i * channels + j] = int16_t(s);
305        }
306    }
307
308    // write output to disk
309    int output_fd = open(file_out, O_WRONLY | O_CREAT | O_TRUNC,
310            S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
311    if (output_fd < 0) {
312        fprintf(stderr, "open: %s\n", strerror(errno));
313        return -1;
314    }
315
316    if (writeHeader) {
317        HeaderWav wav(out_frames * channels * sizeof(int16_t), channels, output_freq, 16);
318        write(output_fd, &wav, sizeof(wav));
319    }
320
321    write(output_fd, convert, out_frames * channels * sizeof(int16_t));
322    close(output_fd);
323
324    return 0;
325}
326