Asterisk - The Open Source Telephony Project GIT-master-754dea3
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros Modules Pages
app_mp3.c
Go to the documentation of this file.
1/*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2005, Digium, Inc.
5 *
6 * Mark Spencer <markster@digium.com>
7 *
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
13 *
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
17 */
18
19/*! \file
20 *
21 * \brief Silly application to play an MP3 file -- uses mpg123
22 *
23 * \author Mark Spencer <markster@digium.com>
24 *
25 * \note Add feature to play local M3U playlist file
26 * Vincent Li <mchun.li@gmail.com>
27 *
28 * \ingroup applications
29 */
30
31/*** MODULEINFO
32 <support_level>extended</support_level>
33 ***/
34
35#include "asterisk.h"
36
37#include <sys/time.h>
38#include <sys/types.h>
39#include <signal.h>
40
41#include "asterisk/lock.h"
42#include "asterisk/file.h"
43#include "asterisk/channel.h"
44#include "asterisk/frame.h"
45#include "asterisk/pbx.h"
46#include "asterisk/module.h"
47#include "asterisk/translate.h"
48#include "asterisk/app.h"
50
51#define LOCAL_MPG_123 "/usr/local/bin/mpg123"
52#define MPG_123 "/usr/bin/mpg123"
53
54/*** DOCUMENTATION
55 <application name="MP3Player" language="en_US">
56 <since>
57 <version>0.1.0</version>
58 </since>
59 <synopsis>
60 Play an MP3 file or M3U playlist file or stream.
61 </synopsis>
62 <syntax>
63 <parameter name="Location" required="true">
64 <para>Location of the file to be played.
65 (argument passed to mpg123)</para>
66 </parameter>
67 </syntax>
68 <description>
69 <para>Executes mpg123 to play the given location, which typically would be a mp3 filename
70 or m3u playlist filename or a URL. Please read https://en.wikipedia.org/wiki/M3U
71 to see what the M3U playlist file format is like.</para>
72 <para>Note that mpg123 does not support HTTPS, so use HTTP for web streams.</para>
73 <para>User can exit by pressing any key on the dialpad, or by hanging up.</para>
74 <example title="Play an MP3 playlist">
75 exten => 1234,1,MP3Player(/var/lib/asterisk/playlist.m3u)
76 </example>
77 <para>This application does not automatically answer and should be preceded by an
78 application such as Answer() or Progress().</para>
79 </description>
80 </application>
81
82 ***/
83static char *app = "MP3Player";
84
85static int mp3play(const char *filename, unsigned int sampling_rate, int fd)
86{
87 int res;
88 char sampling_rate_str[8];
89
90 res = ast_safe_fork(0);
91 if (res < 0)
92 ast_log(LOG_WARNING, "Fork failed\n");
93 if (res) {
94 return res;
95 }
98
99 dup2(fd, STDOUT_FILENO);
100 ast_close_fds_above_n(STDERR_FILENO);
101
102 snprintf(sampling_rate_str, 8, "%u", sampling_rate);
103
104 /* Execute mpg123, but buffer if it's a net connection */
105 if (!strncasecmp(filename, "http://", 7) && strstr(filename, ".m3u")) {
106 char buffer_size_str[8];
107 snprintf(buffer_size_str, 8, "%u", (int) 0.5*2*sampling_rate/1000); /* 0.5 seconds for a live stream */
108 /* Most commonly installed in /usr/local/bin */
109 execl(LOCAL_MPG_123, "mpg123", "-e", "s16", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
110 /* But many places has it in /usr/bin */
111 execl(MPG_123, "mpg123", "-e", "s16", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
112 /* As a last-ditch effort, try to use PATH */
113 execlp("mpg123", "mpg123", "-e", "s16", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
114 }
115 else if (!strncasecmp(filename, "http://", 7)) {
116 char buffer_size_str[8];
117 snprintf(buffer_size_str, 8, "%u", 6*2*sampling_rate/1000); /* 6 seconds for a remote MP3 file */
118 /* Most commonly installed in /usr/local/bin */
119 execl(LOCAL_MPG_123, "mpg123", "-e", "s16", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
120 /* But many places has it in /usr/bin */
121 execl(MPG_123, "mpg123", "-e", "s16", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
122 /* As a last-ditch effort, try to use PATH */
123 execlp("mpg123", "mpg123", "-e", "s16", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
124 }
125 else if (strstr(filename, ".m3u")) {
126 /* Most commonly installed in /usr/local/bin */
127 execl(LOCAL_MPG_123, "mpg123", "-e", "s16", "-q", "-z", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
128 /* But many places has it in /usr/bin */
129 execl(MPG_123, "mpg123", "-e", "s16", "-q", "-z", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
130 /* As a last-ditch effort, try to use PATH */
131 execlp("mpg123", "mpg123", "-e", "s16", "-q", "-z", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
132 }
133 else {
134 /* Most commonly installed in /usr/local/bin */
135 execl(MPG_123, "mpg123", "-e", "s16", "-q", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
136 /* But many places has it in /usr/bin */
137 execl(LOCAL_MPG_123, "mpg123", "-e", "s16", "-q", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
138 /* As a last-ditch effort, try to use PATH */
139 execlp("mpg123", "mpg123", "-e", "s16", "-q", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
140 }
141 /* Can't use ast_log since FD's are closed */
142 fprintf(stderr, "Execute of mpg123 failed\n");
143 _exit(0);
144}
145
146static int timed_read(int fd, void *data, int datalen, int timeout, int pid)
147{
148 int res;
149 int i;
150 struct pollfd fds[1];
151 fds[0].fd = fd;
152 fds[0].events = POLLIN;
153 for (i = 0; i < timeout; i++) {
154 res = ast_poll(fds, 1, 1000);
155 if (res > 0) {
156 break;
157 } else if (res == 0) {
158 /* is mpg123 still running? */
159 kill(pid, 0);
160 if (errno == ESRCH) {
161 return -1;
162 }
163 } else {
164 ast_log(LOG_NOTICE, "error polling mpg123: %s\n", strerror(errno));
165 return -1;
166 }
167 }
168
169 if (i == timeout) {
170 ast_log(LOG_NOTICE, "Poll timed out.\n");
171 return -1;
172 }
173
174 return read(fd, data, datalen);
175
176}
177
178static int mp3_exec(struct ast_channel *chan, const char *data)
179{
180 int res=0;
181 int fds[2];
182 int ms = -1;
183 int pid = -1;
184 RAII_VAR(struct ast_format *, owriteformat, NULL, ao2_cleanup);
185 int timeout = 2;
186 int startedmp3 = 0;
187 struct timeval next;
188 struct ast_frame *f;
189 struct myframe {
190 struct ast_frame f;
192 short frdata[160];
193 } myf = {
194 .f = { 0, },
195 };
196 struct ast_format * native_format;
197 unsigned int sampling_rate;
198 struct ast_format * write_format;
199
200 if (ast_strlen_zero(data)) {
201 ast_log(LOG_WARNING, "MP3 Playback requires an argument (filename)\n");
202 return -1;
203 }
204
205 if (pipe(fds)) {
206 ast_log(LOG_WARNING, "Unable to create pipe\n");
207 return -1;
208 }
209
210 ast_stopstream(chan);
211
213 sampling_rate = ast_format_get_sample_rate(native_format);
214 write_format = ast_format_cache_get_slin_by_rate(sampling_rate);
215
216 owriteformat = ao2_bump(ast_channel_writeformat(chan));
217 res = ast_set_write_format(chan, write_format);
218 if (res < 0) {
219 ast_log(LOG_WARNING, "Unable to set write format to signed linear\n");
220 return -1;
221 }
222
223 myf.f.frametype = AST_FRAME_VOICE;
224 myf.f.subclass.format = write_format;
225 myf.f.mallocd = 0;
226 myf.f.offset = AST_FRIENDLY_OFFSET;
227 myf.f.src = __PRETTY_FUNCTION__;
228 myf.f.delivery.tv_sec = 0;
229 myf.f.delivery.tv_usec = 0;
230 myf.f.data.ptr = myf.frdata;
231
232 res = mp3play(data, sampling_rate, fds[1]);
233 if (!strncasecmp(data, "http://", 7)) {
234 timeout = 10;
235 }
236 /* Wait 1000 ms first */
237 next = ast_tvnow();
238 next.tv_sec += 1;
239 if (res >= 0) {
240 pid = res;
241 /* Order is important -- there's almost always going to be mp3... we want to prioritize the
242 user */
243 for (;;) {
244 ms = ast_tvdiff_ms(next, ast_tvnow());
245 if (ms <= 0) {
246 res = timed_read(fds[0], myf.frdata, sizeof(myf.frdata), timeout, pid);
247 if (res > 0) {
248 myf.f.datalen = res;
249 myf.f.samples = res / 2;
250 startedmp3 = 1;
251 if (ast_write(chan, &myf.f) < 0) {
252 res = -1;
253 break;
254 }
255 } else {
256 ast_debug(1, "No more mp3\n");
257 if (!startedmp3) { /* we couldn't do anything, which means this stream doesn't work */
258 if (!strncasecmp(data, "https://", 8)) {
259 ast_log(LOG_WARNING, "%s() does not support HTTPS streams. Use HTTP instead.\n", app);
260 }
261 ast_log(LOG_WARNING, "MP3 stream '%s' is broken or nonexistent\n", data);
262 }
263 res = 0;
264 break;
265 }
266 next = ast_tvadd(next, ast_samp2tv(myf.f.samples, sampling_rate));
267 } else {
268 ms = ast_waitfor(chan, ms);
269 if (ms < 0) {
270 ast_debug(1, "Hangup detected\n");
271 res = -1;
272 break;
273 }
274 if (ms) {
275 f = ast_read(chan);
276 if (!f) {
277 ast_debug(1, "Null frame == hangup() detected\n");
278 res = -1;
279 break;
280 }
281 if (f->frametype == AST_FRAME_DTMF) {
282 ast_debug(1, "User pressed a key\n");
283 ast_frfree(f);
284 res = 0;
285 break;
286 }
287 ast_frfree(f);
288 }
289 }
290 }
291 }
292 close(fds[0]);
293 close(fds[1]);
294
295 if (pid > -1)
296 kill(pid, SIGKILL);
297 if (!res && owriteformat)
298 ast_set_write_format(chan, owriteformat);
299
300 ast_frfree(&myf.f);
301
302 return res;
303}
304
305static int unload_module(void)
306{
308}
309
310static int load_module(void)
311{
313}
314
#define MPG_123
Definition: app_mp3.c:52
static int timed_read(int fd, void *data, int datalen, int timeout, int pid)
Definition: app_mp3.c:146
#define LOCAL_MPG_123
Definition: app_mp3.c:51
static char * app
Definition: app_mp3.c:83
static int load_module(void)
Definition: app_mp3.c:310
static int unload_module(void)
Definition: app_mp3.c:305
AST_MODULE_INFO_STANDARD_EXTENDED(ASTERISK_GPL_KEY, "Silly MP3 Application")
static int mp3play(const char *filename, unsigned int sampling_rate, int fd)
Definition: app_mp3.c:85
static int mp3_exec(struct ast_channel *chan, const char *data)
Definition: app_mp3.c:178
Asterisk main include file. File version handling, generic pbx functions.
int ast_set_priority(int)
We set ourselves to a high priority, that we might pre-empt everything else. If your PBX has heavy ac...
Definition: asterisk.c:1848
#define ast_log
Definition: astobj2.c:42
#define ao2_cleanup(obj)
Definition: astobj2.h:1934
#define ao2_bump(obj)
Bump refcount on an AO2 object by one, returning the object.
Definition: astobj2.h:480
General Asterisk PBX channel definitions.
struct ast_format_cap * ast_channel_nativeformats(const struct ast_channel *chan)
int ast_waitfor(struct ast_channel *chan, int ms)
Wait for input on a channel.
Definition: channel.c:3190
int ast_write(struct ast_channel *chan, struct ast_frame *frame)
Write a frame to a channel This function writes the given frame to the indicated channel.
Definition: channel.c:5161
struct ast_frame * ast_read(struct ast_channel *chan)
Reads a frame.
Definition: channel.c:4274
struct ast_format * ast_channel_writeformat(struct ast_channel *chan)
int ast_set_write_format(struct ast_channel *chan, struct ast_format *format)
Sets write format on channel chan.
Definition: channel.c:5820
Generic File Format Support. Should be included by clients of the file handling routines....
int ast_stopstream(struct ast_channel *c)
Stops a stream.
Definition: file.c:222
unsigned int ast_format_get_sample_rate(const struct ast_format *format)
Get the sample rate of a media format.
Definition: format.c:379
Media Format Cache API.
struct ast_format * ast_format_cache_get_slin_by_rate(unsigned int rate)
Retrieve the best signed linear format given a sample rate.
Definition: format_cache.c:512
struct ast_format * ast_format_cap_get_format(const struct ast_format_cap *cap, int position)
Get the format at a specific index.
Definition: format_cap.c:400
Application convenience functions, designed to give consistent look and feel to Asterisk apps.
int ast_safe_fork(int stop_reaper)
Common routine to safely fork without a chance of a signal handler firing badly in the child.
Definition: main/app.c:3207
void ast_close_fds_above_n(int n)
Common routine for child processes, to close all fds prior to exec(2)
Definition: main/app.c:3202
Asterisk internal frame definitions.
#define AST_FRAME_DTMF
#define ast_frfree(fr)
#define AST_FRIENDLY_OFFSET
Offset into a frame's data buffer.
@ AST_FRAME_VOICE
#define ast_debug(level,...)
Log a DEBUG message.
#define LOG_NOTICE
#define LOG_WARNING
Asterisk locking-related definitions:
int errno
Asterisk module definitions.
#define ASTERISK_GPL_KEY
The text the key() function should return.
Definition: module.h:46
int ast_unregister_application(const char *app)
Unregister an application.
Definition: pbx_app.c:392
#define ast_register_application_xml(app, execute)
Register an application using XML documentation.
Definition: module.h:640
#define ast_opt_high_priority
Definition: options.h:112
Core PBX routines and definitions.
#define ast_poll(a, b, c)
Definition: poll-compat.h:88
#define NULL
Definition: resample.c:96
static force_inline int attribute_pure ast_strlen_zero(const char *s)
Definition: strings.h:65
Main Channel structure associated with a channel.
Definition of a media format.
Definition: format.c:43
Data structure associated with a single frame of data.
enum ast_frame_type frametype
struct timeval ast_samp2tv(unsigned int _nsamp, unsigned int _rate)
Returns a timeval corresponding to the duration of n samples at rate r. Useful to convert samples to ...
Definition: time.h:282
struct timeval ast_tvadd(struct timeval a, struct timeval b)
Returns the sum of two timevals a + b.
Definition: extconf.c:2282
int64_t ast_tvdiff_ms(struct timeval end, struct timeval start)
Computes the difference (in milliseconds) between two struct timeval instances.
Definition: time.h:107
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:159
Support for translation of data formats. translate.c.
#define RAII_VAR(vartype, varname, initval, dtor)
Declare a variable that will call a destructor function when it goes out of scope.
Definition: utils.h:941