Asterisk - The Open Source Telephony Project  18.5.0
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 <[email protected]>
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 <[email protected]>
24  *
25  * \note Add feature to play local M3U playlist file
26  * Vincent Li <[email protected]>
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 http://en.wikipedia.org/wiki/M3U
68  to see how M3U playlist file format is like, Example usage would be
69  exten => 1234,1,MP3Player(/var/lib/asterisk/playlist.m3u)
70  User can exit by pressing any key on the dialpad, or by hanging up.</para>
71  <para>This application does not automatically answer and should be preceeded by an
72  application such as Answer() or Progress().</para>
73  </description>
74  </application>
75 
76  ***/
77 static char *app = "MP3Player";
78 
79 static int mp3play(const char *filename, unsigned int sampling_rate, int fd)
80 {
81  int res;
82  char sampling_rate_str[8];
83 
84  res = ast_safe_fork(0);
85  if (res < 0)
86  ast_log(LOG_WARNING, "Fork failed\n");
87  if (res) {
88  return res;
89  }
92 
93  dup2(fd, STDOUT_FILENO);
94  ast_close_fds_above_n(STDERR_FILENO);
95 
96  snprintf(sampling_rate_str, 8, "%u", sampling_rate);
97 
98  /* Execute mpg123, but buffer if it's a net connection */
99  if (!strncasecmp(filename, "http://", 7) && strstr(filename, ".m3u")) {
100  char buffer_size_str[8];
101  snprintf(buffer_size_str, 8, "%u", (int) 0.5*2*sampling_rate/1000); // 0.5 seconds for a live stream
102  /* Most commonly installed in /usr/local/bin */
103  execl(LOCAL_MPG_123, "mpg123", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
104  /* But many places has it in /usr/bin */
105  execl(MPG_123, "mpg123", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
106  /* As a last-ditch effort, try to use PATH */
107  execlp("mpg123", "mpg123", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
108  }
109  else if (!strncasecmp(filename, "http://", 7)) {
110  char buffer_size_str[8];
111  snprintf(buffer_size_str, 8, "%u", 6*2*sampling_rate/1000); // 6 seconds for a remote MP3 file
112  /* Most commonly installed in /usr/local/bin */
113  execl(LOCAL_MPG_123, "mpg123", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
114  /* But many places has it in /usr/bin */
115  execl(MPG_123, "mpg123", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
116  /* As a last-ditch effort, try to use PATH */
117  execlp("mpg123", "mpg123", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
118  }
119  else if (strstr(filename, ".m3u")) {
120  /* Most commonly installed in /usr/local/bin */
121  execl(LOCAL_MPG_123, "mpg123", "-q", "-z", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
122  /* But many places has it in /usr/bin */
123  execl(MPG_123, "mpg123", "-q", "-z", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
124  /* As a last-ditch effort, try to use PATH */
125  execlp("mpg123", "mpg123", "-q", "-z", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
126  }
127  else {
128  /* Most commonly installed in /usr/local/bin */
129  execl(MPG_123, "mpg123", "-q", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
130  /* But many places has it in /usr/bin */
131  execl(LOCAL_MPG_123, "mpg123", "-q", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
132  /* As a last-ditch effort, try to use PATH */
133  execlp("mpg123", "mpg123", "-q", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
134  }
135  /* Can't use ast_log since FD's are closed */
136  fprintf(stderr, "Execute of mpg123 failed\n");
137  _exit(0);
138 }
139 
140 static int timed_read(int fd, void *data, int datalen, int timeout, int pid)
141 {
142  int res;
143  int i;
144  struct pollfd fds[1];
145  fds[0].fd = fd;
146  fds[0].events = POLLIN;
147  for (i = 0; i < timeout; i++) {
148  res = ast_poll(fds, 1, 1000);
149  if (res > 0) {
150  break;
151  } else if (res == 0) {
152  /* is mpg123 still running? */
153  kill(pid, 0);
154  if (errno == ESRCH) {
155  return -1;
156  }
157  } else {
158  ast_log(LOG_NOTICE, "error polling mpg123: %s\n", strerror(errno));
159  return -1;
160  }
161  }
162 
163  if (i == timeout) {
164  ast_log(LOG_NOTICE, "Poll timed out.\n");
165  return -1;
166  }
167 
168  return read(fd, data, datalen);
169 
170 }
171 
172 static int mp3_exec(struct ast_channel *chan, const char *data)
173 {
174  int res=0;
175  int fds[2];
176  int ms = -1;
177  int pid = -1;
178  RAII_VAR(struct ast_format *, owriteformat, NULL, ao2_cleanup);
179  int timeout = 2;
180  struct timeval next;
181  struct ast_frame *f;
182  struct myframe {
183  struct ast_frame f;
185  short frdata[160];
186  } myf = {
187  .f = { 0, },
188  };
189  struct ast_format * native_format;
190  unsigned int sampling_rate;
191  struct ast_format * write_format;
192 
193  if (ast_strlen_zero(data)) {
194  ast_log(LOG_WARNING, "MP3 Playback requires an argument (filename)\n");
195  return -1;
196  }
197 
198  if (pipe(fds)) {
199  ast_log(LOG_WARNING, "Unable to create pipe\n");
200  return -1;
201  }
202 
203  ast_stopstream(chan);
204 
205  native_format = ast_format_cap_get_format(ast_channel_nativeformats(chan), 0);
206  sampling_rate = ast_format_get_sample_rate(native_format);
207  write_format = ast_format_cache_get_slin_by_rate(sampling_rate);
208 
209  owriteformat = ao2_bump(ast_channel_writeformat(chan));
210  res = ast_set_write_format(chan, write_format);
211  if (res < 0) {
212  ast_log(LOG_WARNING, "Unable to set write format to signed linear\n");
213  return -1;
214  }
215 
216  myf.f.frametype = AST_FRAME_VOICE;
217  myf.f.subclass.format = write_format;
218  myf.f.mallocd = 0;
219  myf.f.offset = AST_FRIENDLY_OFFSET;
220  myf.f.src = __PRETTY_FUNCTION__;
221  myf.f.delivery.tv_sec = 0;
222  myf.f.delivery.tv_usec = 0;
223  myf.f.data.ptr = myf.frdata;
224 
225  res = mp3play(data, sampling_rate, fds[1]);
226  if (!strncasecmp(data, "http://", 7)) {
227  timeout = 10;
228  }
229  /* Wait 1000 ms first */
230  next = ast_tvnow();
231  next.tv_sec += 1;
232  if (res >= 0) {
233  pid = res;
234  /* Order is important -- there's almost always going to be mp3... we want to prioritize the
235  user */
236  for (;;) {
237  ms = ast_tvdiff_ms(next, ast_tvnow());
238  if (ms <= 0) {
239  res = timed_read(fds[0], myf.frdata, sizeof(myf.frdata), timeout, pid);
240  if (res > 0) {
241  myf.f.datalen = res;
242  myf.f.samples = res / 2;
243  if (ast_write(chan, &myf.f) < 0) {
244  res = -1;
245  break;
246  }
247  } else {
248  ast_debug(1, "No more mp3\n");
249  res = 0;
250  break;
251  }
252  next = ast_tvadd(next, ast_samp2tv(myf.f.samples, sampling_rate));
253  } else {
254  ms = ast_waitfor(chan, ms);
255  if (ms < 0) {
256  ast_debug(1, "Hangup detected\n");
257  res = -1;
258  break;
259  }
260  if (ms) {
261  f = ast_read(chan);
262  if (!f) {
263  ast_debug(1, "Null frame == hangup() detected\n");
264  res = -1;
265  break;
266  }
267  if (f->frametype == AST_FRAME_DTMF) {
268  ast_debug(1, "User pressed a key\n");
269  ast_frfree(f);
270  res = 0;
271  break;
272  }
273  ast_frfree(f);
274  }
275  }
276  }
277  }
278  close(fds[0]);
279  close(fds[1]);
280 
281  if (pid > -1)
282  kill(pid, SIGKILL);
283  if (!res && owriteformat)
284  ast_set_write_format(chan, owriteformat);
285 
286  ast_frfree(&myf.f);
287 
288  return res;
289 }
290 
291 static int unload_module(void)
292 {
294 }
295 
296 static int load_module(void)
297 {
299 }
300 
301 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.
static int mp3play(const char *filename, unsigned int sampling_rate, int fd)
Definition: app_mp3.c:79
#define LOG_WARNING
Definition: logger.h:274
AST_MODULE_INFO_STANDARD_EXTENDED(ASTERISK_GPL_KEY, "Silly MP3 Application")
static int timeout
Definition: cdr_mysql.c:86
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:3042
struct ast_frame * ast_read(struct ast_channel *chan)
Reads a frame.
Definition: channel.c:4302
Definition of a media format.
Definition: format.c:43
static int unload_module(void)
Definition: app_mp3.c:291
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:150
int64_t ast_tvdiff_ms(struct timeval end, struct timeval start)
Computes the difference (in milliseconds) between two struct timeval instances.
Definition: time.h:98
Generic File Format Support. Should be included by clients of the file handling routines. File service providers should instead include mod_format.h.
#define NULL
Definition: resample.c:96
#define AST_FRAME_DTMF
int ast_unregister_application(const char *app)
Unregister an application.
Definition: pbx_app.c:392
#define ast_strlen_zero(foo)
Definition: strings.h:52
#define ao2_bump(obj)
Definition: astobj2.h:491
#define ast_debug(level,...)
Log a DEBUG message.
Definition: logger.h:452
#define ast_log
Definition: astobj2.c:42
General Asterisk PBX channel definitions.
#define AST_FRIENDLY_OFFSET
Offset into a frame&#39;s data buffer.
#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:911
#define ast_poll(a, b, c)
Definition: poll-compat.h:88
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:238
int ast_set_write_format(struct ast_channel *chan, struct ast_format *format)
Sets write format on channel chan.
Definition: channel.c:5890
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:1799
int errno
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:3047
struct timeval ast_tvadd(struct timeval a, struct timeval b)
Returns the sum of two timevals a + b.
Definition: extconf.c:2283
#define LOG_NOTICE
Definition: logger.h:263
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:5189
struct ast_format_cap * ast_channel_nativeformats(const struct ast_channel *chan)
#define LOCAL_MPG_123
Definition: app_mp3.c:51
int ast_waitfor(struct ast_channel *chan, int ms)
Wait for input on a channel.
Definition: channel.c:3171
#define ao2_cleanup(obj)
Definition: astobj2.h:1958
#define ast_frfree(fr)
unsigned int ast_format_get_sample_rate(const struct ast_format *format)
Get the sample rate of a media format.
Definition: format.c:379
static char * app
Definition: app_mp3.c:77
Data structure associated with a single frame of data.
static int load_module(void)
Definition: app_mp3.c:296
#define MPG_123
Definition: app_mp3.c:52
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
static int timed_read(int fd, void *data, int datalen, int timeout, int pid)
Definition: app_mp3.c:140
#define ASTERISK_GPL_KEY
The text the key() function should return.
Definition: module.h:46
static int mp3_exec(struct ast_channel *chan, const char *data)
Definition: app_mp3.c:172
Asterisk module definitions.
struct ast_format * ast_channel_writeformat(struct ast_channel *chan)
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:187
#define ast_register_application_xml(app, execute)
Register an application using XML documentation.
Definition: module.h:626
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:520
#define ast_opt_high_priority
Definition: options.h:110
Media Format Cache API.