summaryrefslogtreecommitdiff
path: root/src/main.c
blob: d125122d57fd29f34e92c337ff773b577265afac (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
/*
Copyright (c) 2008 Lars-Dominik Braun

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <piano.h>
#include <curl/curl.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ao/ao.h>
#include <neaacdec.h>
#include <pthread.h>
#include <unistd.h>
#include <termios.h>
#include <poll.h>

struct aacPlayer {
	/* buffer */
	char *buffer;
	size_t bufferFilled;
	char lastBytes[4];
	/* got mdat atom */
	char dataMode;
	char foundEsdsAtom;
	char audioInitialized;
	/* aac */
	NeAACDecHandle aacHandle;
	unsigned long samplerate;
	unsigned char channels;
	/* audio out */
	ao_device *audioOutDevice;
	char *url;
	char finishedPlayback;
	char doQuit;
};

void dumpBuffer (char *buf, size_t len) {
	int i;
	for (i = 0; i < len; i++) {
		printf ("%02x ", buf[i] & 0xff);
	}
	printf ("\n");
}

/* FIXME: this is a huge block of _bad_ and buggy code */
int playCurlCb (void *ptr, size_t size, size_t nmemb, void *stream) {
	char *data = ptr;
	struct aacPlayer *player = stream;

	if (player->doQuit) {
		return -1;
	}

	if (player->dataMode == 1) {
		size_t bufferOffset = 0, aacBufferN;
		char *aacDecoded, *aacBuffer;
		NeAACDecFrameInfo frameInfo;

		aacBufferN = player->bufferFilled + nmemb;
		aacBuffer = calloc (aacBufferN, sizeof (char));
		memcpy (aacBuffer, player->buffer, player->bufferFilled);
		memcpy (aacBuffer + player->bufferFilled, data, nmemb * size);

		free (player->buffer);

		/* keep some bytes in buffer */
		while (bufferOffset < aacBufferN-500) {
			//printf ("play buffer at %i/%i: ", bufferOffset, aacBufferN);
			//dumpBuffer (aacBuffer+bufferOffset, 50);
			/* FIXME: well, i think we need this block length table */
			aacDecoded = NeAACDecDecode(player->aacHandle, &frameInfo,
					(unsigned char *) aacBuffer+bufferOffset,
					aacBufferN-bufferOffset);
			//printf ("bytesconsumed: %li\nerror: %i\nsamples: %lu\nsamplerate: %lu\n\n", frameInfo.bytesconsumed, frameInfo.error, frameInfo.samples, frameInfo.samplerate);
			if (frameInfo.error != 0) {
				printf ("error: %s\n\n", NeAACDecGetErrorMessage (frameInfo.error));
				break;
			}
			ao_play (player->audioOutDevice, aacDecoded,
					frameInfo.samples*frameInfo.channels);
			bufferOffset += frameInfo.bytesconsumed;
		}
		/* copy remaining bytes */
		player->buffer = calloc (aacBufferN - bufferOffset, sizeof (char));
		memcpy (player->buffer, aacBuffer+bufferOffset,
				aacBufferN - bufferOffset);
		player->bufferFilled = aacBufferN - bufferOffset;
		//printf ("player->buffer (%i) = ", aacBufferN - bufferOffset);
		//dumpBuffer (player->buffer, 50);
		free (aacBuffer);
	} else {
		player->buffer = calloc (nmemb + sizeof (player->lastBytes), size);
		/* we are going to find a 4-byte string, but curl sends fragments and
		 * if the identifier is cut into two pieces, we will get into big
		 * trouble... */
		memcpy (player->buffer, player->lastBytes, sizeof (player->lastBytes));
		memcpy (player->buffer+sizeof (player->lastBytes), data, size*nmemb);

		char *searchBegin = player->buffer;

		if (!player->foundEsdsAtom) {
			while (searchBegin < player->buffer + nmemb) {
				if (memcmp (searchBegin, "esds", 4) == 0) {
					player->foundEsdsAtom = 1;
					break;
				}
				searchBegin++;
			}
		}
		if (player->foundEsdsAtom && !player->audioInitialized) {
			/* FIXME: is this the correct way? */
			while (searchBegin < player->buffer + nmemb) {
				if (memcmp (searchBegin, "\x05\x80\x80\x80", 4) == 0) {
					ao_sample_format format;
					int audioOutDriver;

					char err = NeAACDecInit2 (player->aacHandle,
							(unsigned char *) searchBegin+1+4, 5,
							&player->samplerate, &player->channels);
					if (err != 0) {
						printf ("whoops... %i\n", err);
						return 1;
					}
					//printf ("samplerate: %li\nchannels: %i\n\n",
					//		player->samplerate, player->channels);
					audioOutDriver = ao_default_driver_id();
					format.bits = 16;
					format.channels = player->channels;
					format.rate = player->samplerate;
					format.byte_format = AO_FMT_LITTLE;
					player->audioOutDevice = ao_open_live (audioOutDriver, &format, NULL);
					player->audioInitialized = 1;
					break;
				}
				searchBegin++;
			}
		}
		if (player->audioInitialized) {
			while (searchBegin < player->buffer + nmemb) {
				if (memcmp (searchBegin, "mdat", 4) == 0) {
					player->dataMode = 1;
					memmove (player->buffer, searchBegin+4, nmemb - (searchBegin-player->buffer));
					player->bufferFilled = nmemb - (searchBegin-player->buffer);
					//printf ("copied %i bytes: ", nmemb - (searchBegin-player->buffer));
					//dumpBuffer (player->buffer, 50);
					break;
				}
				searchBegin++;
			}
		}
		if (!player->dataMode) {
			memcpy (player->lastBytes, data + (size * nmemb - sizeof (player->lastBytes)),
					sizeof (player->lastBytes));
			//printf ("last bytes: ");
			//dumpBuffer (player->lastBytes, 4);
			free (player->buffer);
		}
	}

	return size*nmemb;
}

void *threadPlayUrl (void *data) {
	struct aacPlayer *player = data;
	NeAACDecConfigurationPtr conf;
	CURL *audioFd;

	audioFd = curl_easy_init ();
	player->aacHandle = NeAACDecOpen();

	conf = NeAACDecGetCurrentConfiguration(player->aacHandle);
	conf->outputFormat = FAAD_FMT_16BIT;
    conf->downMatrix = 1;
	NeAACDecSetConfiguration(player->aacHandle, conf);

	curl_easy_setopt (audioFd, CURLOPT_URL, player->url);
	curl_easy_setopt (audioFd, CURLOPT_WRITEFUNCTION, playCurlCb);
	curl_easy_setopt (audioFd, CURLOPT_WRITEDATA, player);
	/* at the moment we don't need publicity */
	curl_easy_setopt (audioFd, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9pre) Gecko/2008051115 Firefox/3.0pre");
	curl_easy_perform (audioFd);

	free (player->buffer);
	NeAACDecClose(player->aacHandle);
	ao_close(player->audioOutDevice);
	curl_easy_cleanup (audioFd);

	player->finishedPlayback = 1;

	return NULL;
}

PianoStation_t *selectStation (PianoHandle_t *ph) {
	PianoStation_t *curStation;
	size_t i;

	printf ("which station do you want to listen to?\n");
	i = 0;
	curStation = ph->stations;
	while (curStation != NULL) {
		printf ("%2i) %s\n", i, curStation->name);
		curStation = curStation->next;
		i++;
	}
	scanf ("%i", &i);
	curStation = ph->stations;
	while (curStation != NULL && i > 0) {
		curStation = curStation->next;
		i--;
	}
	return curStation;
}

int main (int argc, char **argv) {
	PianoHandle_t ph;
	struct aacPlayer player;
	char doQuit = 0;
	PianoSong_t *curSong = NULL;
	PianoStation_t *curStation;
	struct termios termopts;

	/* init some things */
	curl_global_init (CURL_GLOBAL_SSL);
	ao_initialize();
	PianoInit (&ph);

	/* no buffering for stdin */
	tcgetattr (fileno (stdin), &termopts);
	termopts.c_lflag &= ~ICANON;
	tcsetattr(fileno (stdin), TCSANOW, &termopts);
	setvbuf (stdin, NULL, _IONBF, 1);

	PianoConnect (&ph, argv[1], argv[2]);
	PianoGetStations (&ph);
	printf ("webAuthToken: %s\nauthToken: %s\nlistenerId: %s\n", ph.user.webAuthToken, ph.user.authToken, ph.user.listenerId);

	/* select station */
	curStation = selectStation (&ph);
	printf ("playing station %s\n", curStation->name);
	PianoGetPlaylist (&ph, curStation->id);

	curSong = ph.playlist;
	/* play first track */
	while (!doQuit) {
		PianoSong_t *lastSong = NULL;
		pthread_t playerThread;
		printf ("%s by %s\n", curSong->title, curSong->artist);
		memset (&player, 0, sizeof (player));
		player.url = strdup (curSong->audioUrl);

		/* start player */
		pthread_create (&playerThread, NULL, threadPlayUrl, &player);

		/* in the meantime: wait for user actions */
		while (!player.finishedPlayback) {
			struct pollfd polls = {fileno (stdin), POLLIN, POLLIN};
			char buf;

			if (poll (&polls, 1, 1000) > 0) {
				read (fileno (stdin), &buf, sizeof (buf));
				switch (buf) {
					case '?':
						printf ("n\tnext track\nq\tquit\ns\tchange station\n");
						break;

					case 'b':
						player.doQuit = 1;
						PianoRateTrack (&ph, curStation, curSong,
								PIANO_RATE_BAN);
						PianoDestroyPlaylist (&ph);
						break;

					case 'l':
						PianoRateTrack (&ph, curStation, curSong,
								PIANO_RATE_LOVE);
						break;

					case 'n':
						player.doQuit = 1;
						break;

					case 'q':
						doQuit = 1;
						player.doQuit = 1;
						break;

					case 's':
						/* FIXME: does not work, segfault... */
						player.doQuit = 1;
						PianoDestroyPlaylist (&ph);
						curStation = selectStation (&ph);
						printf ("changed station to %s\n", curStation->name);
						break;

				}
			}
		}
		pthread_join (playerThread, NULL);

		free (player.url);
		/* what's next? */
		lastSong = curSong;
		curSong = lastSong->next;
		if (curSong == NULL && !doQuit) {
			printf ("receiving new playlist\n");
			PianoGetPlaylist (&ph, curStation->id);
			curSong = lastSong->next;
			if (curSong == NULL) {
				/* no tracks left */
				doQuit = 1;
			}
		}
	}

	/* destroy everything (including the world...) */
	PianoDestroy (&ph);
	curl_global_cleanup ();
	ao_shutdown();

	return 0;
}