Bugfix: memory and thread-deleting problems
[monky] / src / mpd.c
1 /* -*- mode: c; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: t -*-
2  * vim: ts=4 sw=4 noet ai cindent syntax=c
3  *
4  * Conky, a system monitor, based on torsmo
5  *
6  * Any original torsmo code is licensed under the BSD license
7  *
8  * All code written since the fork of torsmo is licensed under the GPL
9  *
10  * Please see COPYING for details
11  *
12  * Copyright (c) 2005-2010 Brenden Matthews, Philip Kovacs, et. al.
13  *      (see AUTHORS)
14  * All rights reserved.
15  *
16  * This program is free software: you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License as published by
18  * the Free Software Foundation, either version 3 of the License, or
19  * (at your option) any later version.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  * GNU General Public License for more details.
25  * You should have received a copy of the GNU General Public License
26  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
27  *
28  */
29
30 #include "conky.h"
31 #include "logging.h"
32 #include "timed_thread.h"
33 #include "timeinfo.h"
34 #include "libmpdclient.h"
35 #include "mpd.h"
36
37 /* server connection data */
38 static char mpd_host[128];
39 static char mpd_password[128];
40 static int mpd_port;
41
42 /* this is >0 if the current password was set from MPD_HOST */
43 static int mpd_environment_password = 0;
44
45 /* global mpd information */
46 static struct mpd_s mpd_info;
47
48 /* number of users of the above struct */
49 static int refcount = 0;
50
51 void mpd_set_host(const char *host)
52 {
53         snprintf(mpd_host, 128, "%s", host);
54
55         if (mpd_environment_password) {
56                 /* for security, dont use environment password when user specifies host in config */
57                 mpd_clear_password();
58         }
59 }
60 void mpd_set_password(const char *password, int from_environment)
61 {
62         snprintf(mpd_password, 128, "%s", password);
63         mpd_environment_password = from_environment;
64 }
65 void mpd_clear_password(void)
66 {
67         *mpd_password = '\0';
68         mpd_environment_password = 0;
69 }
70 int mpd_set_port(const char *port)
71 {
72         int val;
73
74         val = strtol(port, 0, 0);
75         if (val < 1 || val > 0xffff)
76                 return 1;
77         mpd_port = val;
78         return 0;
79 }
80
81 void init_mpd(void)
82 {
83         if (!(refcount++))      /* first client */
84                 memset(&mpd_info, 0, sizeof(mpd_info));
85 }
86
87 struct mpd_s *mpd_get_info(void)
88 {
89         return &mpd_info;
90 }
91
92 static void clear_mpd(void)
93 {
94 #define xfree(x) if (x) free(x)
95         xfree(mpd_info.title);
96         xfree(mpd_info.artist);
97         xfree(mpd_info.album);
98         /* do not free() the const char *status! */
99         /* do not free() the const char *random! */
100         /* do not free() the const char *repeat! */
101         xfree(mpd_info.track);
102         xfree(mpd_info.name);
103         xfree(mpd_info.file);
104 #undef xfree
105         memset(&mpd_info, 0, sizeof(struct mpd_s));
106 }
107
108 void free_mpd(void)
109 {
110         if (!(--refcount))      /* last client */
111                 clear_mpd();
112 }
113
114 static void *update_mpd_thread(void *) __attribute__((noreturn));
115
116 int update_mpd(void)
117 {
118         int interval;
119         static timed_thread *thread = NULL;
120
121         if (thread)
122                 return 0;
123
124         interval = info.music_player_interval * 1000000;
125         thread = timed_thread_create(&update_mpd_thread, &thread, interval);
126         if (!thread) {
127                 NORM_ERR("Failed to create MPD timed thread");
128                 return 0;
129         }
130         timed_thread_register(thread, &thread);
131         if (timed_thread_run(thread))
132                 NORM_ERR("Failed to run MPD timed thread");
133         return 0;
134 }
135
136 /* stringMAXdup dups at most text_buffer_size bytes */
137 #define strmdup(x) strndup(x, text_buffer_size - 1)
138
139 static void *update_mpd_thread(void *arg)
140 {
141         static mpd_Connection *conn = NULL;
142         mpd_Status *status;
143         mpd_InfoEntity *entity;
144         timed_thread *me = *(timed_thread **)arg;
145         const char *emptystr = "";
146
147         while (1) {
148                 if (!conn)
149                         conn = mpd_newConnection(mpd_host, mpd_port, 10);
150
151                 if (*mpd_password) {
152                         mpd_sendPasswordCommand(conn, mpd_password);
153                         mpd_finishCommand(conn);
154                 }
155
156                 timed_thread_lock(me);
157
158                 if (conn->error || conn == NULL) {
159                         NORM_ERR("MPD error: %s\n", conn->errorStr);
160                         mpd_closeConnection(conn);
161                         conn = 0;
162                         clear_mpd();
163
164                         mpd_info.status = "MPD not responding";
165                         timed_thread_unlock(me);
166                         if (timed_thread_test(me, 0)) {
167                                 timed_thread_exit(me);
168                         }
169                         continue;
170                 }
171
172                 mpd_sendStatusCommand(conn);
173                 if ((status = mpd_getStatus(conn)) == NULL) {
174                         NORM_ERR("MPD error: %s\n", conn->errorStr);
175                         mpd_closeConnection(conn);
176                         conn = 0;
177                         clear_mpd();
178
179                         mpd_info.status = "MPD not responding";
180                         timed_thread_unlock(me);
181                         if (timed_thread_test(me, 0)) {
182                                 timed_thread_exit(me);
183                         }
184                         continue;
185                 }
186                 mpd_finishCommand(conn);
187                 if (conn->error) {
188                         // fprintf(stderr, "%s\n", conn->errorStr);
189                         mpd_closeConnection(conn);
190                         conn = 0;
191                         timed_thread_unlock(me);
192                         if (timed_thread_test(me, 0)) {
193                                 timed_thread_exit(me);
194                         }
195                         continue;
196                 }
197
198                 mpd_info.vol = status->volume;
199                 if (status->random == 0) {
200                         mpd_info.random = "Off";
201                 } else if (status->random == 1) {
202                         mpd_info.random = "On";
203                 } else {
204                         mpd_info.random = "";
205                 }
206                 if (status->repeat == 0) {
207                         mpd_info.repeat = "Off";
208                 } else if (status->repeat == 1) {
209                         mpd_info.repeat = "On";
210                 } else {
211                         mpd_info.repeat = "";
212                 }
213                 /* if (status->error) {
214                         printf("error: %s\n", status->error);
215                 } */
216
217                 switch (status->state) {
218                         case MPD_STATUS_STATE_PLAY:
219                                 mpd_info.status = "Playing";
220                                 break;
221                         case MPD_STATUS_STATE_STOP:
222                                 mpd_info.status = "Stopped";
223                                 break;
224                         case MPD_STATUS_STATE_PAUSE:
225                                 mpd_info.status = "Paused";
226                                 break;
227                         default:
228                                 mpd_info.status = "";
229                                 clear_mpd();
230                                 break;
231                 }
232
233                 if (status->state == MPD_STATUS_STATE_PLAY ||
234                     status->state == MPD_STATUS_STATE_PAUSE) {
235                         mpd_info.is_playing = 1;
236                         mpd_info.bitrate = status->bitRate;
237                         mpd_info.progress = (float) status->elapsedTime /
238                                 status->totalTime;
239                         mpd_info.elapsed = status->elapsedTime;
240                         mpd_info.length = status->totalTime;
241                 } else {
242                         mpd_info.progress = 0;
243                         mpd_info.is_playing = 0;
244                         mpd_info.elapsed = 0;
245                 }
246
247                 if (conn->error) {
248                         // fprintf(stderr, "%s\n", conn->errorStr);
249                         mpd_closeConnection(conn);
250                         conn = 0;
251                         timed_thread_unlock(me);
252                         if (timed_thread_test(me, 0)) {
253                                 timed_thread_exit(me);
254                         }
255                         continue;
256                 }
257
258                 mpd_sendCurrentSongCommand(conn);
259                 while ((entity = mpd_getNextInfoEntity(conn))) {
260                         mpd_Song *song = entity->info.song;
261
262                         if (entity->type != MPD_INFO_ENTITY_TYPE_SONG) {
263                                 mpd_freeInfoEntity(entity);
264                                 continue;
265                         }
266 #define SONGSET(x) {                            \
267         free(mpd_info.x);                       \
268         if(song->x)                             \
269                 mpd_info.x = strmdup(song->x);  \
270         else                                    \
271                 mpd_info.x = strmdup(emptystr); \
272 }
273                         SONGSET(artist);
274                         SONGSET(album);
275                         SONGSET(title);
276                         SONGSET(track);
277                         SONGSET(name);
278                         SONGSET(file);
279 #undef SONGSET
280                         if (entity != NULL) {
281                                 mpd_freeInfoEntity(entity);
282                                 entity = NULL;
283                         }
284                 }
285                 mpd_finishCommand(conn);
286                 if (conn->error) {
287                         // fprintf(stderr, "%s\n", conn->errorStr);
288                         mpd_closeConnection(conn);
289                         conn = 0;
290                         timed_thread_unlock(me);
291                         if (timed_thread_test(me, 0)) {
292                                 timed_thread_exit(me);
293                         }
294                         continue;
295                 }
296
297                 timed_thread_unlock(me);
298                 if (conn->error) {
299                         // fprintf(stderr, "%s\n", conn->errorStr);
300                         mpd_closeConnection(conn);
301                         conn = 0;
302                         if (timed_thread_test(me, 0)) {
303                                 timed_thread_exit(me);
304                         }
305                         continue;
306                 }
307
308                 mpd_freeStatus(status);
309                 /* if (conn) {
310                         mpd_closeConnection(conn);
311                         conn = 0;
312                 } */
313                 if (timed_thread_test(me, 0)) {
314                         timed_thread_exit(me);
315                 }
316                 continue;
317         }
318         /* never reached */
319 }
320
321 static inline void format_media_player_time(char *buf, const int size,
322                 int seconds)
323 {
324         int days, hours, minutes;
325
326         if (times_in_seconds()) {
327                 snprintf(buf, size, "%d", seconds);
328                 return;
329         }
330
331         days = seconds / (24 * 60 * 60);
332         seconds %= (24 * 60 * 60);
333         hours = seconds / (60 * 60);
334         seconds %= (60 * 60);
335         minutes = seconds / 60;
336         seconds %= 60;
337
338         if (days > 0) {
339                 snprintf(buf, size, "%i days %i:%02i:%02i", days,
340                                 hours, minutes, seconds);
341         } else if (hours > 0) {
342                 snprintf(buf, size, "%i:%02i:%02i", hours, minutes,
343                                 seconds);
344         } else {
345                 snprintf(buf, size, "%i:%02i", minutes, seconds);
346         }
347 }
348
349 void print_mpd_elapsed(struct text_object *obj, char *p, int p_max_size)
350 {
351         (void)obj;
352         format_media_player_time(p, p_max_size, mpd_get_info()->elapsed);
353 }
354
355 void print_mpd_length(struct text_object *obj, char *p, int p_max_size)
356 {
357         (void)obj;
358         format_media_player_time(p, p_max_size, mpd_get_info()->length);
359 }
360
361 void print_mpd_percent(struct text_object *obj, char *p, int p_max_size)
362 {
363         (void)obj;
364         percent_print(p, p_max_size, (int)(mpd_get_info()->progress * 100));
365 }
366
367 void print_mpd_bar(struct text_object *obj, char *p, int p_max_size)
368 {
369         new_bar(obj, p, p_max_size, (int) (mpd_get_info()->progress * 255.0f));
370 }
371
372 void print_mpd_smart(struct text_object *obj, char *p, int p_max_size)
373 {
374         struct mpd_s *mpd = mpd_get_info();
375         int len = obj->data.i;
376         if (len == 0 || len > p_max_size)
377                 len = p_max_size;
378
379         memset(p, 0, p_max_size);
380         if (mpd->artist && *mpd->artist &&
381                         mpd->title && *mpd->title) {
382                 snprintf(p, len, "%s - %s", mpd->artist,
383                                 mpd->title);
384         } else if (mpd->title && *mpd->title) {
385                 snprintf(p, len, "%s", mpd->title);
386         } else if (mpd->artist && *mpd->artist) {
387                 snprintf(p, len, "%s", mpd->artist);
388         } else if (mpd->file && *mpd->file) {
389                 snprintf(p, len, "%s", mpd->file);
390         } else {
391                 *p = 0;
392         }
393 }
394
395 #define MPD_PRINT_GENERATOR(name, fmt) \
396 void print_mpd_##name(struct text_object *obj, char *p, int p_max_size) \
397 { \
398         if (obj->data.i && obj->data.i < p_max_size) \
399                 p_max_size = obj->data.i; \
400         snprintf(p, p_max_size, fmt, mpd_get_info()->name); \
401 }
402
403 MPD_PRINT_GENERATOR(title, "%s")
404 MPD_PRINT_GENERATOR(artist, "%s")
405 MPD_PRINT_GENERATOR(album, "%s")
406 MPD_PRINT_GENERATOR(random, "%s")
407 MPD_PRINT_GENERATOR(repeat, "%s")
408 MPD_PRINT_GENERATOR(track, "%s")
409 MPD_PRINT_GENERATOR(name, "%s")
410 MPD_PRINT_GENERATOR(file, "%s")
411 MPD_PRINT_GENERATOR(vol, "%d")
412 MPD_PRINT_GENERATOR(bitrate, "%d")
413 MPD_PRINT_GENERATOR(status, "%s")
414
415 #undef MPD_PRINT_GENERATOR