Asterisk - The Open Source Telephony Project  21.4.1
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"
49 #include "asterisk/format_cache.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  <synopsis>
57  Play an MP3 file or M3U playlist file or stream.
58  </synopsis>
59  <syntax>
60  <parameter name="Location" required="true">
61  <para>Location of the file to be played.
62  (argument passed to mpg123)</para>
63  </parameter>
64  </syntax>
65  <description>
66  <para>Executes mpg123 to play the given location, which typically would be a mp3 filename
67  or m3u playlist filename or a URL. Please read https://en.wikipedia.org/wiki/M3U
68  to see what the M3U playlist file format is like.</para>
69  <para>Note that mpg123 does not support HTTPS, so use HTTP for web streams.</para>
70  <para>User can exit by pressing any key on the dialpad, or by hanging up.</para>
71  <example title="Play an MP3 playlist">
72  exten => 1234,1,MP3Player(/var/lib/asterisk/playlist.m3u)
73  </example>
74  <para>This application does not automatically answer and should be preceeded by an
75  application such as Answer() or Progress().</para>
76  </description>
77  </application>
78 
79  ***/
80 static char *app = "MP3Player";
81 
82 static int mp3play(const char *filename, unsigned int sampling_rate, int fd)
83 {
84  int res;
85  char sampling_rate_str[8];
86 
87  res = ast_safe_fork(0);
88  if (res < 0)
89  ast_log(LOG_WARNING, "Fork failed\n");
90  if (res) {
91  return res;
92  }
93  if (ast_opt_high_priority)
95 
96  dup2(fd, STDOUT_FILENO);
97  ast_close_fds_above_n(STDERR_FILENO);
98 
99  snprintf(sampling_rate_str, 8, "%u", sampling_rate);
100 
101  /* Execute mpg123, but buffer if it's a net connection */
102  if (!strncasecmp(filename, "http://", 7) && strstr(filename, ".m3u")) {
103  char buffer_size_str[8];
104  snprintf(buffer_size_str, 8, "%u", (int) 0.5*2*sampling_rate/1000); /* 0.5 seconds for a live stream */
105  /* Most commonly installed in /usr/local/bin */
106  execl(LOCAL_MPG_123, "mpg123", "-e", "s16", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
107  /* But many places has it in /usr/bin */
108  execl(MPG_123, "mpg123", "-e", "s16", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
109  /* As a last-ditch effort, try to use PATH */
110  execlp("mpg123", "mpg123", "-e", "s16", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
111  }
112  else if (!strncasecmp(filename, "http://", 7)) {
113  char buffer_size_str[8];
114  snprintf(buffer_size_str, 8, "%u", 6*2*sampling_rate/1000); /* 6 seconds for a remote MP3 file */
115  /* Most commonly installed in /usr/local/bin */
116  execl(LOCAL_MPG_123, "mpg123", "-e", "s16", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
117  /* But many places has it in /usr/bin */
118  execl(MPG_123, "mpg123", "-e", "s16", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
119  /* As a last-ditch effort, try to use PATH */
120  execlp("mpg123", "mpg123", "-e", "s16", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
121  }
122  else if (strstr(filename, ".m3u")) {
123  /* Most commonly installed in /usr/local/bin */
124  execl(LOCAL_MPG_123, "mpg123", "-e", "s16", "-q", "-z", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
125  /* But many places has it in /usr/bin */
126  execl(MPG_123, "mpg123", "-e", "s16", "-q", "-z", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
127  /* As a last-ditch effort, try to use PATH */
128  execlp("mpg123", "mpg123", "-e", "s16", "-q", "-z", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
129  }
130  else {
131  /* Most commonly installed in /usr/local/bin */
132  execl(MPG_123, "mpg123", "-e", "s16", "-q", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
133  /* But many places has it in /usr/bin */
134  execl(LOCAL_MPG_123, "mpg123", "-e", "s16", "-q", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
135  /* As a last-ditch effort, try to use PATH */
136  execlp("mpg123", "mpg123", "-e", "s16", "-q", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
137  }
138  /* Can't use ast_log since FD's are closed */
139  fprintf(stderr, "Execute of mpg123 failed\n");
140  _exit(0);
141 }
142 
143 static int timed_read(int fd, void *data, int datalen, int timeout, int pid)
144 {
145  int res;
146  int i;
147  struct pollfd fds[1];
148  fds[0].fd = fd;
149  fds[0].events = POLLIN;
150  for (i = 0; i < timeout; i++) {
151  res = ast_poll(fds, 1, 1000);
152  if (res > 0) {
153  break;
154  } else if (res == 0) {
155  /* is mpg123 still running? */
156  kill(pid, 0);
157  if (errno == ESRCH) {
158  return -1;
159  }
160  } else {
161  ast_log(LOG_NOTICE, "error polling mpg123: %s\n", strerror(errno));
162  return -1;
163  }
164  }
165 
166  if (i == timeout) {
167  ast_log(LOG_NOTICE, "Poll timed out.\n");
168  return -1;
169  }
170 
171  return read(fd, data, datalen);
172 
173 }
174 
175 static int mp3_exec(struct ast_channel *chan, const char *data)
176 {
177  int res=0;
178  int fds[2];
179  int ms = -1;
180  int pid = -1;
181  RAII_VAR(struct ast_format *, owriteformat, NULL, ao2_cleanup);
182  int timeout = 2;
183  int startedmp3 = 0;
184  struct timeval next;
185  struct ast_frame *f;
186  struct myframe {
187  struct ast_frame f;
189  short frdata[160];
190  } myf = {
191  .f = { 0, },
192  };
193  struct ast_format * native_format;
194  unsigned int sampling_rate;
195  struct ast_format * write_format;
196 
197  if (ast_strlen_zero(data)) {
198  ast_log(LOG_WARNING, "MP3 Playback requires an argument (filename)\n");
199  return -1;
200  }
201 
202  if (pipe(fds)) {
203  ast_log(LOG_WARNING, "Unable to create pipe\n");
204  return -1;
205  }
206 
207  ast_stopstream(chan);
208 
209  native_format = ast_format_cap_get_format(ast_channel_nativeformats(chan), 0);
210  sampling_rate = ast_format_get_sample_rate(native_format);
211  write_format = ast_format_cache_get_slin_by_rate(sampling_rate);
212 
213  owriteformat = ao2_bump(ast_channel_writeformat(chan));
214  res = ast_set_write_format(chan, write_format);
215  if (res < 0) {
216  ast_log(LOG_WARNING, "Unable to set write format to signed linear\n");
217  return -1;
218  }
219 
220  myf.f.frametype = AST_FRAME_VOICE;
221  myf.f.subclass.format = write_format;
222  myf.f.mallocd = 0;
223  myf.f.offset = AST_FRIENDLY_OFFSET;
224  myf.f.src = __PRETTY_FUNCTION__;
225  myf.f.delivery.tv_sec = 0;
226  myf.f.delivery.tv_usec = 0;
227  myf.f.data.ptr = myf.frdata;
228 
229  res = mp3play(data, sampling_rate, fds[1]);
230  if (!strncasecmp(data, "http://", 7)) {
231  timeout = 10;
232  }
233  /* Wait 1000 ms first */
234  next = ast_tvnow();
235  next.tv_sec += 1;
236  if (res >= 0) {
237  pid = res;
238  /* Order is important -- there's almost always going to be mp3... we want to prioritize the
239  user */
240  for (;;) {
241  ms = ast_tvdiff_ms(next, ast_tvnow());
242  if (ms <= 0) {
243  res = timed_read(fds[0], myf.frdata, sizeof(myf.frdata), timeout, pid);
244  if (res > 0) {
245  myf.f.datalen = res;
246  myf.f.samples = res / 2;
247  startedmp3 = 1;
248  if (ast_write(chan, &myf.f) < 0) {
249  res = -1;
250  break;
251  }
252  } else {
253  ast_debug(1, "No more mp3\n");
254  if (!startedmp3) { /* we couldn't do anything, which means this stream doesn't work */
255  if (!strncasecmp(data, "https://", 8)) {
256  ast_log(LOG_WARNING, "%s() does not support HTTPS streams. Use HTTP instead.\n", app);
257  }
258  ast_log(LOG_WARNING, "MP3 stream '%s' is broken or nonexistent\n", data);
259  }
260  res = 0;
261  break;
262  }
263  next = ast_tvadd(next, ast_samp2tv(myf.f.samples, sampling_rate));
264  } else {
265  ms = ast_waitfor(chan, ms);
266  if (ms < 0) {
267  ast_debug(1, "Hangup detected\n");
268  res = -1;
269  break;
270  }
271  if (ms) {
272  f = ast_read(chan);
273  if (!f) {
274  ast_debug(1, "Null frame == hangup() detected\n");
275  res = -1;
276  break;
277  }
278  if (f->frametype == AST_FRAME_DTMF) {
279  ast_debug(1, "User pressed a key\n");
280  ast_frfree(f);
281  res = 0;
282  break;
283  }
284  ast_frfree(f);
285  }
286  }
287  }
288  }
289  close(fds[0]);
290  close(fds[1]);
291 
292  if (pid > -1)
293  kill(pid, SIGKILL);
294  if (!res && owriteformat)
295  ast_set_write_format(chan, owriteformat);
296 
297  ast_frfree(&myf.f);
298 
299  return res;
300 }
301 
302 static int unload_module(void)
303 {
304  return ast_unregister_application(app);
305 }
306 
307 static int load_module(void)
308 {
309  return ast_register_application_xml(app, mp3_exec);
310 }
311 
312 AST_MODULE_INFO_STANDARD_EXTENDED(ASTERISK_GPL_KEY, "Silly MP3 Application");
Main Channel structure associated with a channel.
Asterisk locking-related definitions:
Asterisk main include file. File version handling, generic pbx functions.
Support for translation of data formats. translate.c.
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
struct ast_frame * ast_read(struct ast_channel *chan)
Reads a frame.
Definition: channel.c:4257
Definition of a media format.
Definition: format.c:43
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:159
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
Generic File Format Support. Should be included by clients of the file handling routines. File service providers should instead include mod_format.h.
int ast_unregister_application(const char *app)
Unregister an application.
Definition: pbx_app.c:392
#define ao2_bump(obj)
Bump refcount on an AO2 object by one, returning the object.
Definition: astobj2.h:480
General Asterisk PBX channel definitions.
#define AST_FRIENDLY_OFFSET
Offset into a frame's data buffer.
Asterisk internal frame definitions.
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
#define ast_debug(level,...)
Log a DEBUG message.
int ast_set_write_format(struct ast_channel *chan, struct ast_format *format)
Sets write format on channel chan.
Definition: channel.c:5803
Core PBX routines and definitions.
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:1841
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
struct timeval ast_tvadd(struct timeval a, struct timeval b)
Returns the sum of two timevals a + b.
Definition: extconf.c:2282
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:5144
int ast_waitfor(struct ast_channel *chan, int ms)
Wait for input on a channel.
Definition: channel.c:3162
unsigned int ast_format_get_sample_rate(const struct ast_format *format)
Get the sample rate of a media format.
Definition: format.c:379
Data structure associated with a single frame of data.
enum ast_frame_type frametype
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
#define ASTERISK_GPL_KEY
The text the key() function should return.
Definition: module.h:46
Asterisk module definitions.
#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
Application convenience functions, designed to give consistent look and feel to Asterisk apps...
int ast_stopstream(struct ast_channel *c)
Stops a stream.
Definition: file.c:222
#define ast_register_application_xml(app, execute)
Register an application using XML documentation.
Definition: module.h:640
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
Media Format Cache API.