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