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