sad

simple audio daemon
git clone git@git.2f30.org/sad.git
Log | Files | Refs | LICENSE

mp3.c (1453B)


      1 #include <sys/select.h>
      2 
      3 #include <err.h>
      4 #include <limits.h>
      5 #include <stdio.h>
      6 #include <mpg123.h>
      7 
      8 #include "sad.h"
      9 
     10 static mpg123_handle *hdl;
     11 
     12 static int
     13 mp3open(Format *fmt, const char *name)
     14 {
     15 	int  r;
     16 	long rate;
     17 	int  channels, encoding;
     18 
     19 	if (mpg123_init() != MPG123_OK) {
     20 		warnx("mpg123_init: failed");
     21 		return -1;
     22 	}
     23 
     24 	hdl = mpg123_new(NULL, NULL);
     25 	if (!hdl) {
     26 		warnx("mpg123_new: failed");
     27 		goto err0;
     28 	}
     29 
     30 	r = mpg123_open(hdl, name);
     31 	if (r != MPG123_OK) {
     32 		warnx("mpg123_open: failed");
     33 		goto err1;
     34 	}
     35 
     36 	r = mpg123_getformat(hdl, &rate, &channels, &encoding);
     37 	if (r != MPG123_OK) {
     38 		warnx("mpg123_getformat: failed");
     39 		goto err2;
     40 	}
     41 
     42 	fmt->bits = mpg123_encsize(encoding) * 8;
     43 	fmt->rate = rate;
     44 	fmt->channels = channels;
     45 
     46 	if (initresamplers(fmt) < 0)
     47 		goto err2;
     48 
     49 	return 0;
     50 
     51 err2:
     52 	mpg123_close(hdl);
     53 err1:
     54 	mpg123_delete(hdl);
     55 err0:
     56 	mpg123_exit();
     57 	hdl = NULL;
     58 	return -1;
     59 }
     60 
     61 static int
     62 mp3decode(void *buf, int nbytes)
     63 {
     64 	size_t actual;
     65 	int    r;
     66 
     67 	r = mpg123_read(hdl, buf, nbytes, &actual);
     68 	if (r == MPG123_DONE)
     69 		return 0;
     70 	else if (r != MPG123_OK) {
     71 		warnx("mpg123_read: failed");
     72 		return -1;
     73 	}
     74 	return actual;
     75 }
     76 
     77 static int
     78 mp3close(void)
     79 {
     80 	int r = 0;
     81 
     82 	if (hdl) {
     83 		if (mpg123_close(hdl) != MPG123_OK) {
     84 			warnx("mpg123_close: failed");
     85 			r = -1;
     86 		}
     87 		mpg123_delete(hdl);
     88 		mpg123_exit();
     89 	}
     90 	hdl = NULL;
     91 	return r;
     92 }
     93 
     94 Decoder mp3decoder = {
     95 	.open = mp3open,
     96 	.decode = mp3decode,
     97 	.close = mp3close
     98 };