~mhall119/ubuntu-app-reviews/qtranscribe

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
344
345
346
347
348
349
350
351
352
353
354
355
356
/*
 *  Copyright © 2012 Matt Pharoah (mr.exuberant@gmail.com)
 *
 *  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 3 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, see <http://www.gnu.org/licenses/>.
 *
 */

#ifndef DICTATION_H_
#define DICTATION_H_

#include <sox.h>
#include <cstring>
#include <thread>
#include <mutex>
#include <stdexcept>

extern "C" {
#include <pulse/stream.h>
#include <pulse/sample.h>
#include <pulse/def.h>
#include <pulse/mainloop.h>
}

#include "AudioFileReader.hh"

using namespace std;

enum __REWIND_FASTFORWARD_OR_NEITHER {
	REWIND,
	NORMAL,
	FAST_FORWARD
};

static __REWIND_FASTFORWARD_OR_NEITHER mode;

static unsigned short REWIND_SPEED = 4; //x4 speed
static unsigned short FAST_FORWARD_SPEED = 8; //x8 speed
static bool SFX = true; //sound effects for fast forward and rewind?

static int dontcare;

class Dictation {
  private:
	unsigned int SAMPLE_RATE;
	unsigned short CHANNELS;
	unsigned int SIZE;

	unsigned int BUFFER_SIZE;
	unsigned int BUFFER_FRAMES;

	thread *loopThread;
	pa_stream *audioStream;
	sox_format_t *audioFile;
	unsigned int position;
	float speed;
	AudioFileReader *reader;
	SlowBuffer *stretcher;
	bool paused;
	char *fileName;

	pa_mainloop *PALoop;
	pa_context *context;

	float *SFX_REWIND; //rewind sound effect
	float *SFX_FFORWARD; //fast forward sound effect

	mutex positionLock;

	float *nil;

	static void fetchAudioData(pa_stream *stream, int success, void *me) {
		((Dictation *) me)->fetchAD();
	}

	inline void fetchAD() {
		positionLock.lock();
		if (position > SIZE)  {
			position = SIZE;
			pause();
		}

		if (mode == REWIND) {
			if (SFX) {
				pa_stream_write(audioStream, (void *) SFX_REWIND, BUFFER_SIZE, NULL, 0, PA_SEEK_RELATIVE);
			} else {
				pa_stream_write(audioStream, (void *) nil, BUFFER_SIZE, NULL, 0, PA_SEEK_RELATIVE);
			}
			if (position < BUFFER_FRAMES * REWIND_SPEED) {
				position = 0;
			} else {
				position -= BUFFER_FRAMES * REWIND_SPEED;
			}
		} else if (mode == FAST_FORWARD) {
			if (SFX) {
				pa_stream_write(audioStream, (void *) SFX_FFORWARD, BUFFER_SIZE, NULL, 0, PA_SEEK_RELATIVE);
			} else {
				pa_stream_write(audioStream, (void *) nil, BUFFER_SIZE, NULL, 0, PA_SEEK_RELATIVE);
			}
			position += BUFFER_FRAMES * FAST_FORWARD_SPEED;
		} else if (paused) {
			//write zeroes (silence)
			pa_stream_write(audioStream, (void *) nil, BUFFER_SIZE, NULL, 0, PA_SEEK_RELATIVE);
		} else if (speed == 1.0) {
			pa_stream_write(audioStream, (*reader)[position], BUFFER_SIZE, NULL, 0, PA_SEEK_RELATIVE);
			position += BUFFER_FRAMES;
		} else {
			float temp[BUFFER_FRAMES];
			position += stretcher->fetchInto(position, temp);
			pa_stream_write(audioStream, (void *) temp, BUFFER_SIZE, NULL, 0, PA_SEEK_RELATIVE);
		}
		positionLock.unlock();
	}

	//generate sawtooth sound effects for rewinding and fast forwarding
	inline void generateRewindEffect() {
		SFX_REWIND = new float[BUFFER_FRAMES];
		for (unsigned int i = 0; i < BUFFER_FRAMES; i += CHANNELS) {
			for (unsigned short j = 0; j < CHANNELS; j++) {
				SFX_REWIND[i+j] = 0.25f * (i % 100 / 100.f - 0.5);
			}
		}
	}

	inline void generateFastForwardEffect() {
		SFX_FFORWARD = new float[BUFFER_FRAMES];
		for (unsigned int i = 0; i < BUFFER_FRAMES; i += CHANNELS) {
			for (unsigned short j = 0; j < CHANNELS; j++) {
				SFX_FFORWARD[i+j] = 0.25f * (i % 80 / 80.f - 0.5);
			}
		}
	}

	/*
	 * well, I made a function for generating the sound effects,so I
	 * should make one for freeing them for the purpose of symmetry
	 */
	inline void freeSFX() {
		delete[] SFX_REWIND;
		delete[] SFX_FFORWARD;
	}

  public:
	static void setRewindSpeed(unsigned short mult) {
		REWIND_SPEED = mult;
	}

	static void setFastForwardSpeed(unsigned short mult) {
		FAST_FORWARD_SPEED = mult;
	}

	static unsigned int getRewindSpeed() {
		return REWIND_SPEED;
	}

	static unsigned int getFastForwardSpeed() {
		return FAST_FORWARD_SPEED;
	}

	static void setEffectsEnabled(bool yes) {
		SFX = yes;
	}

	Dictation(const string &file, volatile bool *errorCheck) {
		position = 0;
		speed = 1.0;
		mode = NORMAL;

		fileName = new char[file.length() + 1];
		strcpy(fileName, file.c_str());

		//load audio file
		audioFile = sox_open_read(fileName, NULL, NULL, NULL);

		if (audioFile == NULL || audioFile->encoding.encoding == SOX_ENCODING_UNKNOWN) {
			throw invalid_argument("Could not open audio file. Either the file is not an audio file or SoX does not support its format.");
		} else if (!audioFile->seekable) {
			throw invalid_argument("Audio file is not seekable. Aborting.");
		}

		//load file information
		SAMPLE_RATE = (unsigned int) audioFile->signal.rate;
		CHANNELS = audioFile->signal.channels;
		SIZE = audioFile->signal.length;

		//set buffer settings
		BUFFER_FRAMES = 1024 * CHANNELS;
		BUFFER_SIZE = BUFFER_FRAMES * sizeof(float);

		//initialize the zero'd memory used for when the stream is paused
		nil = new float[BUFFER_FRAMES];
		memset((void *) nil, 0, BUFFER_SIZE);
		paused = true;

		//generate sound effects for rewinding and fast forwarding
		generateRewindEffect();
		generateFastForwardEffect();

		//initialize audio file reader
		reader = new AudioFileReader(audioFile, fileName, errorCheck, CHANNELS, SIZE, BUFFER_FRAMES, SAMPLE_RATE * CHANNELS, (SAMPLE_RATE * CHANNELS * 5) + BUFFER_FRAMES);
		stretcher = new SlowBuffer(reader, SAMPLE_RATE, CHANNELS);

		/*
		 * connect to Pulseaduio server and set up buffer
		 */

		//set buffer settings
		pa_buffer_attr bufferInfo;
		bufferInfo.maxlength = BUFFER_SIZE * 2;
		bufferInfo.tlength = BUFFER_SIZE * 2;
		bufferInfo.minreq = BUFFER_SIZE;
		bufferInfo.prebuf = BUFFER_SIZE;

		//set sample settings
		pa_sample_spec sampleFormat;
		sampleFormat.format = PA_SAMPLE_FLOAT32LE;
		sampleFormat.rate = SAMPLE_RATE;
		sampleFormat.channels = CHANNELS;

		//create default pulseAudio main loop
		PALoop = pa_mainloop_new();

		//initialize pulseAudio context and stream
		context = pa_context_new(pa_mainloop_get_api(PALoop), "QTranscribe Context");
		if (context == NULL) throw runtime_error("Error connecting to PulseAudio server:\nCould not create context.\n");
		pa_context_connect(context, NULL, PA_CONTEXT_NOFLAGS, NULL);

		audioStream = pa_stream_new(context, "QTranscribe Audio Stream", &sampleFormat, NULL);
		if (audioStream == NULL) throw runtime_error("Error connecting to PulseAudio server:\nCould not create audio stream.\n");

		//wait for context to become ready
		while (pa_context_get_state(context) != PA_CONTEXT_READY) pa_mainloop_iterate(PALoop, true, &dontcare);

		//setup audio stream
		pa_stream_connect_playback(audioStream, NULL, &bufferInfo, PA_STREAM_NOFLAGS, NULL, NULL);
		pa_stream_set_write_callback(audioStream, (pa_stream_request_cb_t) fetchAudioData, (void *) this);
		while (pa_stream_get_state(audioStream) != PA_STREAM_READY) pa_mainloop_iterate(PALoop, true, &dontcare);

		//run the pulseAudio main loop in a new thread
		loopThread = new thread(pa_mainloop_run, PALoop, &dontcare);
	}

	void setSpeed(float rate) {
		if (speed != rate) {
			positionLock.lock();
			stretcher->setSpeed(rate);
			speed = rate;
			positionLock.unlock();
		}
	}

	inline void setPositionMilliseconds(unsigned int ms) {
		positionLock.lock();
		pa_stream_flush(audioStream, NULL, NULL);
		position = (unsigned int) (SAMPLE_RATE * CHANNELS * (((double) ms) / (double) 1000));
		positionLock.unlock();
	}

	inline void skipForward(int ms) {
		if (ms == 0) return;
		positionLock.lock();
		pa_stream_flush(audioStream, NULL, NULL);
		int diff = (int) (SAMPLE_RATE * CHANNELS * (((double) ms) / (double) 1000));
		if (ms < 0 && (unsigned int) (-1 * diff) > position) {
			position = 0;
		} else {
			position += diff;
		}
		positionLock.unlock();
	}

	//don't really need to use positionLock for setting play/pause or mode, so I won't

	inline void play() {
		paused = false;
	}

	inline void pause() {
		paused = true;
	}

	inline bool isPaused() {
		return paused;
	}

	inline bool isSlowed() {
		return (speed != 1.0);
	}

	inline void stopRewind() {
		if (mode == REWIND) mode = NORMAL;
	}

	inline void stopFastForward() {
		if (mode == FAST_FORWARD) mode = NORMAL;
	}

	inline void startRewind() {
		mode = REWIND;
	}

	inline void startFastForward() {
		mode = FAST_FORWARD;
	}

	inline bool isRewinding() {
		return (mode == REWIND);
	}

	inline bool isFastForwarding() {
		return (mode == FAST_FORWARD);
	}

	unsigned int getPositionMilliseconds() {
		positionLock.lock();
		unsigned int ret = (unsigned int) ((double) 1000 * ((double) position / (double) (SAMPLE_RATE * CHANNELS)));
		positionLock.unlock();
		return ret;
	}

	unsigned int getLengthMilliseconds() {
		return (unsigned int) ((double) 1000 * ((double) SIZE / (double) (SAMPLE_RATE * CHANNELS)));
	}

	~Dictation() {
		pa_stream_drain(audioStream, NULL, NULL);
		positionLock.lock();
		pa_mainloop_quit(PALoop, 0);
		pa_stream_disconnect(audioStream);
		pa_stream_unref(audioStream);
		pa_context_disconnect(context);
		pa_context_unref(context);
		pa_mainloop_free(PALoop);
		loopThread->join();
		delete loopThread;
		delete stretcher;
		delete reader;
		sox_close(audioFile);
		delete[] nil;
		delete[] fileName;
		freeSFX();
		positionLock.unlock();
	};
};

#endif /* DICTATION_H_ */