Small clean up to http_open()
[cmus.git] / input.c
blob8c62d55156ef299eb5152d40ad613de2b26e6b6f
1 /*
2 * Copyright 2004-2005 Timo Hirvonen
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * 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
17 * 02111-1307, USA.
20 #include "input.h"
21 #include "ip.h"
22 #include "pcm.h"
23 #include "http.h"
24 #include "xmalloc.h"
25 #include "file.h"
26 #include "utils.h"
27 #include "cmus.h"
28 #include "list.h"
29 #include "misc.h"
30 #include "debug.h"
31 #include "ui_curses.h"
32 #include "config/libdir.h"
34 #include <unistd.h>
35 #include <string.h>
36 #include <errno.h>
37 #include <stdarg.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <fcntl.h>
41 #include <dirent.h>
42 #include <dlfcn.h>
44 struct input_plugin {
45 const struct input_plugin_ops *ops;
46 struct input_plugin_data data;
47 unsigned int open : 1;
48 unsigned int eof : 1;
49 int http_code;
50 char *http_reason;
52 /* cached duration, -1 = unset */
53 int duration;
56 * pcm is converted to 16-bit signed little-endian stereo
57 * NOTE: no conversion is done if channels > 2 or bits > 16
59 void (*pcm_convert)(char *, const char *, int);
60 void (*pcm_convert_in_place)(char *, int);
62 * 4 if 8-bit mono
63 * 2 if 8-bit stereo or 16-bit mono
64 * 1 otherwise
66 int pcm_convert_scale;
69 struct ip {
70 struct list_head node;
71 char *name;
72 void *handle;
74 const char * const *extensions;
75 const char * const *mime_types;
76 const struct input_plugin_ops *ops;
79 static const char * const plugin_dir = LIBDIR "/cmus/ip";
80 static LIST_HEAD(ip_head);
82 /* timeouts (ms) */
83 static int http_connection_timeout = 5e3;
84 static int http_read_timeout = 5e3;
86 static const char *pl_mime_types[] = {
87 "audio/m3u",
88 "audio/x-scpls",
89 "audio/x-mpegurl"
92 static const char *get_extension(const char *filename)
94 const char *ext;
96 ext = filename + strlen(filename) - 1;
97 while (ext >= filename && *ext != '/') {
98 if (*ext == '.') {
99 ext++;
100 return ext;
102 ext--;
104 return NULL;
107 static const struct input_plugin_ops *get_ops_by_filename(const char *filename)
109 struct ip *ip;
110 const char *ext;
112 ext = get_extension(filename);
113 if (ext == NULL)
114 return NULL;
115 list_for_each_entry(ip, &ip_head, node) {
116 const char * const *exts = ip->extensions;
117 int i;
119 for (i = 0; exts[i]; i++) {
120 if (strcasecmp(ext, exts[i]) == 0)
121 return ip->ops;
124 return NULL;
127 static const struct input_plugin_ops *get_ops_by_mime_type(const char *mime_type)
129 struct ip *ip;
131 list_for_each_entry(ip, &ip_head, node) {
132 const char * const *types = ip->mime_types;
133 int i;
135 for (i = 0; types[i]; i++) {
136 if (strcasecmp(mime_type, types[i]) == 0)
137 return ip->ops;
140 return NULL;
143 static int do_http_get(struct http_get *hg, const char *uri)
145 GROWING_KEYVALS(h);
146 int i, rc;
147 const char *val;
148 char *redirloc;
150 d_print("%s\n", uri);
152 hg->headers = NULL;
153 hg->reason = NULL;
154 hg->code = -1;
155 hg->fd = -1;
156 if (http_parse_uri(uri, &hg->uri))
157 return -IP_ERROR_INVALID_URI;
159 if (http_open(hg, http_connection_timeout))
160 return -IP_ERROR_ERRNO;
162 keyvals_add(&h, "Host", xstrdup(hg->uri.host));
163 keyvals_add(&h, "User-Agent", xstrdup("cmus/" VERSION));
164 keyvals_add(&h, "Icy-MetaData", xstrdup("1"));
165 if (hg->uri.user && hg->uri.pass) {
166 char buf[256];
167 char *encoded;
169 snprintf(buf, sizeof(buf), "%s:%s", hg->uri.user, hg->uri.pass);
170 encoded = base64_encode(buf);
171 if (encoded == NULL) {
172 d_print("couldn't base64 encode '%s'\n", buf);
173 } else {
174 snprintf(buf, sizeof(buf), "Basic %s", encoded);
175 free(encoded);
176 keyvals_add(&h, "Authorization", xstrdup(buf));
179 keyvals_terminate(&h);
181 rc = http_get(hg, h.keyvals, http_read_timeout);
182 keyvals_free(h.keyvals);
183 switch (rc) {
184 case -1:
185 return -IP_ERROR_ERRNO;
186 case -2:
187 return -IP_ERROR_HTTP_RESPONSE;
191 * FIXME: Use information from the headers, we read.
193 * especially interesting:
194 * + icy-name
195 * + icy-url
197 d_print("HTTP response: %d %s\n", hg->code, hg->reason);
198 for (i = 0; hg->headers[i].key != NULL; i++)
199 d_print(" %s: %s\n", hg->headers[i].key, hg->headers[i].val);
201 switch (hg->code) {
202 case 200: /* OK */
203 return 0;
205 * 3xx Codes (Redirections)
206 * unhandled: 300 Multiple Choices
208 case 301: /* Moved Permanently */
209 case 302: /* Found */
210 case 303: /* See Other */
211 case 307: /* Temporary Redirect */
212 val = keyvals_get_val(hg->headers, "location");
213 if (!val)
214 return -IP_ERROR_HTTP_RESPONSE;
215 redirloc = xstrdup(val);
216 http_get_free(hg);
217 close(hg->fd);
219 rc = do_http_get(hg, redirloc);
220 free(redirloc);
221 return rc;
222 default:
223 return -IP_ERROR_HTTP_STATUS;
227 static int setup_remote(struct input_plugin *ip, const struct keyval *headers, int sock)
229 const char *val;
231 val = keyvals_get_val(headers, "Content-Type");
232 if (val) {
233 d_print("Content-Type: %s\n", val);
234 ip->ops = get_ops_by_mime_type(val);
235 if (ip->ops == NULL) {
236 d_print("unsupported content type: %s\n", val);
237 close(sock);
238 return -IP_ERROR_FILE_FORMAT;
240 } else {
241 const char *type = "audio/mpeg";
243 d_print("assuming %s content type\n", type);
244 ip->ops = get_ops_by_mime_type(type);
245 if (ip->ops == NULL) {
246 d_print("unsupported content type: %s\n", type);
247 close(sock);
248 return -IP_ERROR_FILE_FORMAT;
252 ip->data.fd = sock;
253 ip->data.metadata = xmalloc(16 * 255 + 1);
255 val = keyvals_get_val(headers, "icy-metaint");
256 if (val) {
257 long int lint;
259 if (str_to_int(val, &lint) == 0 && lint >= 0) {
260 ip->data.metaint = lint;
261 d_print("metaint: %d\n", ip->data.metaint);
264 return 0;
267 struct read_playlist_data {
268 struct input_plugin *ip;
269 int rc;
270 int count;
273 static int handle_line(void *data, const char *uri)
275 struct read_playlist_data *rpd = data;
276 struct http_get hg;
278 rpd->count++;
279 rpd->rc = do_http_get(&hg, uri);
280 if (rpd->rc) {
281 rpd->ip->http_code = hg.code;
282 rpd->ip->http_reason = hg.reason;
283 if (hg.fd >= 0)
284 close(hg.fd);
286 hg.reason = NULL;
287 http_get_free(&hg);
288 return 0;
291 rpd->rc = setup_remote(rpd->ip, hg.headers, hg.fd);
292 http_get_free(&hg);
293 return 1;
296 static int read_playlist(struct input_plugin *ip, int sock)
298 struct read_playlist_data rpd = { ip, 0, 0 };
299 char *body;
300 int rc;
302 rc = http_read_body(sock, &body, http_read_timeout);
303 close(sock);
304 if (rc)
305 return -IP_ERROR_ERRNO;
307 cmus_playlist_for_each(body, strlen(body), 0, handle_line, &rpd);
308 free(body);
309 if (!rpd.count) {
310 d_print("empty playlist\n");
311 rpd.rc = -IP_ERROR_HTTP_RESPONSE;
313 return rpd.rc;
316 static int open_remote(struct input_plugin *ip)
318 struct input_plugin_data *d = &ip->data;
319 struct http_get hg;
320 const char *val;
321 int rc;
323 rc = do_http_get(&hg, d->filename);
324 if (rc) {
325 ip->http_code = hg.code;
326 ip->http_reason = hg.reason;
327 hg.reason = NULL;
328 http_get_free(&hg);
329 return rc;
332 val = keyvals_get_val(hg.headers, "Content-Type");
333 if (val) {
334 int i;
336 for (i = 0; i < sizeof(pl_mime_types) / sizeof(pl_mime_types[0]); i++) {
337 if (!strcasecmp(val, pl_mime_types[i])) {
338 d_print("Content-Type: %s\n", val);
339 http_get_free(&hg);
340 return read_playlist(ip, hg.fd);
345 rc = setup_remote(ip, hg.headers, hg.fd);
346 http_get_free(&hg);
347 return rc;
350 static int open_file(struct input_plugin *ip)
352 ip->ops = get_ops_by_filename(ip->data.filename);
353 if (ip->ops == NULL)
354 return -IP_ERROR_UNRECOGNIZED_FILE_TYPE;
355 ip->data.fd = open(ip->data.filename, O_RDONLY);
356 if (ip->data.fd == -1) {
357 ip->ops = NULL;
358 return -IP_ERROR_ERRNO;
360 return 0;
363 void ip_load_plugins(void)
365 DIR *dir;
366 struct dirent *d;
368 dir = opendir(plugin_dir);
369 if (dir == NULL) {
370 error_msg("couldn't open directory `%s': %s", plugin_dir, strerror(errno));
371 return;
373 while ((d = readdir(dir)) != NULL) {
374 char filename[256];
375 struct ip *ip;
376 void *so;
377 char *ext;
378 const char *sym;
380 if (d->d_name[0] == '.')
381 continue;
382 ext = strrchr(d->d_name, '.');
383 if (ext == NULL)
384 continue;
385 if (strcmp(ext, ".so"))
386 continue;
388 snprintf(filename, sizeof(filename), "%s/%s", plugin_dir, d->d_name);
390 so = dlopen(filename, RTLD_NOW);
391 if (so == NULL) {
392 error_msg("%s", dlerror());
393 continue;
396 ip = xnew(struct ip, 1);
398 sym = "ip_extensions";
399 if (!(ip->extensions = dlsym(so, sym)))
400 goto sym_err;
402 sym = "ip_mime_types";
403 if (!(ip->mime_types = dlsym(so, sym)))
404 goto sym_err;
406 sym = "ip_ops";
407 if (!(ip->ops = dlsym(so, sym)))
408 goto sym_err;
410 ip->name = xstrndup(d->d_name, ext - d->d_name);
411 ip->handle = so;
413 list_add_tail(&ip->node, &ip_head);
414 continue;
415 sym_err:
416 error_msg("%s: symbol %s not found", filename, sym);
417 free(ip);
418 dlclose(so);
420 closedir(dir);
423 static void ip_init(struct input_plugin *ip, char *filename)
425 memset(ip, 0, sizeof(*ip));
426 ip->http_code = -1;
427 ip->pcm_convert_scale = -1;
428 ip->duration = -1;
429 ip->data.fd = -1;
430 ip->data.filename = filename;
431 ip->data.remote = is_url(filename);
434 struct input_plugin *ip_new(const char *filename)
436 struct input_plugin *ip = xnew(struct input_plugin, 1);
438 ip_init(ip, xstrdup(filename));
439 return ip;
442 void ip_delete(struct input_plugin *ip)
444 if (ip->open)
445 ip_close(ip);
446 free(ip->data.filename);
447 free(ip);
450 int ip_open(struct input_plugin *ip)
452 int rc;
454 BUG_ON(ip->open);
456 /* set fd and ops */
457 if (ip->data.remote) {
458 rc = open_remote(ip);
459 } else {
460 rc = open_file(ip);
463 if (rc) {
464 d_print("opening `%s' failed: %d %s\n", ip->data.filename, rc,
465 rc == -1 ? strerror(errno) : "");
466 return rc;
469 rc = ip->ops->open(&ip->data);
470 if (rc) {
471 d_print("opening file `%s' failed: %d %s\n", ip->data.filename, rc,
472 rc == -1 ? strerror(errno) : "");
473 if (ip->data.fd != -1)
474 close(ip->data.fd);
475 free(ip->data.metadata);
476 ip_init(ip, ip->data.filename);
477 return rc;
479 ip->open = 1;
480 return 0;
483 void ip_setup(struct input_plugin *ip)
485 unsigned int bits, is_signed, channels;
486 sample_format_t sf = ip->data.sf;
488 bits = sf_get_bits(sf);
489 is_signed = sf_get_signed(sf);
490 channels = sf_get_channels(sf);
492 ip->pcm_convert_scale = 1;
493 ip->pcm_convert = NULL;
494 ip->pcm_convert_in_place = NULL;
496 if (bits <= 16 && channels <= 2) {
497 unsigned int mask = ((bits >> 2) & 4) | (is_signed << 1);
499 ip->pcm_convert = pcm_conv[mask | (channels - 1)];
500 ip->pcm_convert_in_place = pcm_conv_in_place[mask | sf_get_bigendian(sf)];
502 ip->pcm_convert_scale = (3 - channels) * (3 - bits / 8);
505 d_print("pcm convert: scale=%d convert=%d convert_in_place=%d\n",
506 ip->pcm_convert_scale,
507 ip->pcm_convert != NULL,
508 ip->pcm_convert_in_place != NULL);
511 int ip_close(struct input_plugin *ip)
513 int rc;
515 rc = ip->ops->close(&ip->data);
516 BUG_ON(ip->data.private);
517 if (ip->data.fd != -1)
518 close(ip->data.fd);
519 free(ip->data.metadata);
520 free(ip->http_reason);
522 ip_init(ip, ip->data.filename);
523 return rc;
526 int ip_read(struct input_plugin *ip, char *buffer, int count)
528 struct timeval tv;
529 fd_set readfds;
530 /* 4608 seems to be optimal for mp3s, 4096 for oggs */
531 char tmp[8 * 1024];
532 char *buf;
533 int sample_size;
534 int rc;
536 BUG_ON(count <= 0);
538 FD_ZERO(&readfds);
539 FD_SET(ip->data.fd, &readfds);
540 /* zero timeout -> return immediately */
541 tv.tv_sec = 0;
542 tv.tv_usec = 50e3;
543 rc = select(ip->data.fd + 1, &readfds, NULL, NULL, &tv);
544 if (rc == -1) {
545 if (errno == EINTR)
546 errno = EAGAIN;
547 return -1;
549 if (rc == 0) {
550 errno = EAGAIN;
551 return -1;
554 buf = buffer;
555 if (ip->pcm_convert_scale > 1) {
556 /* use tmp buffer for 16-bit mono and 8-bit */
557 buf = tmp;
558 count /= ip->pcm_convert_scale;
559 if (count > sizeof(tmp))
560 count = sizeof(tmp);
563 rc = ip->ops->read(&ip->data, buf, count);
564 if (rc == -1 && (errno == EAGAIN || errno == EINTR)) {
565 errno = EAGAIN;
566 return -1;
568 if (rc <= 0) {
569 ip->eof = 1;
570 return rc;
573 BUG_ON((rc & ~((unsigned int)sf_get_frame_size(ip->data.sf) - 1U)) != rc);
575 sample_size = sf_get_sample_size(ip->data.sf);
576 if (ip->pcm_convert_in_place != NULL)
577 ip->pcm_convert_in_place(buf, rc / sample_size);
578 if (ip->pcm_convert != NULL)
579 ip->pcm_convert(buffer, tmp, rc / sample_size);
580 return rc * ip->pcm_convert_scale;
583 int ip_seek(struct input_plugin *ip, double offset)
585 int rc;
587 if (ip->data.remote)
588 return -IP_ERROR_FUNCTION_NOT_SUPPORTED;
589 rc = ip->ops->seek(&ip->data, offset);
590 if (rc == 0)
591 ip->eof = 0;
592 return rc;
595 int ip_read_comments(struct input_plugin *ip, struct keyval **comments)
597 return ip->ops->read_comments(&ip->data, comments);
600 int ip_duration(struct input_plugin *ip)
602 if (ip->data.remote)
603 return -1;
604 if (ip->duration == -1)
605 ip->duration = ip->ops->duration(&ip->data);
606 if (ip->duration < 0)
607 return -1;
608 return ip->duration;
611 sample_format_t ip_get_sf(struct input_plugin *ip)
613 BUG_ON(!ip->open);
614 return ip->data.sf;
617 const char *ip_get_filename(struct input_plugin *ip)
619 return ip->data.filename;
622 const char *ip_get_metadata(struct input_plugin *ip)
624 BUG_ON(!ip->open);
625 return ip->data.metadata;
628 int ip_is_remote(struct input_plugin *ip)
630 return ip->data.remote;
633 int ip_metadata_changed(struct input_plugin *ip)
635 int ret = ip->data.metadata_changed;
637 BUG_ON(!ip->open);
638 ip->data.metadata_changed = 0;
639 return ret;
642 int ip_eof(struct input_plugin *ip)
644 BUG_ON(!ip->open);
645 return ip->eof;
648 char *ip_get_error_msg(struct input_plugin *ip, int rc, const char *arg)
650 char buffer[1024];
652 switch (-rc) {
653 case IP_ERROR_ERRNO:
654 snprintf(buffer, sizeof(buffer), "%s: %s", arg, strerror(errno));
655 break;
656 case IP_ERROR_UNRECOGNIZED_FILE_TYPE:
657 snprintf(buffer, sizeof(buffer),
658 "%s: unrecognized filename extension", arg);
659 break;
660 case IP_ERROR_FUNCTION_NOT_SUPPORTED:
661 snprintf(buffer, sizeof(buffer),
662 "%s: function not supported", arg);
663 break;
664 case IP_ERROR_FILE_FORMAT:
665 snprintf(buffer, sizeof(buffer),
666 "%s: file format not supported or corrupted file",
667 arg);
668 break;
669 case IP_ERROR_INVALID_URI:
670 snprintf(buffer, sizeof(buffer), "%s: invalid URI", arg);
671 break;
672 case IP_ERROR_SAMPLE_FORMAT:
673 snprintf(buffer, sizeof(buffer),
674 "%s: input plugin doesn't support the sample format",
675 arg);
676 break;
677 case IP_ERROR_HTTP_RESPONSE:
678 snprintf(buffer, sizeof(buffer), "%s: invalid HTTP response", arg);
679 break;
680 case IP_ERROR_HTTP_STATUS:
681 snprintf(buffer, sizeof(buffer), "%s: %d %s", arg, ip->http_code, ip->http_reason);
682 free(ip->http_reason);
683 ip->http_reason = NULL;
684 ip->http_code = -1;
685 break;
686 case IP_ERROR_INTERNAL:
687 snprintf(buffer, sizeof(buffer), "%s: internal error", arg);
688 break;
689 case IP_ERROR_SUCCESS:
690 default:
691 snprintf(buffer, sizeof(buffer),
692 "%s: this is not an error (%d), this is a bug",
693 arg, rc);
694 break;
696 return xstrdup(buffer);
699 char **ip_get_supported_extensions(void)
701 struct ip *ip;
702 char **exts;
703 int i, size;
704 int count = 0;
706 size = 8;
707 exts = xnew(char *, size);
708 list_for_each_entry(ip, &ip_head, node) {
709 const char * const *e = ip->extensions;
711 for (i = 0; e[i]; i++) {
712 if (count == size - 1) {
713 size *= 2;
714 exts = xrenew(char *, exts, size);
716 exts[count++] = xstrdup(e[i]);
719 exts[count] = NULL;
720 qsort(exts, count, sizeof(char *), strptrcmp);
721 return exts;
724 void ip_dump_plugins(void)
726 struct ip *ip;
727 int i;
729 printf("Input Plugins: %s\n", plugin_dir);
730 list_for_each_entry(ip, &ip_head, node) {
731 printf(" %s:\n File Types:", ip->name);
732 for (i = 0; ip->extensions[i]; i++)
733 printf(" %s", ip->extensions[i]);
734 printf("\n MIME Types:");
735 for (i = 0; ip->mime_types[i]; i++)
736 printf(" %s", ip->mime_types[i]);
737 printf("\n");