Initial revision 6759
[qball-mpd.git] / src / audioOutputs / .svn / text-base / audioOutput_shout.c.svn-base
blob294d6a152479ebf30402df537b01de1971906a0c
1 /* the Music Player Daemon (MPD)
2  * Copyright (C) 2003-2007 by Warren Dukes (warren.dukes@gmail.com)
3  * This project's homepage is: http://www.musicpd.org
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
19 #include "../audioOutput.h"
21 #include <stdlib.h>
23 #ifdef HAVE_SHOUT
25 #include "../conf.h"
26 #include "../log.h"
27 #include "../pcm_utils.h"
28 #include "../timer.h"
30 #include <string.h>
31 #include <time.h>
33 #include <shout/shout.h>
34 #include <vorbis/vorbisenc.h>
36 #define CONN_ATTEMPT_INTERVAL 60
37 #define DEFAULT_CONN_TIMEOUT  2
39 static int shoutInitCount;
41 /* lots of this code blatantly stolent from bossogg/bossao2 */
43 typedef struct _ShoutData {
44         shout_t *shoutConn;
45         int shoutError;
47         ogg_stream_state os;
48         ogg_page og;
49         ogg_packet op;
50         ogg_packet header_main;
51         ogg_packet header_comments;
52         ogg_packet header_codebooks;
54         vorbis_dsp_state vd;
55         vorbis_block vb;
56         vorbis_info vi;
57         vorbis_comment vc;
59         float quality;
60         int bitrate;
62         int opened;
64         MpdTag *tag;
65         int tagToSend;
67         int timeout;
68         int connAttempts;
69         time_t lastAttempt;
71         Timer *timer;
73         /* just a pointer to audioOutput->outAudioFormat */
74         AudioFormat *audioFormat;
75 } ShoutData;
77 static ShoutData *newShoutData(void)
79         ShoutData *ret = xmalloc(sizeof(ShoutData));
81         ret->shoutConn = shout_new();
82         ret->opened = 0;
83         ret->tag = NULL;
84         ret->tagToSend = 0;
85         ret->bitrate = -1;
86         ret->quality = -2.0;
87         ret->timeout = DEFAULT_CONN_TIMEOUT;
88         ret->connAttempts = 0;
89         ret->lastAttempt = 0;
90         ret->audioFormat = NULL;
91         ret->timer = NULL;
93         return ret;
96 static void freeShoutData(ShoutData * sd)
98         if (sd->shoutConn)
99                 shout_free(sd->shoutConn);
100         if (sd->tag)
101                 freeMpdTag(sd->tag);
102         if (sd->timer)
103                 timer_free(sd->timer);
105         free(sd);
108 #define checkBlockParam(name) { \
109         blockParam = getBlockParam(param, name); \
110         if (!blockParam) { \
111                 FATAL("no \"%s\" defined for shout device defined at line " \
112                                 "%i\n", name, param->line); \
113         } \
116 static int myShout_initDriver(AudioOutput * audioOutput, ConfigParam * param)
118         ShoutData *sd;
119         char *test;
120         int port;
121         char *host;
122         char *mount;
123         char *passwd;
124         char *user;
125         char *name;
126         BlockParam *blockParam;
127         unsigned int public = 0;
129         sd = newShoutData();
131         if (shoutInitCount == 0)
132                 shout_init();
134         shoutInitCount++;
136         checkBlockParam("host");
137         host = blockParam->value;
139         checkBlockParam("mount");
140         mount = blockParam->value;
142         checkBlockParam("port");
144         port = strtol(blockParam->value, &test, 10);
146         if (*test != '\0' || port <= 0) {
147                 FATAL("shout port \"%s\" is not a positive integer, line %i\n",
148                       blockParam->value, blockParam->line);
149         }
151         checkBlockParam("password");
152         passwd = blockParam->value;
154         checkBlockParam("name");
155         name = blockParam->value;
157         blockParam = getBlockParam(param, "public");
158         if (blockParam) {
159                 if (0 == strcmp(blockParam->value, "yes")) {
160                         public = 1;
161                 } else if (0 == strcmp(blockParam->value, "no")) {
162                         public = 0;
163                 } else {
164                         FATAL("public \"%s\" is not \"yes\" or \"no\" at line "
165                               "%i\n", param->value, param->line);
166                 }
167         }
169         blockParam = getBlockParam(param, "user");
170         if (blockParam)
171                 user = blockParam->value;
172         else
173                 user = "source";
175         blockParam = getBlockParam(param, "quality");
177         if (blockParam) {
178                 int line = blockParam->line;
180                 sd->quality = strtod(blockParam->value, &test);
182                 if (*test != '\0' || sd->quality < -1.0 || sd->quality > 10.0) {
183                         FATAL("shout quality \"%s\" is not a number in the "
184                               "range -1 to 10, line %i\n", blockParam->value,
185                               blockParam->line);
186                 }
188                 blockParam = getBlockParam(param, "bitrate");
190                 if (blockParam) {
191                         FATAL("quality (line %i) and bitrate (line %i) are "
192                               "both defined for shout output\n", line,
193                               blockParam->line);
194                 }
195         } else {
196                 blockParam = getBlockParam(param, "bitrate");
198                 if (!blockParam) {
199                         FATAL("neither bitrate nor quality defined for shout "
200                               "output at line %i\n", param->line);
201                 }
203                 sd->bitrate = strtol(blockParam->value, &test, 10);
205                 if (*test != '\0' || sd->bitrate <= 0) {
206                         FATAL("bitrate at line %i should be a positive integer "
207                               "\n", blockParam->line);
208                 }
209         }
211         checkBlockParam("format");
212         sd->audioFormat = &audioOutput->outAudioFormat;
214         if (shout_set_host(sd->shoutConn, host) != SHOUTERR_SUCCESS ||
215             shout_set_port(sd->shoutConn, port) != SHOUTERR_SUCCESS ||
216             shout_set_password(sd->shoutConn, passwd) != SHOUTERR_SUCCESS ||
217             shout_set_mount(sd->shoutConn, mount) != SHOUTERR_SUCCESS ||
218             shout_set_name(sd->shoutConn, name) != SHOUTERR_SUCCESS ||
219             shout_set_user(sd->shoutConn, user) != SHOUTERR_SUCCESS ||
220             shout_set_public(sd->shoutConn, public) != SHOUTERR_SUCCESS ||
221             shout_set_nonblocking(sd->shoutConn, 1) != SHOUTERR_SUCCESS ||
222             shout_set_format(sd->shoutConn, SHOUT_FORMAT_VORBIS)
223             != SHOUTERR_SUCCESS ||
224             shout_set_protocol(sd->shoutConn, SHOUT_PROTOCOL_HTTP)
225             != SHOUTERR_SUCCESS ||
226             shout_set_agent(sd->shoutConn, "MPD") != SHOUTERR_SUCCESS) {
227                 FATAL("error configuring shout defined at line %i: %s\n",
228                       param->line, shout_get_error(sd->shoutConn));
229         }
231         /* optional paramters */
232         blockParam = getBlockParam(param, "timeout");
233         if (blockParam) {
234                 sd->timeout = strtod(blockParam->value, &test);
235                 if (*test != '\0' || sd->timeout <= 0) {
236                         FATAL("shout timeout is not a positive integer, "
237                               "line %i\n", blockParam->line);
238                 }
239         }
241         blockParam = getBlockParam(param, "genre");
242         if (blockParam && shout_set_genre(sd->shoutConn, blockParam->value)) {
243                 FATAL("error configuring shout defined at line %i: %s\n",
244                       param->line, shout_get_error(sd->shoutConn));
245         }
247         blockParam = getBlockParam(param, "description");
248         if (blockParam && shout_set_description(sd->shoutConn,
249                                                 blockParam->value)) {
250                 FATAL("error configuring shout defined at line %i: %s\n",
251                       param->line, shout_get_error(sd->shoutConn));
252         }
254         {
255                 char temp[11];
256                 memset(temp, 0, sizeof(temp));
258                 snprintf(temp, sizeof(temp), "%d", sd->audioFormat->channels);
259                 shout_set_audio_info(sd->shoutConn, SHOUT_AI_CHANNELS, temp);
261                 snprintf(temp, sizeof(temp), "%d", sd->audioFormat->sampleRate);
263                 shout_set_audio_info(sd->shoutConn, SHOUT_AI_SAMPLERATE, temp);
265                 if (sd->quality >= -1.0) {
266                         snprintf(temp, sizeof(temp), "%2.2f", sd->quality);
267                         shout_set_audio_info(sd->shoutConn, SHOUT_AI_QUALITY,
268                                              temp);
269                 } else {
270                         snprintf(temp, sizeof(temp), "%d", sd->bitrate);
271                         shout_set_audio_info(sd->shoutConn, SHOUT_AI_BITRATE,
272                                              temp);
273                 }
274         }
276         audioOutput->data = sd;
278         return 0;
281 static int myShout_handleError(ShoutData * sd, int err)
283         switch (err) {
284         case SHOUTERR_SUCCESS:
285                 break;
286         case SHOUTERR_UNCONNECTED:
287         case SHOUTERR_SOCKET:
288                 ERROR("Lost shout connection to %s:%i: %s\n",
289                       shout_get_host(sd->shoutConn),
290                       shout_get_port(sd->shoutConn),
291                       shout_get_error(sd->shoutConn));
292                 sd->shoutError = 1;
293                 return -1;
294         default:
295                 ERROR("shout: connection to %s:%i error: %s\n",
296                       shout_get_host(sd->shoutConn),
297                       shout_get_port(sd->shoutConn),
298                       shout_get_error(sd->shoutConn));
299                 sd->shoutError = 1;
300                 return -1;
301         }
303         return 0;
306 static int write_page(ShoutData * sd)
308         int err = 0;
310         shout_sync(sd->shoutConn);
311         err = shout_send(sd->shoutConn, sd->og.header, sd->og.header_len);
312         if (myShout_handleError(sd, err) < 0)
313                 return -1;
314         err = shout_send(sd->shoutConn, sd->og.body, sd->og.body_len);
315         if (myShout_handleError(sd, err) < 0)
316                 return -1;
318         return 0;
321 static void finishEncoder(ShoutData * sd)
323         vorbis_analysis_wrote(&sd->vd, 0);
325         while (vorbis_analysis_blockout(&sd->vd, &sd->vb) == 1) {
326                 vorbis_analysis(&sd->vb, NULL);
327                 vorbis_bitrate_addblock(&sd->vb);
328                 while (vorbis_bitrate_flushpacket(&sd->vd, &sd->op)) {
329                         ogg_stream_packetin(&sd->os, &sd->op);
330                 }
331         }
334 static int flushEncoder(ShoutData * sd)
336         return (ogg_stream_pageout(&sd->os, &sd->og) > 0);
339 static void clearEncoder(ShoutData * sd)
341         finishEncoder(sd);
342         while (1 == flushEncoder(sd)) {
343                 if (!sd->shoutError)
344                         write_page(sd);
345         }
347         vorbis_comment_clear(&sd->vc);
348         ogg_stream_clear(&sd->os);
349         vorbis_block_clear(&sd->vb);
350         vorbis_dsp_clear(&sd->vd);
351         vorbis_info_clear(&sd->vi);
354 static void myShout_closeShoutConn(ShoutData * sd)
356         if (sd->opened)
357                 clearEncoder(sd);
359         if (shout_get_connected(sd->shoutConn) != SHOUTERR_UNCONNECTED &&
360             shout_close(sd->shoutConn) != SHOUTERR_SUCCESS) {
361                 ERROR("problem closing connection to shout server: %s\n",
362                       shout_get_error(sd->shoutConn));
363         }
365         sd->opened = 0;
368 static void myShout_finishDriver(AudioOutput * audioOutput)
370         ShoutData *sd = (ShoutData *) audioOutput->data;
372         myShout_closeShoutConn(sd);
374         freeShoutData(sd);
376         shoutInitCount--;
378         if (shoutInitCount == 0)
379                 shout_shutdown();
382 static void myShout_dropBufferedAudio(AudioOutput * audioOutput)
384         ShoutData *sd = (ShoutData *)audioOutput->data;
385         timer_reset(sd->timer);
387         /* needs to be implemented for shout */
390 static void myShout_closeDevice(AudioOutput * audioOutput)
392         ShoutData *sd = (ShoutData *) audioOutput->data;
394         myShout_closeShoutConn(sd);
396         if (sd->timer) { 
397                 timer_free(sd->timer);
398                 sd->timer = NULL;
399         }
401         audioOutput->open = 0;
404 #define addTag(name, value) { \
405         if(value) vorbis_comment_add_tag(&(sd->vc), name, value); \
408 static void copyTagToVorbisComment(ShoutData * sd)
410         if (sd->tag) {
411                 int i;
413                 for (i = 0; i < sd->tag->numOfItems; i++) {
414                         switch (sd->tag->items[i].type) {
415                         case TAG_ITEM_ARTIST:
416                                 addTag("ARTIST", sd->tag->items[i].value);
417                                 break;
418                         case TAG_ITEM_ALBUM:
419                                 addTag("ALBUM", sd->tag->items[i].value);
420                                 break;
421                         case TAG_ITEM_TITLE:
422                                 addTag("TITLE", sd->tag->items[i].value);
423                                 break;
424                         }
425                 }
426         }
429 static int initEncoder(ShoutData * sd)
431         vorbis_info_init(&(sd->vi));
433         if (sd->quality >= -1.0) {
434                 if (0 != vorbis_encode_init_vbr(&(sd->vi),
435                                                 sd->audioFormat->channels,
436                                                 sd->audioFormat->sampleRate,
437                                                 sd->quality * 0.1)) {
438                         ERROR("problem setting up vorbis encoder for shout\n");
439                         vorbis_info_clear(&(sd->vi));
440                         return -1;
441                 }
442         } else {
443                 if (0 != vorbis_encode_init(&(sd->vi),
444                                             sd->audioFormat->channels,
445                                             sd->audioFormat->sampleRate, -1.0,
446                                             sd->bitrate * 1000, -1.0)) {
447                         ERROR("problem setting up vorbis encoder for shout\n");
448                         vorbis_info_clear(&(sd->vi));
449                         return -1;
450                 }
451         }
453         vorbis_analysis_init(&(sd->vd), &(sd->vi));
454         vorbis_block_init(&(sd->vd), &(sd->vb));
456         ogg_stream_init(&(sd->os), rand());
458         vorbis_comment_init(&(sd->vc));
460         return 0;
463 static int myShout_connect(ShoutData *sd)
465         time_t t = time(NULL);
466         int state = shout_get_connected(sd->shoutConn);
468         /* already connected */
469         if (state == SHOUTERR_CONNECTED)
470                 return 0;
472         /* waiting to connect */
473         if (state == SHOUTERR_BUSY && sd->connAttempts != 0) {
474                 /* timeout waiting to connect */
475                 if ((t - sd->lastAttempt) > sd->timeout) {
476                         ERROR("timeout connecting to shout server %s:%i "
477                               "(attempt %i)\n",
478                               shout_get_host(sd->shoutConn),
479                               shout_get_port(sd->shoutConn),
480                               sd->connAttempts);
481                         return -1;
482                 }
484                 return 1;
485         }
487         /* we're in some funky state, so just reset it to unconnected */
488         if (state != SHOUTERR_UNCONNECTED)
489                 shout_close(sd->shoutConn);
491         /* throttle new connection attempts */
492         if (sd->connAttempts != 0 &&
493             (t - sd->lastAttempt) <= CONN_ATTEMPT_INTERVAL) {
494                 return -1;
495         }
497         /* initiate a new connection */
499         sd->connAttempts++;
500         sd->lastAttempt = t;
502         state = shout_open(sd->shoutConn);
503         switch (state) {
504         case SHOUTERR_SUCCESS:
505         case SHOUTERR_CONNECTED:
506                 return 0;
507         case SHOUTERR_BUSY:
508                 return 1;
509         default:
510                 ERROR("problem opening connection to shout server %s:%i "
511                       "(attempt %i): %s\n",
512                       shout_get_host(sd->shoutConn),
513                       shout_get_port(sd->shoutConn),
514                       sd->connAttempts, shout_get_error(sd->shoutConn));
515                 return -1;
516         }
519 static int myShout_openShoutConn(AudioOutput * audioOutput)
521         ShoutData *sd = (ShoutData *) audioOutput->data;
522         int status;
524         status = myShout_connect(sd);
525         if (status != 0)
526                 return status;
528         if (initEncoder(sd) < 0) {
529                 shout_close(sd->shoutConn);
530                 return -1;
531         }
533         sd->shoutError = 0;
535         copyTagToVorbisComment(sd);
537         vorbis_analysis_headerout(&(sd->vd), &(sd->vc), &(sd->header_main),
538                                   &(sd->header_comments),
539                                   &(sd->header_codebooks));
541         ogg_stream_packetin(&(sd->os), &(sd->header_main));
542         ogg_stream_packetin(&(sd->os), &(sd->header_comments));
543         ogg_stream_packetin(&(sd->os), &(sd->header_codebooks));
545         sd->opened = 1;
546         sd->tagToSend = 0;
548         while (ogg_stream_flush(&(sd->os), &(sd->og))) {
549                 if (write_page(sd) < 0) {
550                         myShout_closeShoutConn(sd);
551                         return -1;
552                 }
553         }
555         sd->connAttempts = 0;
557         return 0;
560 static int myShout_openDevice(AudioOutput * audioOutput)
562         ShoutData *sd = (ShoutData *) audioOutput->data;
564         if (!sd->opened && myShout_openShoutConn(audioOutput) < 0)
565                 return -1;
567         if (sd->timer)
568                 timer_free(sd->timer);
570         sd->timer = timer_new(&audioOutput->outAudioFormat);
572         audioOutput->open = 1;
574         return 0;
577 static void myShout_sendMetadata(ShoutData * sd)
579         if (!sd->opened || !sd->tag)
580                 return;
582         clearEncoder(sd);
583         if (initEncoder(sd) < 0)
584                 return;
586         copyTagToVorbisComment(sd);
588         vorbis_analysis_headerout(&(sd->vd), &(sd->vc), &(sd->header_main),
589                                   &(sd->header_comments),
590                                   &(sd->header_codebooks));
592         ogg_stream_packetin(&(sd->os), &(sd->header_main));
593         ogg_stream_packetin(&(sd->os), &(sd->header_comments));
594         ogg_stream_packetin(&(sd->os), &(sd->header_codebooks));
596         while (ogg_stream_flush(&(sd->os), &(sd->og))) {
597                 if (write_page(sd) < 0) {
598                         myShout_closeShoutConn(sd);
599                         return;
600                 }
601         }
603         /*if(sd->tag) freeMpdTag(sd->tag);
604            sd->tag = NULL; */
605         sd->tagToSend = 0;
608 static int myShout_play(AudioOutput * audioOutput, char *playChunk, int size)
610         int i, j;
611         ShoutData *sd = (ShoutData *) audioOutput->data;
612         float **vorbbuf;
613         int samples;
614         int bytes = sd->audioFormat->bits / 8;
615         int status;
617         if (!sd->timer->started)
618                 timer_start(sd->timer);
620         timer_add(sd->timer, size);
622         if (sd->opened && sd->tagToSend)
623                 myShout_sendMetadata(sd);
625         if (!sd->opened) {
626                 status = myShout_openShoutConn(audioOutput);
627                 if (status < 0) {
628                         myShout_closeDevice(audioOutput);
629                         return -1;
630                 } else if (status > 0) {
631                         timer_sync(sd->timer);
632                         return 0;
633                 }
634         }
636         samples = size / (bytes * sd->audioFormat->channels);
638         /* this is for only 16-bit audio */
640         vorbbuf = vorbis_analysis_buffer(&(sd->vd), samples);
642         for (i = 0; i < samples; i++) {
643                 for (j = 0; j < sd->audioFormat->channels; j++) {
644                         vorbbuf[j][i] = (*((mpd_sint16 *) playChunk)) / 32768.0;
645                         playChunk += bytes;
646                 }
647         }
649         vorbis_analysis_wrote(&(sd->vd), samples);
651         while (1 == vorbis_analysis_blockout(&(sd->vd), &(sd->vb))) {
652                 vorbis_analysis(&(sd->vb), NULL);
653                 vorbis_bitrate_addblock(&(sd->vb));
655                 while (vorbis_bitrate_flushpacket(&(sd->vd), &(sd->op))) {
656                         ogg_stream_packetin(&(sd->os), &(sd->op));
657                 }
658         }
660         while (ogg_stream_pageout(&(sd->os), &(sd->og)) != 0) {
661                 if (write_page(sd) < 0) {
662                         myShout_closeDevice(audioOutput);
663                         return -1;
664                 }
665         }
667         return 0;
670 static void myShout_setTag(AudioOutput * audioOutput, MpdTag * tag)
672         ShoutData *sd = (ShoutData *) audioOutput->data;
674         if (sd->tag)
675                 freeMpdTag(sd->tag);
676         sd->tag = NULL;
677         sd->tagToSend = 0;
679         if (!tag)
680                 return;
682         sd->tag = mpdTagDup(tag);
683         sd->tagToSend = 1;
686 AudioOutputPlugin shoutPlugin = {
687         "shout",
688         NULL,
689         myShout_initDriver,
690         myShout_finishDriver,
691         myShout_openDevice,
692         myShout_play,
693         myShout_dropBufferedAudio,
694         myShout_closeDevice,
695         myShout_setTag,
698 #else
700 DISABLED_AUDIO_OUTPUT_PLUGIN(shoutPlugin)
701 #endif