merge manifest file
[external/opencore-amr.git] / test / wav.cpp
1 /* ------------------------------------------------------------------
2  * Copyright (C) 2009 Martin Storsjo
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
13  * express or implied.
14  * See the License for the specific language governing permissions
15  * and limitations under the License.
16  * -------------------------------------------------------------------
17  */
18
19 #include "wav.h"
20
21 void WavWriter::writeString(const char *str) {
22         fputc(str[0], wav);
23         fputc(str[1], wav);
24         fputc(str[2], wav);
25         fputc(str[3], wav);
26 }
27
28 void WavWriter::writeInt32(int value) {
29         fputc((value >>  0) & 0xff, wav);
30         fputc((value >>  8) & 0xff, wav);
31         fputc((value >> 16) & 0xff, wav);
32         fputc((value >> 24) & 0xff, wav);
33 }
34
35 void WavWriter::writeInt16(int value) {
36         fputc((value >> 0) & 0xff, wav);
37         fputc((value >> 8) & 0xff, wav);
38 }
39
40 void WavWriter::writeHeader(int length) {
41         writeString("RIFF");
42         writeInt32(4 + 8 + 16 + 8 + length);
43         writeString("WAVE");
44
45         writeString("fmt ");
46         writeInt32(16);
47
48         int bytesPerFrame = bitsPerSample/8*channels;
49         int bytesPerSec = bytesPerFrame*sampleRate;
50         writeInt16(1);             // Format
51         writeInt16(channels);      // Channels
52         writeInt32(sampleRate);    // Samplerate
53         writeInt32(bytesPerSec);   // Bytes per sec
54         writeInt16(bytesPerFrame); // Bytes per frame
55         writeInt16(bitsPerSample); // Bits per sample
56
57         writeString("data");
58         writeInt32(length);
59 }
60
61 WavWriter::WavWriter(const char *filename, int sampleRate, int bitsPerSample, int channels) {
62         wav = fopen(filename, "wb");
63         if (wav == NULL)
64                 return;
65         dataLength = 0;
66         this->sampleRate = sampleRate;
67         this->bitsPerSample = bitsPerSample;
68         this->channels = channels;
69
70         writeHeader(dataLength);
71 }
72
73 WavWriter::~WavWriter() {
74         if (wav == NULL)
75                 return;
76         fseek(wav, 0, SEEK_SET);
77         writeHeader(dataLength);
78         fclose(wav);
79 }
80
81 void WavWriter::writeData(const unsigned char* data, int length) {
82         if (wav == NULL)
83                 return;
84         fwrite(data, length, 1, wav);
85         dataLength += length;
86 }
87