summaryrefslogtreecommitdiffstats
path: root/khotkeys/shared/sound.cpp
blob: 5b99a1cbaf38ff1bae7144c555471ad69705b8ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/***************************************************************************
 *   Copyright (C) 2005 by Olivier Goffart   *
 *   ogoffart@kde.org   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.             *
 ***************************************************************************/

#include "sound.h"
#include <tqfile.h>
#include <tqdatastream.h>
#include <kdebug.h>




Sound::Sound()
{
}


Sound::~Sound()
{
}


#define READ_FROM_STREAM(FORMAT,NAME)  FORMAT NAME; stream >> NAME;
#define MAGIC(CH) { \
   stream >> magic;  \
   if( magic != ( (CH)[0] | (CH)[1]<<8 | (CH)[2]<< 16 | (CH)[3] << 24 ) ) \
   {  \
      kdWarning() << k_funcinfo << "bad format " << magic << " != " << CH "\n";\
      return;\
   } }   

#define ABS(X)  ( (X>0) ? X : -X )

void Sound::load(const TQString& filename)
{
	kdDebug() << k_funcinfo << filename << endl;
	data=TQMemArray<TQ_INT32>();
	TQFile file(filename);
	if(!file.open(IO_ReadOnly))
	{
		kdWarning() << k_funcinfo <<"unable to open file" << endl;
		return;
	}
	TQDataStream stream(&file);
	stream.setByteOrder( TQDataStream::LittleEndian );
	TQ_INT32 magic;
	
	MAGIC("RIFF");
	READ_FROM_STREAM(TQ_UINT32,ChunkSize);
	MAGIC("WAVE");
	MAGIC("fmt ");
	READ_FROM_STREAM(TQ_UINT32,ChunkSize2);
	READ_FROM_STREAM(TQ_INT16,AudioFormat);
	READ_FROM_STREAM(TQ_UINT16,NumberOfChannels);
	READ_FROM_STREAM(TQ_UINT32,SampleRate);
	_fs=SampleRate;
	READ_FROM_STREAM(TQ_UINT32,ByteRate);
	READ_FROM_STREAM(TQ_UINT16,BlockAlign);
	READ_FROM_STREAM(TQ_UINT16,BitsPerSample);
	MAGIC("data");
	READ_FROM_STREAM(TQByteArray,SoundData);
	NumberOfChannels=1; //Wav i play are broken

	file.close();

	uint BytePS=BitsPerSample/8;
	uint NumberOfSamples = (SoundData.size())/(NumberOfChannels*BytePS);
	

	data.resize(NumberOfSamples);

//	kdDebug() << k_funcinfo << NumberOfSamples << " samples" << endl;

	max=0;
	for(unsigned long int f=0;f<NumberOfSamples;f++)
	{
		TQ_INT32 nb=0;
		for(uint k=0;k<BytePS;k++)
		{
			nb |= (SoundData.tqat(f*BytePS+k)&0x000000FF) << (k*8);
		}
		if(nb & (1 << (BytePS*8 -1)) )
			nb = nb-(1<<BytePS*8);
		data[f]=nb;
		if(ABS(nb)>max)
		{
			max=ABS(nb);
		}
	}

/*	static int q=0;
	TQString name="test" + TQString::number(q++) + ".wav";
	save(name);*/

}

#define SMAGIC(CH) { stream << ( TQ_INT32) ( (CH)[0] | (CH)[1]<<8 | (CH)[2]<< 16 | (CH)[3] << 24 ) ; }

void Sound::save(const TQString& filename) const
{
	kdDebug( 1217 ) << k_funcinfo << filename << " - " << data.size() <<  endl;
	TQFile file(filename);
	if(!file.open(IO_WriteOnly))
	{
		kdWarning() << k_funcinfo <<"unable to open file" << endl;
		return;
	}
	TQDataStream stream(&file);
	stream.setByteOrder( TQDataStream::LittleEndian );


	TQByteArray SoundData(data.size()*2);
	
	for(unsigned long int f=0;f<data.size();f++)
	{
		TQ_UINT16 val= (signed short int) ( (data.tqat(f) * ((double)(1<<13)/(signed)max)  ) );
		SoundData.tqat( 2*f )=   val & 0x00FF;
		SoundData.tqat(2*f+1)=  (val & 0xFF00) >> 8;
		
//		kdDebug( 1217 ) << k_funcinfo << data.tqat(f) << " / " << max << " = " << val << "  |  " <<   SoundData[ 2*f ] << " "<< SoundData[ 2*f+1 ] <<  endl;
	}

	TQ_UINT16 NumberOfChannels=2;
	TQ_UINT32 SampleRate=_fs;

	SMAGIC("RIFF");
	//READ_FROM_STREAM(TQ_UINT32,ChunkSize);
	stream <<  (TQ_UINT32)(36+ SoundData.size());
	SMAGIC("WAVE");
	SMAGIC("fmt ");
	//READ_FROM_STREAM(TQ_UINT32,ChunkSize2);
	stream <<  (TQ_UINT32)(16);
	//READ_FROM_STREAM(TQ_INT16,AudioFormat);
	stream <<  (TQ_INT16)(1);
	//READ_FROM_STREAM(TQ_UINT16,NumberOfChannels);
	stream <<  (TQ_UINT16)(NumberOfChannels);
	//READ_FROM_STREAM(TQ_UINT32,SampleRate);
	stream <<  (TQ_UINT32)(SampleRate);
	//READ_FROM_STREAM(TQ_UINT32,ByteRate);
	stream <<  (TQ_UINT32)(NumberOfChannels*SampleRate*16/8);
	//READ_FROM_STREAM(TQ_UINT16,BlockAlign);
	stream <<  (TQ_UINT16)(16/8 *NumberOfChannels);
	//READ_FROM_STREAM(TQ_UINT16,BitsPerSample);
	stream <<  (TQ_UINT16)(16);
	SMAGIC("data");
	//READ_FROM_STREAM(TQByteArray,SoundData);
	stream <<  SoundData;

	file.close();
	
}




#if 0
void Sound::load(const TQString& filename)
{
	cout << "saout \n";
	data=TQMemArray<long unsigned int>();
	static const int BUFFER_LEN = 4096;

	//code from libtunepimp
	//(wav_trm.cpp)

	FILE          *source;
	unsigned char  buffer[100], *copyBuffer;
	unsigned int   bytes;
	unsigned long  ulRIFF;
	unsigned long  ulLength;
	unsigned long  ulWAVE;
	unsigned long  ulType;
	unsigned long  ulCount;
	unsigned long  ulLimit;
	bool           haveWaveHeader = false;
	unsigned long  waveSize = 0;
	WAVEFORMAT     waveFormat;
	int            toRead;
	mb_int64_t     fileLen = 0;

	source = fopen(filename.ascii(), "rb");
	if (source == NULL)
	{
//		errorString = string("File not found");
//		fclose(source);
		cout << "File not found \n";
		return;
	}

	fseek(source, 0, SEEK_END);
	fileLen = ftell(source);
	fseek(source, 0, SEEK_SET);

	if (fread(buffer, 1, 12, source) != 12)
	{
//		errorString = string("File is too short");
		cout << "File is to short \n";
		fclose(source);
		return ;
	}

	ulRIFF = (unsigned long)(((unsigned long *)buffer)[0]);
	ulLength = (unsigned long)(((unsigned long *)buffer)[1]);
	ulWAVE = (unsigned long)(((unsigned long *)buffer)[2]);

	if(ulRIFF != MAKEFOURCC('R', 'I', 'F', 'F') ||
		  ulWAVE != MAKEFOURCC('W', 'A', 'V', 'E'))
	{
//		errorString = strdup("File is not in WAVE format");
		cout << "File is not WAVE \n";
		fclose(source);
		return ;
	}

    // Run through the bytes looking for the tags
	ulCount = 0;
	ulLimit = ulLength - 4;
	while (ulCount < ulLimit && waveSize == 0)
	{
		if (fread(buffer, 1, 8, source) != 8)
		{
//			errorString = strdup("File is too short");
			cout << "File is to short \n";
			fclose(source);
			return;
		}

		ulType   = (unsigned long)(((unsigned long *)buffer)[0]);
		ulLength = (unsigned long)(((unsigned long *)buffer)[1]);
		switch (ulType)
		{
          // format
			case MAKEFOURCC('f', 'm', 't', ' '):
				if (ulLength < sizeof(WAVEFORMAT))
				{
//					errorString = strdup("File is too short");
					cout << "File is to short \n";
					fclose(source);
					return ;
				}

				if (fread(&waveFormat, 1, ulLength, source) != ulLength)
				{
//					errorString = strdup("File is too short");
					cout << "File is to short \n";
					fclose(source);
					return ;
				}

				if (waveFormat.wFormatTag != WAVE_FORMAT_PCM)
				{
//					errorString = strdup("Unsupported WAV format");
					cout << "Unsupported WAVE \n";
					fclose(source);
					return ;
				}
				haveWaveHeader = true;

				ulCount += ulLength;
				break;

          // data
			case MAKEFOURCC('d', 'a', 't', 'a'):
				waveSize = ulLength;
				break;

			default:
				fseek(source, ulLength, SEEK_CUR);
				break;

		}
	}


	if (!haveWaveHeader)
	{
//		errorString = strdup("Could not find WAV header");
		cout << "Header nbot found \n";
		fclose(source);
		return ;
	}

	fileLen -= (mb_int64_t)ftell(source);
	fileLen /= waveFormat.nChannels;
	fileLen /= (waveFormat.nBlockAlign / waveFormat.nChannels);

	fileLen /= waveFormat.nSamplesPerSec;

	//on ne lit qu'un channel
	//waveSize=fileLen;
	data.resize(waveSize);
	unsigned long pos=0;

	cout << "Weeee "<< waveSize <<"\n";

	copyBuffer = (unsigned char*)malloc(BUFFER_LEN);
	if (copyBuffer == NULL)
	{
//		errorString = strdup("Cannot allocate buffer space.");
		return ;
	}

	for(;;)
	{
		toRead = min(waveSize, (unsigned long)BUFFER_LEN);
		if (toRead <= 0)
			break;

		bytes = fread(copyBuffer, 1, toRead, source);
		if (bytes <= 0)
			break;

		for(uint f=0;f<bytes;f+=4)
		{
			data[pos]=(((unsigned long*)copyBuffer)[f/4]);
			pos++;
		}

		waveSize -= toRead;
	}
	free(copyBuffer);
	fclose(source);

    return ;
}

#endif