oss: Avoid sound artefacts on some setups.
[paraslash.git] / play.c
1 /*
2 * Copyright (C) 2012-2014 Andre Noll <maan@tuebingen.mpg.de>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file play.c Paraslash's standalone player. */
8
9 #include <regex.h>
10 #include <fnmatch.h>
11 #include <signal.h>
12
13 #include "para.h"
14 #include "list.h"
15 #include "play.cmdline.h"
16 #include "filter.cmdline.h"
17 #include "error.h"
18 #include "ggo.h"
19 #include "buffer_tree.h"
20 #include "version.h"
21 #include "string.h"
22 #include "sched.h"
23 #include "filter.h"
24 #include "afh.h"
25 #include "recv.h"
26 #include "write.h"
27 #include "write_common.h"
28 #include "fd.h"
29
30 /**
31 * Besides playback tasks which correspond to the receiver/filter/writer nodes,
32 * para_play creates two further tasks: The play task and the i9e task. It is
33 * important whether a function can be called in the context of para_play or
34 * i9e or both. As a rule, all command handlers are called only in i9e context via
35 * the line handler (input mode) or the key handler (command mode) below.
36 *
37 * Playlist handling is done exclusively in play context.
38 */
39
40 /**
41 * Describes a request to change the state of para_play.
42 *
43 * There is only one variable of this type: \a rq of the global play task
44 * structure. Command handlers only set this variable and the post_select()
45 * function of the play task investigates its value during each iteration of
46 * the scheduler run and performs the actual work.
47 */
48 enum state_change_request_type {
49 /** Everybody is happy. */
50 CRT_NONE,
51 /** Stream must be repositioned (com_jmp(), com_ff()). */
52 CRT_REPOS,
53 /** New file should be loaded (com_next()). */
54 CRT_FILE_CHANGE,
55 /** Someone wants us for dead (com_quit()). */
56 CRT_TERM_RQ
57 };
58
59 struct play_task {
60 struct task *task;
61 /* A bit array of invalid files (those will be skipped). */
62 bool *invalid;
63 /* The file which is currently open. */
64 unsigned current_file;
65 /* When to update the status again. */
66 struct timeval next_update;
67
68 /* Root of the buffer tree for command and status output. */
69 struct btr_node *btrn;
70
71 /* The decoding machinery. */
72 struct receiver_node rn;
73 struct filter_node fn;
74 struct writer_node wn;
75
76 /* See comment to enum state_change_request_type above */
77 enum state_change_request_type rq;
78 /* only relevant if rq == CRT_FILE_CHANGE */
79 unsigned next_file;
80 /*
81 bg: read lines at prompt, fg: display status and wait
82 for keystroke.
83 */
84 bool background;
85
86 /* We have the *intention* to play. Set by com_play(). */
87 bool playing;
88
89 /* as returned by afh_recv->open() */
90 int audio_format_num;
91
92 /* retrieved via the btr exec mechanism */
93 long unsigned start_chunk;
94 long unsigned seconds;
95 long unsigned num_chunks;
96 char *afhi_txt;
97 };
98
99 /** Initialize the array of errors for para_play. */
100 INIT_PLAY_ERRLISTS;
101
102 /* Activate the afh receiver. */
103 extern void afh_recv_init(struct receiver *r);
104 #undef AFH_RECEIVER
105 /** Initialization code for a receiver struct. */
106 #define AFH_RECEIVER {.name = "afh", .init = afh_recv_init},
107 /** This expands to the array of all receivers. */
108 DEFINE_RECEIVER_ARRAY;
109
110 static int loglevel = LL_WARNING;
111
112 /** The log function which writes log messages to stderr. */
113 INIT_STDERR_LOGGING(loglevel);
114
115 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
116
117 /** Iterate over all files in the playlist. */
118 #define FOR_EACH_PLAYLIST_FILE(i) for (i = 0; i < conf.inputs_num; i++)
119 static struct play_args_info conf;
120
121 static struct sched sched = {.max_fileno = 0};
122 static struct play_task play_task;
123 static struct receiver *afh_recv;
124
125 static void check_afh_receiver_or_die(void)
126 {
127 int i;
128
129 FOR_EACH_RECEIVER(i) {
130 struct receiver *r = receivers + i;
131 if (strcmp(r->name, "afh"))
132 continue;
133 afh_recv = r;
134 return;
135 }
136 PARA_EMERG_LOG("fatal: afh receiver not found\n");
137 exit(EXIT_FAILURE);
138 }
139
140 __noreturn static void print_help_and_die(void)
141 {
142 struct ggo_help help = DEFINE_GGO_HELP(play);
143 unsigned flags = conf.detailed_help_given?
144 GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS;
145
146 ggo_print_help(&help, flags);
147 printf("supported audio formats: %s\n", AUDIO_FORMAT_HANDLERS);
148 exit(0);
149 }
150
151 static void parse_config_or_die(int argc, char *argv[])
152 {
153 int i, ret;
154 char *config_file;
155 struct play_cmdline_parser_params params = {
156 .override = 0,
157 .initialize = 1,
158 .check_required = 0,
159 .check_ambiguity = 0,
160 .print_errors = 1
161 };
162
163 play_cmdline_parser_ext(argc, argv, &conf, &params);
164 loglevel = get_loglevel_by_name(conf.loglevel_arg);
165 version_handle_flag("play", conf.version_given);
166 if (conf.help_given || conf.detailed_help_given)
167 print_help_and_die();
168 if (conf.config_file_given)
169 config_file = para_strdup(conf.config_file_arg);
170 else {
171 char *home = para_homedir();
172 config_file = make_message("%s/.paraslash/play.conf", home);
173 free(home);
174 }
175 ret = file_exists(config_file);
176 if (conf.config_file_given && !ret) {
177 PARA_EMERG_LOG("can not read config file %s\n", config_file);
178 goto err;
179 }
180 if (ret) {
181 params.initialize = 0;
182 params.check_required = 1;
183 play_cmdline_parser_config_file(config_file, &conf, &params);
184 loglevel = get_loglevel_by_name(conf.loglevel_arg);
185 }
186 for (i = 0; i < conf.key_map_given; i++) {
187 char *s = strchr(conf.key_map_arg[i] + 1, ':');
188 if (s)
189 continue;
190 PARA_EMERG_LOG("invalid key map arg: %s\n", conf.key_map_arg[i]);
191 goto err;
192 }
193 free(config_file);
194 return;
195 err:
196 free(config_file);
197 exit(EXIT_FAILURE);
198 }
199
200 static char get_playback_state(struct play_task *pt)
201 {
202 switch (pt->rq) {
203 case CRT_NONE: return pt->playing? 'P' : 'U';
204 case CRT_REPOS: return 'R';
205 case CRT_FILE_CHANGE: return 'F';
206 case CRT_TERM_RQ: return 'X';
207 }
208 assert(false);
209 };
210
211 static long unsigned get_play_time(struct play_task *pt)
212 {
213 char state = get_playback_state(pt);
214 long unsigned result;
215
216 if (state != 'P' && state != 'U')
217 return 0;
218 if (pt->num_chunks == 0 || pt->seconds == 0)
219 return 0;
220 /* where the stream started (in seconds) */
221 result = pt->start_chunk * pt->seconds / pt->num_chunks;
222 if (pt->wn.btrn) { /* Add the uptime of the writer node */
223 struct timeval diff = {.tv_sec = 0}, wstime;
224 btr_get_node_start(pt->wn.btrn, &wstime);
225 if (wstime.tv_sec > 0)
226 tv_diff(now, &wstime, &diff);
227 result += diff.tv_sec;
228 }
229 result = PARA_MIN(result, pt->seconds);
230 result = PARA_MAX(result, 0UL);
231 return result;
232 }
233
234 static void wipe_receiver_node(struct play_task *pt)
235 {
236 PARA_NOTICE_LOG("cleaning up receiver node\n");
237 btr_remove_node(&pt->rn.btrn);
238 afh_recv->close(&pt->rn);
239 afh_recv->free_config(pt->rn.conf);
240 memset(&pt->rn, 0, sizeof(struct receiver_node));
241 }
242
243 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
244 static int get_playback_error(struct play_task *pt)
245 {
246 int err;
247
248 if (!pt->wn.task)
249 return 0;
250 err = task_status(pt->wn.task);
251 if (err >= 0)
252 return 0;
253 if (task_status(pt->fn.task) >= 0)
254 return 0;
255 if (task_status(pt->rn.task) >= 0)
256 return 0;
257 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
258 || err == -E_WRITE_COMMON_EOF)
259 return 1;
260 return err;
261 }
262
263 static int eof_cleanup(struct play_task *pt)
264 {
265 struct writer *w = writers + DEFAULT_WRITER;
266 struct filter *decoder = filters + pt->fn.filter_num;
267 int ret;
268
269 ret = get_playback_error(pt);
270 if (ret == 0)
271 return ret;
272 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
273 task_reap(&pt->wn.task);
274 w->close(&pt->wn);
275 btr_remove_node(&pt->wn.btrn);
276 w->free_config(pt->wn.conf);
277 memset(&pt->wn, 0, sizeof(struct writer_node));
278
279 task_reap(&pt->fn.task);
280 decoder->close(&pt->fn);
281 btr_remove_node(&pt->fn.btrn);
282 free(pt->fn.conf);
283 memset(&pt->fn, 0, sizeof(struct filter_node));
284
285 task_reap(&pt->rn.task);
286 btr_remove_node(&pt->rn.btrn);
287 /*
288 * On eof (ret > 0), we do not wipe the receiver node struct until a
289 * new file is loaded because we still need it for jumping around when
290 * paused.
291 */
292 if (ret < 0)
293 wipe_receiver_node(pt);
294 return ret;
295 }
296
297 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
298 {
299 return para_random(100) - 50;
300 }
301
302 static void shuffle(char **base, size_t num)
303 {
304 srandom(time(NULL));
305 qsort(base, num, sizeof(char *), shuffle_compare);
306 }
307
308 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
309 {
310 return btr_new_node(&(struct btr_node_description)
311 EMBRACE(.name = afh_recv->name, .context = rn,
312 .handler = afh_recv->execute));
313 }
314
315 static int open_new_file(struct play_task *pt)
316 {
317 int ret;
318 char *tmp, *path = conf.inputs[pt->next_file], *afh_recv_conf[] =
319 {"play", "-f", path, "-b", "0", NULL};
320
321 PARA_NOTICE_LOG("next file: %s\n", path);
322 wipe_receiver_node(pt);
323 pt->start_chunk = 0;
324 pt->rn.btrn = new_recv_btrn(&pt->rn);
325 pt->rn.conf = afh_recv->parse_config(ARRAY_SIZE(afh_recv_conf) - 1,
326 afh_recv_conf);
327 assert(pt->rn.conf);
328 pt->rn.receiver = afh_recv;
329 ret = afh_recv->open(&pt->rn);
330 if (ret < 0) {
331 PARA_ERROR_LOG("could not open %s: %s\n", path,
332 para_strerror(-ret));
333 goto fail;
334 }
335 pt->audio_format_num = ret;
336 free(pt->afhi_txt);
337 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
338 if (ret < 0)
339 pt->afhi_txt = make_message("[afhi command failed]\n");
340 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
341 if (ret < 0)
342 pt->seconds = 1;
343 else {
344 int32_t x;
345 ret = para_atoi32(tmp, &x);
346 pt->seconds = ret < 0? 1 : x;
347 free(tmp);
348 tmp = NULL;
349 }
350 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
351 if (ret < 0)
352 pt->num_chunks = 1;
353 else {
354 int32_t x;
355 ret = para_atoi32(tmp, &x);
356 pt->num_chunks = ret < 0? 1 : x;
357 free(tmp);
358 tmp = NULL;
359 }
360 return 1;
361 fail:
362 wipe_receiver_node(pt);
363 return ret;
364 }
365
366 static int load_file(struct play_task *pt)
367 {
368 const char *af;
369 char *tmp, buf[20];
370 int ret;
371 struct filter *decoder;
372
373 btr_remove_node(&pt->rn.btrn);
374 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
375 ret = open_new_file(pt);
376 if (ret < 0)
377 return ret;
378 } else {
379 pt->rn.btrn = new_recv_btrn(&pt->rn);
380 sprintf(buf, "repos %lu", pt->start_chunk);
381 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
382 if (ret < 0)
383 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
384 freep(&tmp);
385 }
386 if (!pt->playing)
387 return 0;
388 /* set up decoding filter */
389 af = audio_format_name(pt->audio_format_num);
390 tmp = make_message("%sdec", af);
391 ret = check_filter_arg(tmp, &pt->fn.conf);
392 freep(&tmp);
393 if (ret < 0)
394 goto fail;
395 pt->fn.filter_num = ret;
396 decoder = filters + ret;
397 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
398 EMBRACE(.name = decoder->name, .parent = pt->rn.btrn,
399 .handler = decoder->execute, .context = &pt->fn));
400 decoder->open(&pt->fn);
401
402 /* setup default writer */
403 pt->wn.conf = check_writer_arg_or_die(NULL, &pt->wn.writer_num);
404
405 /* success, register tasks */
406 pt->rn.task = task_register(
407 &(struct task_info) {
408 .name = afh_recv->name,
409 .pre_select = afh_recv->pre_select,
410 .post_select = afh_recv->post_select,
411 .context = &pt->rn
412 }, &sched);
413 sprintf(buf, "%s decoder", af);
414 pt->fn.task = task_register(
415 &(struct task_info) {
416 .name = buf,
417 .pre_select = decoder->pre_select,
418 .post_select = decoder->post_select,
419 .context = &pt->fn
420 }, &sched);
421 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
422 return 1;
423 fail:
424 wipe_receiver_node(pt);
425 return ret;
426 }
427
428 static int next_valid_file(struct play_task *pt)
429 {
430 int i, j = pt->current_file;
431
432 FOR_EACH_PLAYLIST_FILE(i) {
433 j = (j + 1) % conf.inputs_num;
434 if (!pt->invalid[j])
435 return j;
436 }
437 return -E_NO_VALID_FILES;
438 }
439
440 static int load_next_file(struct play_task *pt)
441 {
442 int ret;
443
444 again:
445 if (pt->rq == CRT_NONE) {
446 pt->start_chunk = 0;
447 ret = next_valid_file(pt);
448 if (ret < 0)
449 return ret;
450 pt->next_file = ret;
451 } else if (pt->rq == CRT_REPOS)
452 pt->next_file = pt->current_file;
453 ret = load_file(pt);
454 if (ret < 0) {
455 pt->invalid[pt->next_file] = true;
456 pt->rq = CRT_NONE;
457 goto again;
458 }
459 pt->current_file = pt->next_file;
460 pt->rq = CRT_NONE;
461 return ret;
462 }
463
464 static void kill_stream(struct play_task *pt)
465 {
466 if (pt->wn.task)
467 task_notify(pt->wn.task, E_EOF);
468 }
469
470 #ifdef HAVE_READLINE
471
472 /* only called from com_prev(), nec. only if we have readline */
473 static int previous_valid_file(struct play_task *pt)
474 {
475 int i, j = pt->current_file;
476
477 FOR_EACH_PLAYLIST_FILE(i) {
478 j--;
479 if (j < 0)
480 j = conf.inputs_num - 1;
481 if (!pt->invalid[j])
482 return j;
483 }
484 return -E_NO_VALID_FILES;
485 }
486
487 #include "interactive.h"
488
489 /*
490 * Define the default (internal) key mappings and helper functions to get the
491 * key sequence or the command from a key id, which is what we obtain from
492 * i9e/readline when the key is pressed.
493 *
494 * In some of these helper functions we could return pointers to the constant
495 * arrays defined below. However, for others we can not, so let's better be
496 * consistent and allocate all returned strings on the heap.
497 */
498
499 #define INTERNAL_KEYMAP_ENTRIES \
500 KEYMAP_ENTRY("^", "jmp 0"), \
501 KEYMAP_ENTRY("1", "jmp 10"), \
502 KEYMAP_ENTRY("2", "jmp 21"), \
503 KEYMAP_ENTRY("3", "jmp 32"), \
504 KEYMAP_ENTRY("4", "jmp 43"), \
505 KEYMAP_ENTRY("5", "jmp 54"), \
506 KEYMAP_ENTRY("6", "jmp 65"), \
507 KEYMAP_ENTRY("7", "jmp 76"), \
508 KEYMAP_ENTRY("8", "jmp 87"), \
509 KEYMAP_ENTRY("9", "jmp 98"), \
510 KEYMAP_ENTRY("+", "next"), \
511 KEYMAP_ENTRY("-", "prev"), \
512 KEYMAP_ENTRY(":", "bg"), \
513 KEYMAP_ENTRY("i", "info"), \
514 KEYMAP_ENTRY("l", "ls"), \
515 KEYMAP_ENTRY("s", "play"), \
516 KEYMAP_ENTRY("p", "pause"), \
517 KEYMAP_ENTRY("q", "quit"), \
518 KEYMAP_ENTRY("?", "help"), \
519 KEYMAP_ENTRY("\033[D", "ff -10"), \
520 KEYMAP_ENTRY("\033[C", "ff 10"), \
521 KEYMAP_ENTRY("\033[A", "ff 60"), \
522 KEYMAP_ENTRY("\033[B", "ff -60"), \
523
524 #define KEYMAP_ENTRY(a, b) a
525 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
526 #undef KEYMAP_ENTRY
527 #define KEYMAP_ENTRY(a, b) b
528 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
529 #undef KEYMAP_ENTRY
530 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
531 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + conf.key_map_given)
532 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
533
534 static inline bool is_internal_key(int key)
535 {
536 return key < NUM_INTERNALLY_MAPPED_KEYS;
537 }
538
539 /* for internal keys, the key id is just the array index. */
540 static inline int get_internal_key_map_idx(int key)
541 {
542 assert(is_internal_key(key));
543 return key;
544 }
545
546 /*
547 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
548 * difference is the index to the array of user defined key maps.
549 */
550 static inline int get_user_key_map_idx(int key)
551 {
552 assert(!is_internal_key(key));
553 return key - NUM_INTERNALLY_MAPPED_KEYS;
554 }
555
556 static inline int get_key_map_idx(int key)
557 {
558 return is_internal_key(key)?
559 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
560 }
561
562 static inline char *get_user_key_map_arg(int key)
563 {
564 return conf.key_map_arg[get_user_key_map_idx(key)];
565 }
566
567 static inline char *get_internal_key_map_seq(int key)
568 {
569 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
570 }
571
572 static char *get_user_key_map_seq(int key)
573 {
574 const char *kma = get_user_key_map_arg(key);
575 const char *p = strchr(kma + 1, ':');
576 char *result;
577 int len;
578
579 if (!p)
580 return NULL;
581 len = p - kma;
582 result = para_malloc(len + 1);
583 memcpy(result, kma, len);
584 result[len] = '\0';
585 return result;
586 }
587
588 static char *get_key_map_seq(int key)
589 {
590 return is_internal_key(key)?
591 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
592 }
593
594 static inline char *get_internal_key_map_cmd(int key)
595 {
596 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
597 }
598
599 static char *get_user_key_map_cmd(int key)
600 {
601 const char *kma = get_user_key_map_arg(key);
602 const char *p = strchr(kma + 1, ':');
603
604 if (!p)
605 return NULL;
606 return para_strdup(p + 1);
607 }
608
609 static char *get_key_map_cmd(int key)
610 {
611 return is_internal_key(key)?
612 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
613 }
614
615 static char **get_mapped_keyseqs(void)
616 {
617 char **result;
618 int i;
619
620 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
621 FOR_EACH_MAPPED_KEY(i) {
622 int idx = get_key_map_idx(i);
623 char *seq = get_key_map_seq(i);
624 char *cmd = get_key_map_cmd(i);
625 bool internal = is_internal_key(i);
626 PARA_DEBUG_LOG("%s key sequence #%d: %s -> %s\n",
627 internal? "internal" : "user-defined",
628 idx, seq, cmd);
629 result[i] = seq;
630 free(cmd);
631 }
632 result[i] = NULL;
633 return result;
634 }
635
636 #include "play_completion.h"
637
638
639 /* defines one command of para_play */
640 struct pp_command {
641 const char *name;
642 int (*handler)(struct play_task *, int, char**);
643 const char *description;
644 const char *usage;
645 const char *help;
646 };
647
648 #include "play_command_list.h"
649 static struct pp_command pp_cmds[] = {DEFINE_PLAY_CMD_ARRAY};
650 #define FOR_EACH_COMMAND(c) for (c = 0; pp_cmds[c].name; c++)
651
652 #include "play_completion.h"
653 static struct i9e_completer pp_completers[];
654
655 I9E_DUMMY_COMPLETER(jmp);
656 I9E_DUMMY_COMPLETER(next);
657 I9E_DUMMY_COMPLETER(prev);
658 I9E_DUMMY_COMPLETER(fg);
659 I9E_DUMMY_COMPLETER(bg);
660 I9E_DUMMY_COMPLETER(ls);
661 I9E_DUMMY_COMPLETER(info);
662 I9E_DUMMY_COMPLETER(play);
663 I9E_DUMMY_COMPLETER(pause);
664 I9E_DUMMY_COMPLETER(stop);
665 I9E_DUMMY_COMPLETER(tasks);
666 I9E_DUMMY_COMPLETER(quit);
667 I9E_DUMMY_COMPLETER(ff);
668
669 static void help_completer(struct i9e_completion_info *ci,
670 struct i9e_completion_result *result)
671 {
672 result->matches = i9e_complete_commands(ci->word, pp_completers);
673 }
674
675 static struct i9e_completer pp_completers[] = {PLAY_COMPLETERS {.name = NULL}};
676
677 static void attach_stdout(struct play_task *pt, const char *name)
678 {
679 if (pt->btrn)
680 return;
681 pt->btrn = btr_new_node(&(struct btr_node_description)
682 EMBRACE(.name = name));
683 i9e_attach_to_stdout(pt->btrn);
684 }
685
686 static void detach_stdout(struct play_task *pt)
687 {
688 btr_remove_node(&pt->btrn);
689 }
690
691 static int com_quit(struct play_task *pt, int argc, __a_unused char **argv)
692 {
693 if (argc != 1)
694 return -E_PLAY_SYNTAX;
695 pt->rq = CRT_TERM_RQ;
696 return 0;
697 }
698
699 static int com_help(struct play_task *pt, int argc, char **argv)
700 {
701 int i;
702 char *buf;
703 size_t sz;
704
705 if (argc > 2)
706 return -E_PLAY_SYNTAX;
707 if (argc < 2) {
708 if (pt->background)
709 FOR_EACH_COMMAND(i) {
710 sz = xasprintf(&buf, "%s\t%s\n", pp_cmds[i].name,
711 pp_cmds[i].description);
712 btr_add_output(buf, sz, pt->btrn);
713 }
714 else {
715 FOR_EACH_MAPPED_KEY(i) {
716 bool internal = is_internal_key(i);
717 int idx = get_key_map_idx(i);
718 char *seq = get_key_map_seq(i);
719 char *cmd = get_key_map_cmd(i);
720 sz = xasprintf(&buf,
721 "%s key #%d: %s -> %s\n",
722 internal? "internal" : "user-defined",
723 idx, seq, cmd);
724 btr_add_output(buf, sz, pt->btrn);
725 free(seq);
726 free(cmd);
727 }
728 }
729 return 0;
730 }
731 FOR_EACH_COMMAND(i) {
732 if (strcmp(pp_cmds[i].name, argv[1]))
733 continue;
734 sz = xasprintf(&buf,
735 "NAME\n\t%s -- %s\n"
736 "SYNOPSIS\n\t%s\n"
737 "DESCRIPTION\n%s\n",
738 argv[1],
739 pp_cmds[i].description,
740 pp_cmds[i].usage,
741 pp_cmds[i].help
742 );
743 btr_add_output(buf, sz, pt->btrn);
744 return 0;
745 }
746 return -E_BAD_PLAY_CMD;
747 }
748
749 static int com_info(struct play_task *pt, int argc, __a_unused char **argv)
750 {
751 char *buf;
752 size_t sz;
753 static char dflt[] = "[no information available]";
754
755 if (argc != 1)
756 return -E_PLAY_SYNTAX;
757 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
758 pt->current_file, conf.inputs[pt->current_file]);
759 btr_add_output(buf, sz, pt->btrn);
760 buf = pt->afhi_txt? pt->afhi_txt : dflt;
761 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
762 return 0;
763 }
764
765 static void list_file(struct play_task *pt, int num)
766 {
767 char *buf;
768 size_t sz;
769
770 sz = xasprintf(&buf, "%s %4u %s\n", num == pt->current_file?
771 "*" : " ", num, conf.inputs[num]);
772 btr_add_output(buf, sz, pt->btrn);
773 }
774
775 static int com_tasks(struct play_task *pt, int argc, __a_unused char **argv)
776 {
777 static char state;
778 char *buf;
779 size_t sz;
780
781 if (argc != 1)
782 return -E_PLAY_SYNTAX;
783
784 buf = get_task_list(&sched);
785 btr_add_output(buf, strlen(buf), pt->btrn);
786 state = get_playback_state(pt);
787 sz = xasprintf(&buf, "state: %c\n", state);
788 btr_add_output(buf, sz, pt->btrn);
789 return 0;
790 }
791
792 static int com_ls(struct play_task *pt, int argc, char **argv)
793 {
794 int i, j, ret;
795
796 if (argc == 1) {
797 FOR_EACH_PLAYLIST_FILE(i)
798 list_file(pt, i);
799 return 0;
800 }
801 for (j = 1; j < argc; j++) {
802 FOR_EACH_PLAYLIST_FILE(i) {
803 ret = fnmatch(argv[j], conf.inputs[i], 0);
804 if (ret == 0) /* match */
805 list_file(pt, i);
806 }
807 }
808 return 0;
809 }
810
811 static int com_play(struct play_task *pt, int argc, char **argv)
812 {
813 int32_t x;
814 int ret;
815 char state;
816
817 if (argc > 2)
818 return -E_PLAY_SYNTAX;
819 state = get_playback_state(pt);
820 if (argc == 1) {
821 if (state == 'P')
822 return 0;
823 pt->next_file = pt->current_file;
824 pt->rq = CRT_REPOS;
825 pt->playing = true;
826 return 0;
827 }
828 ret = para_atoi32(argv[1], &x);
829 if (ret < 0)
830 return ret;
831 if (x < 0 || x >= conf.inputs_num)
832 return -ERRNO_TO_PARA_ERROR(EINVAL);
833 kill_stream(pt);
834 pt->next_file = x;
835 pt->rq = CRT_FILE_CHANGE;
836 return 0;
837 }
838
839 static int com_pause(struct play_task *pt, int argc, __a_unused char **argv)
840 {
841 char state;
842 long unsigned seconds, ss;
843
844 if (argc != 1)
845 return -E_PLAY_SYNTAX;
846 state = get_playback_state(pt);
847 pt->playing = false;
848 if (state != 'P')
849 return 0;
850 seconds = get_play_time(pt);
851 pt->playing = false;
852 ss = 0;
853 if (pt->seconds > 0)
854 ss = seconds * pt->num_chunks / pt->seconds + 1;
855 ss = PARA_MAX(ss, 0UL);
856 ss = PARA_MIN(ss, pt->num_chunks);
857 pt->start_chunk = ss;
858 kill_stream(pt);
859 return 0;
860 }
861
862 static int com_prev(struct play_task *pt, int argc, __a_unused char **argv)
863
864 {
865 int ret;
866
867 if (argc != 1)
868 return -E_PLAY_SYNTAX;
869 ret = previous_valid_file(pt);
870 if (ret < 0)
871 return ret;
872 kill_stream(pt);
873 pt->next_file = ret;
874 pt->rq = CRT_FILE_CHANGE;
875 return 0;
876 }
877
878 static int com_next(struct play_task *pt, int argc, __a_unused char **argv)
879 {
880 int ret;
881
882 if (argc != 1)
883 return -E_PLAY_SYNTAX;
884 ret = next_valid_file(pt);
885 if (ret < 0)
886 return ret;
887 kill_stream(pt);
888 pt->next_file = ret;
889 pt->rq = CRT_FILE_CHANGE;
890 return 0;
891 }
892
893 static int com_fg(struct play_task *pt, int argc, __a_unused char **argv)
894 {
895 if (argc != 1)
896 return -E_PLAY_SYNTAX;
897 pt->background = false;
898 return 0;
899 }
900
901 static int com_bg(struct play_task *pt, int argc, __a_unused char **argv)
902 {
903 if (argc != 1)
904 return -E_PLAY_SYNTAX;
905 pt->background = true;
906 return 0;
907 }
908
909 static int com_jmp(struct play_task *pt, int argc, char **argv)
910 {
911 int32_t percent;
912 int ret;
913
914 if (argc != 2)
915 return -E_PLAY_SYNTAX;
916 ret = para_atoi32(argv[1], &percent);
917 if (ret < 0)
918 return ret;
919 if (percent < 0 || percent > 100)
920 return -ERRNO_TO_PARA_ERROR(EINVAL);
921 if (pt->playing && !pt->fn.btrn)
922 return 0;
923 pt->start_chunk = percent * pt->num_chunks / 100;
924 if (!pt->playing)
925 return 0;
926 pt->rq = CRT_REPOS;
927 kill_stream(pt);
928 return 0;
929 }
930
931 static int com_ff(struct play_task *pt, int argc, char **argv)
932 {
933 int32_t seconds;
934 int ret;
935
936 if (argc != 2)
937 return -E_PLAY_SYNTAX;
938 ret = para_atoi32(argv[1], &seconds);
939 if (ret < 0)
940 return ret;
941 if (pt->playing && !pt->fn.btrn)
942 return 0;
943 seconds += get_play_time(pt);
944 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
945 seconds = PARA_MAX(seconds, 0);
946 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
947 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
948 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
949 if (!pt->playing)
950 return 0;
951 pt->rq = CRT_REPOS;
952 kill_stream(pt);
953 return 0;
954 }
955
956 static int run_command(char *line, struct play_task *pt)
957 {
958 int i, ret, argc;
959 char **argv = NULL;
960
961 attach_stdout(pt, __FUNCTION__);
962 ret = create_argv(line, " ", &argv);
963 if (ret < 0) {
964 PARA_ERROR_LOG("parse error: %s\n", para_strerror(-ret));
965 return 0;
966 }
967 if (ret == 0)
968 goto out;
969 argc = ret;
970 FOR_EACH_COMMAND(i) {
971 if (strcmp(pp_cmds[i].name, argv[0]))
972 continue;
973 ret = pp_cmds[i].handler(pt, argc, argv);
974 if (ret < 0)
975 PARA_WARNING_LOG("%s: %s\n", pt->background?
976 "" : argv[0], para_strerror(-ret));
977 ret = 1;
978 goto out;
979 }
980 PARA_WARNING_LOG("invalid command: %s\n", argv[0]);
981 ret = 0;
982 out:
983 free_argv(argv);
984 return ret;
985 }
986
987 static int play_i9e_line_handler(char *line)
988 {
989 return run_command(line, &play_task);
990 }
991
992 static int play_i9e_key_handler(int key)
993 {
994 struct play_task *pt = &play_task;
995 int idx = get_key_map_idx(key);
996 char *seq = get_key_map_seq(key);
997 char *cmd = get_key_map_cmd(key);
998 bool internal = is_internal_key(key);
999
1000 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1001 key, internal? "internal" : "user-defined",
1002 idx, seq, cmd);
1003 run_command(cmd, pt);
1004 free(seq);
1005 free(cmd);
1006 pt->next_update = *now;
1007 return 0;
1008 }
1009
1010 static struct i9e_client_info ici = {
1011 .fds = {0, 1, 2},
1012 .prompt = "para_play> ",
1013 .line_handler = play_i9e_line_handler,
1014 .key_handler = play_i9e_key_handler,
1015 .completers = pp_completers,
1016 };
1017
1018 static void sigint_handler(int sig)
1019 {
1020 play_task.background = true;
1021 i9e_signal_dispatch(sig);
1022 }
1023
1024 /*
1025 * We start with para_log() set to the standard log function which writes to
1026 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1027 * log facility.
1028 */
1029 static void session_open(__a_unused struct play_task *pt)
1030 {
1031 int ret;
1032 char *history_file;
1033 struct sigaction act;
1034
1035 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1036 if (conf.history_file_given)
1037 history_file = para_strdup(conf.history_file_arg);
1038 else {
1039 char *home = para_homedir();
1040 history_file = make_message("%s/.paraslash/play.history",
1041 home);
1042 free(home);
1043 }
1044 ici.history_file = history_file;
1045 ici.loglevel = loglevel;
1046
1047 act.sa_handler = sigint_handler;
1048 sigemptyset(&act.sa_mask);
1049 act.sa_flags = 0;
1050 sigaction(SIGINT, &act, NULL);
1051 act.sa_handler = i9e_signal_dispatch;
1052 sigemptyset(&act.sa_mask);
1053 act.sa_flags = 0;
1054 sigaction(SIGWINCH, &act, NULL);
1055 sched.select_function = i9e_select;
1056
1057 ici.bound_keyseqs = get_mapped_keyseqs();
1058 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1059 EMBRACE(.name = __FUNCTION__));
1060 ret = i9e_open(&ici, &sched);
1061 if (ret < 0)
1062 goto out;
1063 para_log = i9e_log;
1064 return;
1065 out:
1066 free(history_file);
1067 if (ret >= 0)
1068 return;
1069 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1070 exit(EXIT_FAILURE);
1071 }
1072
1073 static void session_update_time_string(struct play_task *pt, char *str, unsigned len)
1074 {
1075 if (pt->background)
1076 return;
1077 if (pt->btrn) {
1078 if (btr_get_output_queue_size(pt->btrn) > 0)
1079 return;
1080 if (btr_get_input_queue_size(pt->btrn) > 0)
1081 return;
1082 }
1083 ie9_print_status_bar(str, len);
1084 }
1085
1086 /*
1087 * If we are about to die we must call i9e_close() to reset the terminal.
1088 * However, i9e_close() must be called in *this* context, i.e. from
1089 * play_task.post_select() rather than from i9e_post_select(), because
1090 * otherwise i9e would access freed memory upon return. So the play task must
1091 * stay alive until the i9e task terminates.
1092 *
1093 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1094 * and reschedule. In the next iteration, i9e->post_select returns an error and
1095 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1096 * are allowed to call i9e_close() and terminate as well.
1097 */
1098 static int session_post_select(__a_unused struct sched *s, struct play_task *pt)
1099 {
1100 int ret;
1101
1102 if (pt->background)
1103 detach_stdout(pt);
1104 else
1105 attach_stdout(pt, __FUNCTION__);
1106 ret = i9e_get_error();
1107 if (ret < 0) {
1108 kill_stream(pt);
1109 i9e_close();
1110 para_log = stderr_log;
1111 free(ici.history_file);
1112 return ret;
1113 }
1114 if (get_playback_state(pt) == 'X')
1115 i9e_signal_dispatch(SIGTERM);
1116 return 0;
1117 }
1118
1119 #else /* HAVE_READLINE */
1120
1121 static int session_post_select(struct sched *s, struct play_task *pt)
1122 {
1123 char c;
1124
1125 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1126 return 0;
1127 if (read(STDIN_FILENO, &c, 1))
1128 do_nothing;
1129 kill_stream(pt);
1130 return 1;
1131 }
1132
1133 static void session_open(__a_unused struct play_task *pt)
1134 {
1135 }
1136
1137 static void session_update_time_string(__a_unused struct play_task *pt,
1138 char *str, __a_unused unsigned len)
1139 {
1140 printf("\r%s ", str);
1141 fflush(stdout);
1142 }
1143 #endif /* HAVE_READLINE */
1144
1145 static void play_pre_select(struct sched *s, void *context)
1146 {
1147 struct play_task *pt = context;
1148 char state;
1149
1150 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1151 state = get_playback_state(pt);
1152 if (state == 'R' || state == 'F' || state == 'X')
1153 return sched_min_delay(s);
1154 sched_request_barrier_or_min_delay(&pt->next_update, s);
1155 }
1156
1157 static unsigned get_time_string(struct play_task *pt, char **result)
1158 {
1159 int seconds, length;
1160 char state = get_playback_state(pt);
1161
1162 /* do not return anything if things are about to change */
1163 if (state != 'P' && state != 'U') {
1164 *result = NULL;
1165 return 0;
1166 }
1167 length = pt->seconds;
1168 if (length == 0)
1169 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1170 seconds = get_play_time(pt);
1171 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1172 pt->current_file,
1173 seconds / 60,
1174 seconds % 60,
1175 (length - seconds) / 60,
1176 (length - seconds) % 60,
1177 length? (seconds * 100 + length / 2) / length : 0,
1178 length / 60,
1179 length % 60,
1180 conf.inputs[pt->current_file]
1181 );
1182 }
1183
1184 static int play_post_select(struct sched *s, void *context)
1185 {
1186 struct play_task *pt = context;
1187 int ret;
1188
1189 ret = eof_cleanup(pt);
1190 if (ret < 0) {
1191 pt->rq = CRT_TERM_RQ;
1192 return 0;
1193 }
1194 ret = session_post_select(s, pt);
1195 if (ret < 0)
1196 goto out;
1197 if (!pt->wn.btrn && !pt->fn.btrn) {
1198 char state = get_playback_state(pt);
1199 if (state == 'P' || state == 'R' || state == 'F') {
1200 PARA_NOTICE_LOG("state: %c\n", state);
1201 ret = load_next_file(pt);
1202 if (ret < 0) {
1203 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1204 pt->rq = CRT_TERM_RQ;
1205 ret = 1;
1206 goto out;
1207 }
1208 pt->next_update = *now;
1209 }
1210 }
1211 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1212 char *str;
1213 unsigned len = get_time_string(pt, &str);
1214 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1215 if (str && len > 0)
1216 session_update_time_string(pt, str, len);
1217 free(str);
1218 tv_add(now, &delay, &pt->next_update);
1219 }
1220 ret = 1;
1221 out:
1222 return ret;
1223 }
1224
1225 /**
1226 * The main function of para_play.
1227 *
1228 * \param argc Standard.
1229 * \param argv Standard.
1230 *
1231 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1232 */
1233 int main(int argc, char *argv[])
1234 {
1235 int ret;
1236 struct play_task *pt = &play_task;
1237
1238 /* needed this early to make help work */
1239 recv_init();
1240 filter_init();
1241 writer_init();
1242
1243 sched.default_timeout.tv_sec = 5;
1244
1245 parse_config_or_die(argc, argv);
1246 if (conf.inputs_num == 0)
1247 print_help_and_die();
1248 check_afh_receiver_or_die();
1249
1250 session_open(pt);
1251 if (conf.randomize_given)
1252 shuffle(conf.inputs, conf.inputs_num);
1253 pt->invalid = para_calloc(sizeof(*pt->invalid) * conf.inputs_num);
1254 pt->rq = CRT_FILE_CHANGE;
1255 pt->current_file = conf.inputs_num - 1;
1256 pt->playing = true;
1257 pt->task = task_register(&(struct task_info){
1258 .name = "play",
1259 .pre_select = play_pre_select,
1260 .post_select = play_post_select,
1261 .context = pt,
1262 }, &sched);
1263 ret = schedule(&sched);
1264 sched_shutdown(&sched);
1265 if (ret < 0)
1266 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1267 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1268 }