2 * "THE BEER-WARE LICENSE" (Revision 42):
3 * <tobias.rehbein@web.de> wrote this file. As long as you retain this notice
4 * you can do whatever you want with this stuff. If we meet some day, and you
5 * think this stuff is worth it, you can buy me a beer in return.
9 #define _POSIX_C_SOURCE 199506
20 #include <mpd/connection.h>
21 #include <mpd/error.h>
22 #include <mpd/player.h>
24 #include <mpd/status.h>
35 const char *NOTAVAILABLE
= "n/a";
36 const char *NOARTIST
= "unknown artist";
37 const char *NOTITLE
= "unknown title";
40 struct mpd_connection
*conn
;
41 char mpd_utf
[MPD_BUFFLEN
];
42 char mpd_str
[MPD_BUFFLEN
];
50 struct mpd_context
*ctx
;
52 if ((ctx
= malloc(sizeof(*ctx
))) == NULL
)
53 err(EX_SOFTWARE
, "malloc(%d) mpd_context", sizeof(*ctx
));
55 if ((ctx
->cd
= iconv_open("", "UTF-8")) == (iconv_t
) (-1))
56 err(EX_SOFTWARE
, "iconv_open");
59 ctx
->mpd_str
[0] = '\0';
60 ctx
->mpd_utf
[0] = '\0';
61 ctx
->last
= time(NULL
) - SLEEP
;
67 mpd_context_close(struct mpd_context
*ctx
)
71 if (iconv_close(ctx
->cd
) == -1)
72 err(EX_SOFTWARE
, "iconv_close");
74 if (ctx
->conn
!= NULL
)
75 mpd_connection_free(ctx
->conn
);
81 mpd_str(struct mpd_context
*ctx
)
83 struct mpd_song
*song
= NULL
;
84 struct mpd_status
*status
= NULL
;
85 const char *artist
, *title
;
87 size_t inleft
, outleft
;
93 if ((now
- ctx
->last
) < SLEEP
)
97 if (ctx
->conn
== NULL
) {
98 if ((ctx
->conn
= mpd_connection_new(NULL
, 0, 0)) == NULL
) {
99 warnx("mpd_connection_new");
100 strncpy(ctx
->mpd_str
, NOTAVAILABLE
, sizeof(ctx
->mpd_str
) - 1);
101 ctx
->mpd_str
[sizeof(ctx
->mpd_str
) - 1] = '\0';
105 assert(ctx
->conn
!= NULL
);
107 if ((status
= mpd_run_status(ctx
->conn
)) == NULL
) {
108 warnx("mpd_run_status: %s", mpd_connection_get_error_message(ctx
->conn
));
109 strncpy(ctx
->mpd_str
, NOTAVAILABLE
, sizeof(ctx
->mpd_str
) - 1);
110 ctx
->mpd_str
[sizeof(ctx
->mpd_str
) - 1] = '\0';
112 mpd_connection_free(ctx
->conn
);
116 if (mpd_status_get_state(status
) != MPD_STATE_PLAY
) {
117 ctx
->mpd_str
[0] = '\0';
120 if ((song
= mpd_run_current_song(ctx
->conn
)) == NULL
) {
121 strncpy(ctx
->mpd_str
, NOTAVAILABLE
, sizeof(ctx
->mpd_str
) - 1);
122 ctx
->mpd_str
[sizeof(ctx
->mpd_str
) - 1] = '\0';
125 if ((artist
= mpd_song_get_tag(song
, MPD_TAG_ARTIST
, 0)) == NULL
)
128 if ((title
= mpd_song_get_tag(song
, MPD_TAG_TITLE
, 0)) == NULL
)
131 inleft
= tools_catitems(ctx
->mpd_utf
, sizeof(ctx
->mpd_utf
), artist
, " - ", title
, NULL
);
133 inleft
= inleft
< sizeof(ctx
->mpd_utf
) ? inleft
: (sizeof(ctx
->mpd_utf
) - 1);
134 outleft
= sizeof(ctx
->mpd_str
);
135 in
= (char *)ctx
->mpd_utf
;
136 out
= (char *)ctx
->mpd_str
;
138 if (iconv(ctx
->cd
, NULL
, NULL
, &out
, &outleft
) == (size_t) (-1))
139 err(EX_SOFTWARE
, "iconv");
141 if (iconv(ctx
->cd
, (const char **)&in
, &inleft
, &out
, &outleft
) == (size_t) (-1)) {
152 mpd_status_free(status
);
154 return (ctx
->mpd_str
);