Merge "BuildSystem: For consistency, avoid double-checking via if clauses."
[asterisk/asterisk.git] / apps / app_mp3.c
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 <signal.h>
39
40 #include "asterisk/lock.h"
41 #include "asterisk/file.h"
42 #include "asterisk/channel.h"
43 #include "asterisk/frame.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/module.h"
46 #include "asterisk/translate.h"
47 #include "asterisk/app.h"
48 #include "asterisk/format_cache.h"
49
50 #define LOCAL_MPG_123 "/usr/local/bin/mpg123"
51 #define MPG_123 "/usr/bin/mpg123"
52
53 /*** DOCUMENTATION
54         <application name="MP3Player" language="en_US">
55                 <synopsis>
56                         Play an MP3 file or M3U playlist file or stream.
57                 </synopsis>
58                 <syntax>
59                         <parameter name="Location" required="true">
60                                 <para>Location of the file to be played.
61                                 (argument passed to mpg123)</para>
62                         </parameter>
63                 </syntax>
64                 <description>
65                         <para>Executes mpg123 to play the given location, which typically would be a mp3 filename
66                         or m3u playlist filename or a URL. Please read http://en.wikipedia.org/wiki/M3U
67                         to see how M3U playlist file format is like, Example usage would be
68                         exten => 1234,1,MP3Player(/var/lib/asterisk/playlist.m3u)
69                         User can exit by pressing any key on the dialpad, or by hanging up.</para>
70                         <para>This application does not automatically answer and should be preceeded by an
71                         application such as Answer() or Progress().</para>
72                 </description>
73         </application>
74
75  ***/
76 static char *app = "MP3Player";
77
78 static int mp3play(const char *filename, unsigned int sampling_rate, int fd)
79 {
80         int res;
81         char sampling_rate_str[8];
82
83         res = ast_safe_fork(0);
84         if (res < 0)
85                 ast_log(LOG_WARNING, "Fork failed\n");
86         if (res) {
87                 return res;
88         }
89         if (ast_opt_high_priority)
90                 ast_set_priority(0);
91
92         dup2(fd, STDOUT_FILENO);
93         ast_close_fds_above_n(STDERR_FILENO);
94
95         snprintf(sampling_rate_str, 8, "%u", sampling_rate);
96
97         /* Execute mpg123, but buffer if it's a net connection */
98         if (!strncasecmp(filename, "http://", 7) && strstr(filename, ".m3u")) {
99             char buffer_size_str[8];
100             snprintf(buffer_size_str, 8, "%u", (int) 0.5*2*sampling_rate/1000); // 0.5 seconds for a live stream
101                 /* Most commonly installed in /usr/local/bin */
102             execl(LOCAL_MPG_123, "mpg123", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
103                 /* But many places has it in /usr/bin */
104             execl(MPG_123, "mpg123", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
105                 /* As a last-ditch effort, try to use PATH */
106             execlp("mpg123", "mpg123", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
107         }
108         else if (!strncasecmp(filename, "http://", 7)) {
109             char buffer_size_str[8];
110             snprintf(buffer_size_str, 8, "%u", 6*2*sampling_rate/1000); // 6 seconds for a remote MP3 file
111                 /* Most commonly installed in /usr/local/bin */
112             execl(LOCAL_MPG_123, "mpg123", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
113                 /* But many places has it in /usr/bin */
114             execl(MPG_123, "mpg123", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
115                 /* As a last-ditch effort, try to use PATH */
116             execlp("mpg123", "mpg123", "-q", "-s", "-b", buffer_size_str, "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
117         }
118         else if (strstr(filename, ".m3u")) {
119                 /* Most commonly installed in /usr/local/bin */
120             execl(LOCAL_MPG_123, "mpg123", "-q", "-z", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
121                 /* But many places has it in /usr/bin */
122             execl(MPG_123, "mpg123", "-q", "-z", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
123                 /* As a last-ditch effort, try to use PATH */
124             execlp("mpg123", "mpg123", "-q", "-z", "-s",  "-f", "8192", "--mono", "-r", sampling_rate_str, "-@", filename, (char *)NULL);
125         }
126         else {
127                 /* Most commonly installed in /usr/local/bin */
128             execl(MPG_123, "mpg123", "-q", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
129                 /* But many places has it in /usr/bin */
130             execl(LOCAL_MPG_123, "mpg123", "-q", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
131                 /* As a last-ditch effort, try to use PATH */
132             execlp("mpg123", "mpg123", "-q", "-s", "-f", "8192", "--mono", "-r", sampling_rate_str, filename, (char *)NULL);
133         }
134         /* Can't use ast_log since FD's are closed */
135         fprintf(stderr, "Execute of mpg123 failed\n");
136         _exit(0);
137 }
138
139 static int timed_read(int fd, void *data, int datalen, int timeout)
140 {
141         int res;
142         struct pollfd fds[1];
143         fds[0].fd = fd;
144         fds[0].events = POLLIN;
145         res = ast_poll(fds, 1, timeout);
146         if (res < 1) {
147                 ast_log(LOG_NOTICE, "Poll timed out/errored out with %d\n", res);
148                 return -1;
149         }
150         return read(fd, data, datalen);
151
152 }
153
154 static int mp3_exec(struct ast_channel *chan, const char *data)
155 {
156         int res=0;
157         int fds[2];
158         int ms = -1;
159         int pid = -1;
160         RAII_VAR(struct ast_format *, owriteformat, NULL, ao2_cleanup);
161         int timeout = 2000;
162         struct timeval next;
163         struct ast_frame *f;
164         struct myframe {
165                 struct ast_frame f;
166                 char offset[AST_FRIENDLY_OFFSET];
167                 short frdata[160];
168         } myf = {
169                 .f = { 0, },
170         };
171         struct ast_format * native_format;
172         unsigned int sampling_rate;
173         struct ast_format * write_format;
174
175         if (ast_strlen_zero(data)) {
176                 ast_log(LOG_WARNING, "MP3 Playback requires an argument (filename)\n");
177                 return -1;
178         }
179
180         if (pipe(fds)) {
181                 ast_log(LOG_WARNING, "Unable to create pipe\n");
182                 return -1;
183         }
184
185         ast_stopstream(chan);
186
187         native_format = ast_format_cap_get_format(ast_channel_nativeformats(chan), 0);
188         sampling_rate = ast_format_get_sample_rate(native_format);
189         write_format = ast_format_cache_get_slin_by_rate(sampling_rate);
190
191         owriteformat = ao2_bump(ast_channel_writeformat(chan));
192         res = ast_set_write_format(chan, write_format);
193         if (res < 0) {
194                 ast_log(LOG_WARNING, "Unable to set write format to signed linear\n");
195                 return -1;
196         }
197
198         myf.f.frametype = AST_FRAME_VOICE;
199         myf.f.subclass.format = write_format;
200         myf.f.mallocd = 0;
201         myf.f.offset = AST_FRIENDLY_OFFSET;
202         myf.f.src = __PRETTY_FUNCTION__;
203         myf.f.delivery.tv_sec = 0;
204         myf.f.delivery.tv_usec = 0;
205         myf.f.data.ptr = myf.frdata;
206
207         res = mp3play(data, sampling_rate, fds[1]);
208         if (!strncasecmp(data, "http://", 7)) {
209                 timeout = 10000;
210         }
211         /* Wait 1000 ms first */
212         next = ast_tvnow();
213         next.tv_sec += 1;
214         if (res >= 0) {
215                 pid = res;
216                 /* Order is important -- there's almost always going to be mp3...  we want to prioritize the
217                    user */
218                 for (;;) {
219                         ms = ast_tvdiff_ms(next, ast_tvnow());
220                         if (ms <= 0) {
221                                 res = timed_read(fds[0], myf.frdata, sizeof(myf.frdata), timeout);
222                                 if (res > 0) {
223                                         myf.f.datalen = res;
224                                         myf.f.samples = res / 2;
225                                         if (ast_write(chan, &myf.f) < 0) {
226                                                 res = -1;
227                                                 break;
228                                         }
229                                 } else {
230                                         ast_debug(1, "No more mp3\n");
231                                         res = 0;
232                                         break;
233                                 }
234                                 next = ast_tvadd(next, ast_samp2tv(myf.f.samples, sampling_rate));
235                         } else {
236                                 ms = ast_waitfor(chan, ms);
237                                 if (ms < 0) {
238                                         ast_debug(1, "Hangup detected\n");
239                                         res = -1;
240                                         break;
241                                 }
242                                 if (ms) {
243                                         f = ast_read(chan);
244                                         if (!f) {
245                                                 ast_debug(1, "Null frame == hangup() detected\n");
246                                                 res = -1;
247                                                 break;
248                                         }
249                                         if (f->frametype == AST_FRAME_DTMF) {
250                                                 ast_debug(1, "User pressed a key\n");
251                                                 ast_frfree(f);
252                                                 res = 0;
253                                                 break;
254                                         }
255                                         ast_frfree(f);
256                                 }
257                         }
258                 }
259         }
260         close(fds[0]);
261         close(fds[1]);
262
263         if (pid > -1)
264                 kill(pid, SIGKILL);
265         if (!res && owriteformat)
266                 ast_set_write_format(chan, owriteformat);
267
268         ast_frfree(&myf.f);
269
270         return res;
271 }
272
273 static int unload_module(void)
274 {
275         return ast_unregister_application(app);
276 }
277
278 static int load_module(void)
279 {
280         return ast_register_application_xml(app, mp3_exec);
281 }
282
283 AST_MODULE_INFO_STANDARD_EXTENDED(ASTERISK_GPL_KEY, "Silly MP3 Application");