replace memory allocation function calls with pa_xXXXX()
[profile/ivi/pulseaudio.git] / src / utils / pacat.c
1 /* $Id$ */
2
3 /***
4   This file is part of polypaudio.
5  
6   polypaudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as published
8   by the Free Software Foundation; either version 2 of the License,
9   or (at your option) any later version.
10  
11   polypaudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   General Public License for more details.
15  
16   You should have received a copy of the GNU Lesser General Public License
17   along with polypaudio; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <signal.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <assert.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <getopt.h>
34 #include <fcntl.h>
35
36 #include <polyp/polypaudio.h>
37 #include <polypcore/util.h>
38
39 #define TIME_EVENT_USEC 50000
40
41 #if PA_API_VERSION != 9
42 #error Invalid Polypaudio API version
43 #endif
44
45 static enum { RECORD, PLAYBACK } mode = PLAYBACK;
46
47 static pa_context *context = NULL;
48 static pa_stream *stream = NULL;
49 static pa_mainloop_api *mainloop_api = NULL;
50
51 static void *buffer = NULL;
52 static size_t buffer_length = 0, buffer_index = 0;
53
54 static pa_io_event* stdio_event = NULL;
55
56 static char *stream_name = NULL, *client_name = NULL, *device = NULL;
57
58 static int verbose = 0;
59 static pa_volume_t volume = PA_VOLUME_NORM;
60
61 static pa_sample_spec sample_spec = {
62     .format = PA_SAMPLE_S16LE,
63     .rate = 44100,
64     .channels = 2
65 };
66
67 static pa_channel_map channel_map;
68 static int channel_map_set = 0;
69
70 /* A shortcut for terminating the application */
71 static void quit(int ret) {
72     assert(mainloop_api);
73     mainloop_api->quit(mainloop_api, ret);
74 }
75
76 /* Write some data to the stream */
77 static void do_stream_write(size_t length) {
78     size_t l;
79     assert(length);
80
81     if (!buffer || !buffer_length)
82         return;
83     
84     l = length;
85     if (l > buffer_length)
86         l = buffer_length;
87     
88     if (pa_stream_write(stream, (uint8_t*) buffer + buffer_index, l, NULL, 0, PA_SEEK_RELATIVE) < 0) {
89         fprintf(stderr, "pa_stream_write() failed: %s\n", pa_strerror(pa_context_errno(context)));
90         quit(1);
91         return;
92     }
93     
94     buffer_length -= l;
95     buffer_index += l;
96     
97     if (!buffer_length) {
98         pa_xfree(buffer);
99         buffer = NULL;
100         buffer_index = buffer_length = 0;
101     }
102 }
103
104 /* This is called whenever new data may be written to the stream */
105 static void stream_write_callback(pa_stream *s, size_t length, void *userdata) {
106     assert(s && length);
107
108     if (stdio_event)
109         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_INPUT);
110
111     if (!buffer)
112         return;
113
114     do_stream_write(length);
115 }
116
117 /* This is called whenever new data may is available */
118 static void stream_read_callback(pa_stream *s, size_t length, void *userdata) {
119     const void *data;
120     assert(s && length);
121
122     if (stdio_event)
123         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_OUTPUT);
124
125     if (pa_stream_peek(s, &data, &length) < 0) {
126         fprintf(stderr, "pa_stream_peek() failed: %s\n", pa_strerror(pa_context_errno(context)));
127         quit(1);
128         return;
129     }
130     
131     assert(data && length);
132
133     if (buffer) {
134         fprintf(stderr, "Buffer overrun, dropping incoming data\n");
135         if (pa_stream_drop(s) < 0) {
136             fprintf(stderr, "pa_stream_drop() failed: %s\n", pa_strerror(pa_context_errno(context)));
137             quit(1);
138         }
139         return;
140     }
141
142     buffer = pa_xmalloc(buffer_length = length);
143     memcpy(buffer, data, length);
144     buffer_index = 0;
145     pa_stream_drop(s);
146 }
147
148 /* This routine is called whenever the stream state changes */
149 static void stream_state_callback(pa_stream *s, void *userdata) {
150     assert(s);
151
152     switch (pa_stream_get_state(s)) {
153         case PA_STREAM_CREATING:
154         case PA_STREAM_TERMINATED:
155             break;
156
157         case PA_STREAM_READY:
158             if (verbose)
159                 fprintf(stderr, "Stream successfully created.\n");
160             break;
161             
162         case PA_STREAM_FAILED:
163         default:
164             fprintf(stderr, "Stream error: %s\n", pa_strerror(pa_context_errno(pa_stream_get_context(s))));
165             quit(1);
166     }
167 }
168
169 /* This is called whenever the context status changes */
170 static void context_state_callback(pa_context *c, void *userdata) {
171     assert(c);
172
173     switch (pa_context_get_state(c)) {
174         case PA_CONTEXT_CONNECTING:
175         case PA_CONTEXT_AUTHORIZING:
176         case PA_CONTEXT_SETTING_NAME:
177             break;
178         
179         case PA_CONTEXT_READY: {
180             int r;
181             
182             assert(c && !stream);
183
184             if (verbose)
185                 fprintf(stderr, "Connection established.\n");
186
187             if (!(stream = pa_stream_new(c, stream_name, &sample_spec, channel_map_set ? &channel_map : NULL))) {
188                 fprintf(stderr, "pa_stream_new() failed: %s\n", pa_strerror(pa_context_errno(c)));
189                 goto fail;
190             }
191
192             pa_stream_set_state_callback(stream, stream_state_callback, NULL);
193             pa_stream_set_write_callback(stream, stream_write_callback, NULL);
194             pa_stream_set_read_callback(stream, stream_read_callback, NULL);
195
196             if (mode == PLAYBACK) {
197                 pa_cvolume cv;
198                 if ((r = pa_stream_connect_playback(stream, device, NULL, 0, pa_cvolume_set(&cv, sample_spec.channels, volume), NULL)) < 0) {
199                     fprintf(stderr, "pa_stream_connect_playback() failed: %s\n", pa_strerror(pa_context_errno(c)));
200                     goto fail;
201                 }
202                     
203             } else {
204                 if ((r = pa_stream_connect_record(stream, device, NULL, 0)) < 0) {
205                     fprintf(stderr, "pa_stream_connect_record() failed: %s\n", pa_strerror(pa_context_errno(c)));
206                     goto fail;
207                 }
208             }
209                 
210             break;
211         }
212             
213         case PA_CONTEXT_TERMINATED:
214             quit(0);
215             break;
216
217         case PA_CONTEXT_FAILED:
218         default:
219             fprintf(stderr, "Connection failure: %s\n", pa_strerror(pa_context_errno(c)));
220             goto fail;
221     }
222
223     return;
224     
225 fail:
226     quit(1);
227     
228 }
229
230 /* Connection draining complete */
231 static void context_drain_complete(pa_context*c, void *userdata) {
232     pa_context_disconnect(c);
233 }
234
235 /* Stream draining complete */
236 static void stream_drain_complete(pa_stream*s, int success, void *userdata) {
237     pa_operation *o;
238
239     if (!success) {
240         fprintf(stderr, "Failed to drain stream: %s\n", pa_strerror(pa_context_errno(context)));
241         quit(1);
242     }
243     
244     if (verbose)    
245         fprintf(stderr, "Playback stream drained.\n");
246
247     pa_stream_disconnect(stream);
248     pa_stream_unref(stream);
249     stream = NULL;
250     
251     if (!(o = pa_context_drain(context, context_drain_complete, NULL)))
252         pa_context_disconnect(context);
253     else {
254         if (verbose)
255             fprintf(stderr, "Draining connection to server.\n");
256     }
257 }
258
259 /* New data on STDIN **/
260 static void stdin_callback(pa_mainloop_api*a, pa_io_event *e, int fd, pa_io_event_flags_t f, void *userdata) {
261     size_t l, w = 0;
262     ssize_t r;
263     assert(a == mainloop_api && e && stdio_event == e);
264
265     if (buffer) {
266         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_NULL);
267         return;
268     }
269
270     if (!stream || pa_stream_get_state(stream) != PA_STREAM_READY || !(l = w = pa_stream_writable_size(stream)))
271         l = 4096;
272     
273     buffer = pa_xmalloc(l);
274
275     if ((r = read(fd, buffer, l)) <= 0) {
276         if (r == 0) {
277             pa_operation *o;
278             
279             if (verbose)
280                 fprintf(stderr, "Got EOF.\n");
281             
282             if (!(o = pa_stream_drain(stream, stream_drain_complete, NULL))) {
283                 fprintf(stderr, "pa_stream_drain(): %s\n", pa_strerror(pa_context_errno(context)));
284                 quit(1);
285                 return;
286             }
287
288             pa_operation_unref(o);
289         } else {
290             fprintf(stderr, "read() failed: %s\n", strerror(errno));
291             quit(1);
292         }
293
294         mainloop_api->io_free(stdio_event);
295         stdio_event = NULL;
296         return;
297     }
298
299     buffer_length = r;
300     buffer_index = 0;
301
302     if (w)
303         do_stream_write(w);
304 }
305
306 /* Some data may be written to STDOUT */
307 static void stdout_callback(pa_mainloop_api*a, pa_io_event *e, int fd, pa_io_event_flags_t f, void *userdata) {
308     ssize_t r;
309     assert(a == mainloop_api && e && stdio_event == e);
310
311     if (!buffer) {
312         mainloop_api->io_enable(stdio_event, PA_IO_EVENT_NULL);
313         return;
314     }
315
316     assert(buffer_length);
317     
318     if ((r = write(fd, (uint8_t*) buffer+buffer_index, buffer_length)) <= 0) {
319         fprintf(stderr, "write() failed: %s\n", strerror(errno));
320         quit(1);
321
322         mainloop_api->io_free(stdio_event);
323         stdio_event = NULL;
324         return;
325     }
326
327     buffer_length -= r;
328     buffer_index += r;
329
330     if (!buffer_length) {
331         pa_xfree(buffer);
332         buffer = NULL;
333         buffer_length = buffer_index = 0;
334     }
335 }
336
337 /* UNIX signal to quit recieved */
338 static void exit_signal_callback(pa_mainloop_api*m, pa_signal_event *e, int sig, void *userdata) {
339     if (verbose)
340         fprintf(stderr, "Got signal, exiting.\n");
341     quit(0);
342 }
343
344 /* Show the current latency */
345 static void stream_update_timing_callback(pa_stream *s, int success, void *userdata) {
346     pa_usec_t latency, usec;
347     int negative = 0;
348     
349     assert(s);
350
351     if (!success ||
352         pa_stream_get_time(s, &usec) < 0 ||
353         pa_stream_get_latency(s, &latency, &negative) < 0) {
354         fprintf(stderr, "Failed to get latency: %s\n", pa_strerror(pa_context_errno(context)));
355         quit(1);
356         return;
357     }
358
359     fprintf(stderr, "Time: %0.3f sec; Latency: %0.0f usec.  \r",
360             (float) usec / 1000000,
361             (float) latency * (negative?-1:1));
362 }
363
364 /* Someone requested that the latency is shown */
365 static void sigusr1_signal_callback(pa_mainloop_api*m, pa_signal_event *e, int sig, void *userdata) {
366
367     if (!stream)
368         return;
369     
370     pa_operation_unref(pa_stream_update_timing_info(stream, stream_update_timing_callback, NULL));
371 }
372
373 static void time_event_callback(pa_mainloop_api*m, pa_time_event *e, const struct timeval *tv, void *userdata) {
374     struct timeval next;
375     
376     if (stream && pa_stream_get_state(stream) == PA_STREAM_READY) {
377         pa_operation *o;
378         if (!(o = pa_stream_update_timing_info(stream, stream_update_timing_callback, NULL)))
379             fprintf(stderr, "pa_stream_update_timing_info() failed: %s\n", pa_strerror(pa_context_errno(context)));
380         else
381             pa_operation_unref(o);
382     }
383
384     pa_gettimeofday(&next);
385     pa_timeval_add(&next, TIME_EVENT_USEC);
386
387     m->time_restart(e, &next);
388 }
389
390 static void help(const char *argv0) {
391
392     printf("%s [options]\n\n"
393            "  -h, --help                            Show this help\n"
394            "      --version                         Show version\n\n"
395            "  -r, --record                          Create a connection for recording\n"
396            "  -p, --playback                        Create a connection for playback\n\n"
397            "  -v, --verbose                         Enable verbose operations\n\n"
398            "  -s, --server=SERVER                   The name of the server to connect to\n"
399            "  -d, --device=DEVICE                   The name of the sink/source to connect to\n"
400            "  -n, --client-name=NAME                How to call this client on the server\n"
401            "      --stream-name=NAME                How to call this stream on the server\n"
402            "      --volume=VOLUME                   Specify the initial (linear) volume in range 0...65536\n"
403            "      --rate=SAMPLERATE                 The sample rate in Hz (defaults to 44100)\n"
404            "      --format=SAMPLEFORMAT             The sample type, one of s16le, s16be, u8, float32le,\n"
405            "                                        float32be, ulaw, alaw (defaults to s16ne)\n"
406            "      --channels=CHANNELS               The number of channels, 1 for mono, 2 for stereo\n"
407            "                                        (defaults to 2)\n"
408            "      --channel-map=CHANNELMAP          Channel map to use instead of the default\n",
409            argv0);
410 }
411
412 enum {
413     ARG_VERSION = 256,
414     ARG_STREAM_NAME,
415     ARG_VOLUME,
416     ARG_SAMPLERATE,
417     ARG_SAMPLEFORMAT,
418     ARG_CHANNELS,
419     ARG_CHANNELMAP,
420 };
421
422 int main(int argc, char *argv[]) {
423     pa_mainloop* m = NULL;
424     int ret = 1, r, c;
425     char *bn, *server = NULL;
426     pa_time_event *time_event = NULL;
427
428     static const struct option long_options[] = {
429         {"record",      0, NULL, 'r'},
430         {"playback",    0, NULL, 'p'},
431         {"device",      1, NULL, 'd'},
432         {"server",      1, NULL, 's'},
433         {"client-name", 1, NULL, 'n'},
434         {"stream-name", 1, NULL, ARG_STREAM_NAME},
435         {"version",     0, NULL, ARG_VERSION},
436         {"help",        0, NULL, 'h'},
437         {"verbose",     0, NULL, 'v'},
438         {"volume",      1, NULL, ARG_VOLUME},
439         {"rate",        1, NULL, ARG_SAMPLERATE},
440         {"format",      1, NULL, ARG_SAMPLEFORMAT},
441         {"channels",    1, NULL, ARG_CHANNELS},
442         {"channel-map", 1, NULL, ARG_CHANNELMAP},
443         {NULL,          0, NULL, 0}
444     };
445
446     if (!(bn = strrchr(argv[0], '/')))
447         bn = argv[0];
448     else
449         bn++;
450
451     if (strstr(bn, "rec") || strstr(bn, "mon"))
452         mode = RECORD;
453     else if (strstr(bn, "cat") || strstr(bn, "play"))
454         mode = PLAYBACK;
455
456     while ((c = getopt_long(argc, argv, "rpd:s:n:hv", long_options, NULL)) != -1) {
457
458         switch (c) {
459             case 'h' :
460                 help(bn);
461                 ret = 0;
462                 goto quit;
463                 
464             case ARG_VERSION:
465                 printf("pacat "PACKAGE_VERSION"\nCompiled with libpolyp %s\nLinked with libpolyp %s\n", pa_get_headers_version(), pa_get_library_version());
466                 ret = 0;
467                 goto quit;
468
469             case 'r':
470                 mode = RECORD;
471                 break;
472
473             case 'p':
474                 mode = PLAYBACK;
475                 break;
476
477             case 'd':
478                 pa_xfree(device);
479                 device = pa_xstrdup(optarg);
480                 break;
481
482             case 's':
483                 pa_xfree(server);
484                 server = pa_xstrdup(optarg);
485                 break;
486
487             case 'n':
488                 pa_xfree(client_name);
489                 client_name = pa_xstrdup(optarg);
490                 break;
491
492             case ARG_STREAM_NAME:
493                 pa_xfree(stream_name);
494                 stream_name = pa_xstrdup(optarg);
495                 break;
496
497             case 'v':
498                 verbose = 1;
499                 break;
500
501             case ARG_VOLUME: {
502                 int v = atoi(optarg);
503                 volume = v < 0 ? 0 : v;
504                 break;
505             }
506
507             case ARG_CHANNELS: 
508                 sample_spec.channels = atoi(optarg);
509                 break;
510
511             case ARG_SAMPLEFORMAT:
512                 sample_spec.format = pa_parse_sample_format(optarg);
513                 break;
514
515             case ARG_SAMPLERATE:
516                 sample_spec.rate = atoi(optarg);
517                 break;
518
519             case ARG_CHANNELMAP:
520                 if (!pa_channel_map_parse(&channel_map, optarg)) {
521                     fprintf(stderr, "Invalid channel map\n");
522                     goto quit;
523                 }
524
525                 channel_map_set = 1;
526                 break;
527                 
528             default:
529                 goto quit;
530         }
531     }
532
533     if (!pa_sample_spec_valid(&sample_spec)) {
534         fprintf(stderr, "Invalid sample specification\n");
535         goto quit;
536     }
537
538     if (channel_map_set && channel_map.channels != sample_spec.channels) {
539         fprintf(stderr, "Channel map doesn't match sample specification\n");
540         goto quit;
541     }
542     
543     if (verbose) {
544         char t[PA_SAMPLE_SPEC_SNPRINT_MAX];
545         pa_sample_spec_snprint(t, sizeof(t), &sample_spec);
546         fprintf(stderr, "Opening a %s stream with sample specification '%s'.\n", mode == RECORD ? "recording" : "playback", t);
547     }
548
549     if (!(optind >= argc)) {
550         if (optind+1 == argc) {
551             int fd;
552             
553             if ((fd = open(argv[optind], mode == PLAYBACK ? O_RDONLY : O_WRONLY|O_TRUNC|O_CREAT, 0666)) < 0) {
554                 fprintf(stderr, "open(): %s\n", strerror(errno));
555                 goto quit;
556             }
557             
558             if (dup2(fd, mode == PLAYBACK ? 0 : 1) < 0) {
559                 fprintf(stderr, "dup2(): %s\n", strerror(errno));
560                 goto quit;
561             }
562             
563             close(fd);
564
565             if (!stream_name)
566                 stream_name = pa_xstrdup(argv[optind]);
567             
568         } else {
569             fprintf(stderr, "Too many arguments.\n");
570             goto quit;
571         }
572     }
573
574     if (!client_name)
575         client_name = pa_xstrdup(bn);
576
577     if (!stream_name)
578         stream_name = pa_xstrdup(client_name);
579
580     /* Set up a new main loop */
581     if (!(m = pa_mainloop_new())) {
582         fprintf(stderr, "pa_mainloop_new() failed.\n");
583         goto quit;
584     }
585
586     mainloop_api = pa_mainloop_get_api(m);
587
588     r = pa_signal_init(mainloop_api);
589     assert(r == 0);
590     pa_signal_new(SIGINT, exit_signal_callback, NULL);
591     pa_signal_new(SIGTERM, exit_signal_callback, NULL);
592 #ifdef SIGUSR1
593     pa_signal_new(SIGUSR1, sigusr1_signal_callback, NULL);
594 #endif
595 #ifdef SIGPIPE
596     signal(SIGPIPE, SIG_IGN);
597 #endif
598     
599     if (!(stdio_event = mainloop_api->io_new(mainloop_api,
600                                              mode == PLAYBACK ? STDIN_FILENO : STDOUT_FILENO,
601                                              mode == PLAYBACK ? PA_IO_EVENT_INPUT : PA_IO_EVENT_OUTPUT,
602                                              mode == PLAYBACK ? stdin_callback : stdout_callback, NULL))) {
603         fprintf(stderr, "io_new() failed.\n");
604         goto quit;
605     }
606
607     /* Create a new connection context */
608     if (!(context = pa_context_new(mainloop_api, client_name))) {
609         fprintf(stderr, "pa_context_new() failed.\n");
610         goto quit;
611     }
612
613     pa_context_set_state_callback(context, context_state_callback, NULL);
614
615     /* Connect the context */
616     pa_context_connect(context, server, 0, NULL);
617
618     if (verbose) {
619         struct timeval tv;
620
621         pa_gettimeofday(&tv);
622         pa_timeval_add(&tv, TIME_EVENT_USEC);
623         
624         if (!(time_event = mainloop_api->time_new(mainloop_api, &tv, time_event_callback, NULL))) {
625             fprintf(stderr, "time_new() failed.\n");
626             goto quit;
627         }
628     }
629
630     /* Run the main loop */
631     if (pa_mainloop_run(m, &ret) < 0) {
632         fprintf(stderr, "pa_mainloop_run() failed.\n");
633         goto quit;
634     }
635     
636 quit:
637     if (stream)
638         pa_stream_unref(stream);
639
640     if (context)
641         pa_context_unref(context);
642
643     if (stdio_event) {
644         assert(mainloop_api);
645         mainloop_api->io_free(stdio_event);
646     }
647
648     if (time_event) {
649         assert(mainloop_api);
650         mainloop_api->time_free(time_event);
651     }
652     
653     if (m) {
654         pa_signal_done();
655         pa_mainloop_free(m);
656     }
657
658     pa_xfree(buffer);
659
660     pa_xfree(server);
661     pa_xfree(device);
662     pa_xfree(client_name);
663     pa_xfree(stream_name);
664     
665     return ret;
666 }