1ab4010160cac7e22988111d361de5e745dcd75c
[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 static struct i9e_completer pp_completers[];
669
670 I9E_DUMMY_COMPLETER(jmp);
671 I9E_DUMMY_COMPLETER(next);
672 I9E_DUMMY_COMPLETER(prev);
673 I9E_DUMMY_COMPLETER(fg);
674 I9E_DUMMY_COMPLETER(bg);
675 I9E_DUMMY_COMPLETER(ls);
676 I9E_DUMMY_COMPLETER(info);
677 I9E_DUMMY_COMPLETER(play);
678 I9E_DUMMY_COMPLETER(pause);
679 I9E_DUMMY_COMPLETER(stop);
680 I9E_DUMMY_COMPLETER(tasks);
681 I9E_DUMMY_COMPLETER(quit);
682 I9E_DUMMY_COMPLETER(ff);
683
684 static void help_completer(struct i9e_completion_info *ci,
685 struct i9e_completion_result *result)
686 {
687 result->matches = i9e_complete_commands(ci->word, pp_completers);
688 }
689
690 I9E_DUMMY_COMPLETER(SUPERCOMMAND_UNAVAILABLE);
691 static struct i9e_completer pp_completers[] = {
692 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
693 .completer = _name ## _completer}
694 LSG_PLAY_CMD_SUBCOMMANDS
695 #undef LSG_PLAY_CMD_CMD
696 {.name = NULL}
697 };
698
699 static void attach_stdout(struct play_task *pt, const char *name)
700 {
701 if (pt->btrn)
702 return;
703 pt->btrn = btr_new_node(&(struct btr_node_description)
704 EMBRACE(.name = name));
705 i9e_attach_to_stdout(pt->btrn);
706 }
707
708 static void detach_stdout(struct play_task *pt)
709 {
710 btr_remove_node(&pt->btrn);
711 }
712
713 static int com_quit(struct play_task *pt,
714 __a_unused struct lls_parse_result *lpr)
715 {
716 pt->rq = CRT_TERM_RQ;
717 return 0;
718 }
719 EXPORT_PLAY_CMD_HANDLER(quit);
720
721 static int com_help(struct play_task *pt, struct lls_parse_result *lpr)
722 {
723 int i, ret;
724 char *buf, *errctx;
725 size_t sz;
726 const struct lls_command *cmd;
727
728 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
729 if (ret < 0) {
730 if (errctx)
731 PARA_ERROR_LOG("%s\n", errctx);
732 free(errctx);
733 return ret;
734 }
735 if (lls_num_inputs(lpr) == 0) {
736 if (pt->background) {
737 for (i = 1; (cmd = lls_cmd(i, play_cmd_suite)); i++) {
738 sz = xasprintf(&buf, "%s\t%s\n",
739 lls_command_name(cmd), lls_purpose(cmd));
740 btr_add_output(buf, sz, pt->btrn);
741 }
742 return 0;
743 }
744 FOR_EACH_MAPPED_KEY(i) {
745 bool internal = is_internal_key(i);
746 int idx = get_key_map_idx(i);
747 char *seq = get_key_map_seq_safe(i);
748 char *kmc = get_key_map_cmd(i);
749 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
750 internal? "internal" : "user-defined",
751 idx, seq, kmc);
752 btr_add_output(buf, sz, pt->btrn);
753 free(seq);
754 free(kmc);
755 }
756 return 0;
757 }
758 ret = lls(lls_lookup_subcmd(lls_input(0, lpr), play_cmd_suite,
759 &errctx));
760 if (ret < 0) {
761 if (errctx)
762 PARA_ERROR_LOG("%s\n", errctx);
763 free(errctx);
764 return ret;
765 }
766 cmd = lls_cmd(ret, play_cmd_suite);
767 buf = lls_long_help(cmd);
768 assert(buf);
769 btr_add_output(buf, strlen(buf), pt->btrn);
770 return 0;
771 }
772 EXPORT_PLAY_CMD_HANDLER(help);
773
774 static int com_info(struct play_task *pt,
775 __a_unused struct lls_parse_result *lpr)
776 {
777 char *buf;
778 size_t sz;
779 static char dflt[] = "[no information available]";
780
781 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
782 pt->current_file, conf.inputs[pt->current_file]);
783 btr_add_output(buf, sz, pt->btrn);
784 buf = pt->afhi_txt? pt->afhi_txt : dflt;
785 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
786 return 0;
787 }
788 EXPORT_PLAY_CMD_HANDLER(info);
789
790 static void list_file(struct play_task *pt, int num)
791 {
792 char *buf;
793 size_t sz;
794
795 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
796 "*" : " ", num, conf.inputs[num]);
797 btr_add_output(buf, sz, pt->btrn);
798 }
799
800 static int com_tasks(struct play_task *pt,
801 __a_unused struct lls_parse_result *lpr)
802 {
803 static char state;
804 char *buf;
805 size_t sz;
806
807 buf = get_task_list(&sched);
808 btr_add_output(buf, strlen(buf), pt->btrn);
809 state = get_playback_state(pt);
810 sz = xasprintf(&buf, "state: %c\n", state);
811 btr_add_output(buf, sz, pt->btrn);
812 return 0;
813 }
814 EXPORT_PLAY_CMD_HANDLER(tasks);
815
816 static int com_ls(struct play_task *pt,
817 __a_unused struct lls_parse_result *lpr)
818 {
819 int i;
820
821 FOR_EACH_PLAYLIST_FILE(i)
822 list_file(pt, i);
823 return 0;
824 }
825 EXPORT_PLAY_CMD_HANDLER(ls);
826
827 static int com_play(struct play_task *pt, struct lls_parse_result *lpr)
828 {
829 int32_t x;
830 int ret;
831 char state, *errctx;
832
833 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
834 if (ret < 0) {
835 if (errctx)
836 PARA_ERROR_LOG("%s\n", errctx);
837 free(errctx);
838 return ret;
839 }
840 state = get_playback_state(pt);
841 if (lls_num_inputs(lpr) == 0) {
842 if (state == 'P')
843 return 0;
844 pt->next_file = pt->current_file;
845 pt->rq = CRT_REPOS;
846 pt->playing = true;
847 return 0;
848 }
849 ret = para_atoi32(lls_input(0, lpr), &x);
850 if (ret < 0)
851 return ret;
852 if (x < 0 || x >= conf.inputs_num)
853 return -ERRNO_TO_PARA_ERROR(EINVAL);
854 kill_stream(pt);
855 pt->next_file = x;
856 pt->rq = CRT_FILE_CHANGE;
857 return 0;
858 }
859 EXPORT_PLAY_CMD_HANDLER(play);
860
861 static int com_pause(struct play_task *pt,
862 __a_unused struct lls_parse_result *lpr)
863 {
864 char state;
865 long unsigned seconds, ss;
866
867 state = get_playback_state(pt);
868 pt->playing = false;
869 if (state != 'P')
870 return 0;
871 seconds = get_play_time(pt);
872 pt->playing = false;
873 ss = 0;
874 if (pt->seconds > 0)
875 ss = seconds * pt->num_chunks / pt->seconds + 1;
876 ss = PARA_MAX(ss, 0UL);
877 ss = PARA_MIN(ss, pt->num_chunks);
878 pt->start_chunk = ss;
879 kill_stream(pt);
880 return 0;
881 }
882 EXPORT_PLAY_CMD_HANDLER(pause);
883
884 static int com_prev(struct play_task *pt,
885 __a_unused struct lls_parse_result *lpr)
886 {
887 int ret;
888
889 ret = previous_valid_file(pt);
890 if (ret < 0)
891 return ret;
892 kill_stream(pt);
893 pt->next_file = ret;
894 pt->rq = CRT_FILE_CHANGE;
895 pt->start_chunk = 0;
896 return 0;
897 }
898 EXPORT_PLAY_CMD_HANDLER(prev);
899
900 static int com_next(struct play_task *pt,
901 __a_unused struct lls_parse_result *lpr)
902 {
903 int ret;
904
905 ret = next_valid_file(pt);
906 if (ret < 0)
907 return ret;
908 kill_stream(pt);
909 pt->next_file = ret;
910 pt->rq = CRT_FILE_CHANGE;
911 pt->start_chunk = 0;
912 return 0;
913 }
914 EXPORT_PLAY_CMD_HANDLER(next);
915
916 static int com_fg(struct play_task *pt,
917 __a_unused struct lls_parse_result *lpr)
918 {
919 pt->background = false;
920 return 0;
921 }
922 EXPORT_PLAY_CMD_HANDLER(fg);
923
924 static int com_bg(struct play_task *pt,
925 __a_unused struct lls_parse_result *lpr)
926 {
927 pt->background = true;
928 return 0;
929 }
930 EXPORT_PLAY_CMD_HANDLER(bg);
931
932 static int com_jmp(struct play_task *pt, struct lls_parse_result *lpr)
933 {
934 int32_t percent;
935 int ret;
936 char *errctx;
937
938 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
939 if (ret < 0) {
940 if (errctx)
941 PARA_ERROR_LOG("%s\n", errctx);
942 free(errctx);
943 return ret;
944 }
945 ret = para_atoi32(lls_input(0, lpr), &percent);
946 if (ret < 0)
947 return ret;
948 if (percent < 0 || percent > 100)
949 return -ERRNO_TO_PARA_ERROR(EINVAL);
950 if (percent == 100)
951 return com_next(pt, NULL);
952 if (pt->playing && !pt->fn.btrn)
953 return 0;
954 pt->start_chunk = percent * pt->num_chunks / 100;
955 if (!pt->playing)
956 return 0;
957 pt->rq = CRT_REPOS;
958 kill_stream(pt);
959 return 0;
960 }
961 EXPORT_PLAY_CMD_HANDLER(jmp);
962
963 static int com_ff(struct play_task *pt, struct lls_parse_result *lpr)
964 {
965 int32_t seconds;
966 char *errctx;
967 int ret;
968
969 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
970 if (ret < 0) {
971 if (errctx)
972 PARA_ERROR_LOG("%s\n", errctx);
973 free(errctx);
974 return ret;
975 }
976 ret = para_atoi32(lls_input(0, lpr), &seconds);
977 if (ret < 0)
978 return ret;
979 if (pt->playing && !pt->fn.btrn)
980 return 0;
981 seconds += get_play_time(pt);
982 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
983 seconds = PARA_MAX(seconds, 0);
984 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
985 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
986 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
987 if (!pt->playing)
988 return 0;
989 pt->rq = CRT_REPOS;
990 kill_stream(pt);
991 return 0;
992 }
993 EXPORT_PLAY_CMD_HANDLER(ff);
994
995 static int run_command(char *line, struct play_task *pt)
996 {
997 int ret, argc;
998 char **argv = NULL;
999 char *errctx = NULL;
1000 const struct play_command_info *pci;
1001 struct lls_parse_result *lpr;
1002 const struct lls_command *cmd;
1003
1004 attach_stdout(pt, __FUNCTION__);
1005 ret = create_argv(line, " ", &argv);
1006 if (ret < 0)
1007 goto out;
1008 if (ret == 0)
1009 goto out;
1010 argc = ret;
1011 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
1012 if (ret < 0)
1013 goto out;
1014 cmd = lls_cmd(ret, play_cmd_suite);
1015 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
1016 if (ret < 0)
1017 goto out;
1018 pci = lls_user_data(cmd);
1019 ret = pci->handler(pt, lpr);
1020 lls_free_parse_result(lpr, cmd);
1021 out:
1022 if (errctx)
1023 PARA_ERROR_LOG("%s\n", errctx);
1024 free(errctx);
1025 free_argv(argv);
1026 return ret;
1027 }
1028
1029 static int play_i9e_line_handler(char *line)
1030 {
1031 return run_command(line, &play_task);
1032 }
1033
1034 static int play_i9e_key_handler(int key)
1035 {
1036 struct play_task *pt = &play_task;
1037 int idx = get_key_map_idx(key);
1038 char *seq = get_key_map_seq(key);
1039 char *cmd = get_key_map_cmd(key);
1040 bool internal = is_internal_key(key);
1041
1042 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1043 key, internal? "internal" : "user-defined",
1044 idx, seq, cmd);
1045 run_command(cmd, pt);
1046 free(seq);
1047 free(cmd);
1048 pt->next_update = *now;
1049 return 0;
1050 }
1051
1052 static struct i9e_client_info ici = {
1053 .fds = {0, 1, 2},
1054 .prompt = "para_play> ",
1055 .line_handler = play_i9e_line_handler,
1056 .key_handler = play_i9e_key_handler,
1057 .completers = pp_completers,
1058 };
1059
1060 static void sigint_handler(int sig)
1061 {
1062 play_task.background = true;
1063 i9e_signal_dispatch(sig);
1064 }
1065
1066 /*
1067 * We start with para_log() set to the standard log function which writes to
1068 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1069 * log facility.
1070 */
1071 static void session_open(struct play_task *pt)
1072 {
1073 int ret;
1074 char *history_file;
1075 struct sigaction act;
1076
1077 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1078 if (conf.history_file_given)
1079 history_file = para_strdup(conf.history_file_arg);
1080 else {
1081 char *home = para_homedir();
1082 history_file = make_message("%s/.paraslash/play.history",
1083 home);
1084 free(home);
1085 }
1086 ici.history_file = history_file;
1087 ici.loglevel = loglevel;
1088
1089 act.sa_handler = sigint_handler;
1090 sigemptyset(&act.sa_mask);
1091 act.sa_flags = 0;
1092 sigaction(SIGINT, &act, NULL);
1093 act.sa_handler = i9e_signal_dispatch;
1094 sigemptyset(&act.sa_mask);
1095 act.sa_flags = 0;
1096 sigaction(SIGWINCH, &act, NULL);
1097 sched.select_function = i9e_select;
1098
1099 ici.bound_keyseqs = get_mapped_keyseqs();
1100 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1101 EMBRACE(.name = __FUNCTION__));
1102 ret = i9e_open(&ici, &sched);
1103 if (ret < 0)
1104 goto out;
1105 para_log = i9e_log;
1106 return;
1107 out:
1108 free(history_file);
1109 if (ret >= 0)
1110 return;
1111 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1112 exit(EXIT_FAILURE);
1113 }
1114
1115 static void session_update_time_string(struct play_task *pt, char *str, unsigned len)
1116 {
1117 if (pt->background)
1118 return;
1119 if (pt->btrn) {
1120 if (btr_get_output_queue_size(pt->btrn) > 0)
1121 return;
1122 if (btr_get_input_queue_size(pt->btrn) > 0)
1123 return;
1124 }
1125 ie9_print_status_bar(str, len);
1126 }
1127
1128 /*
1129 * If we are about to die we must call i9e_close() to reset the terminal.
1130 * However, i9e_close() must be called in *this* context, i.e. from
1131 * play_task.post_select() rather than from i9e_post_select(), because
1132 * otherwise i9e would access freed memory upon return. So the play task must
1133 * stay alive until the i9e task terminates.
1134 *
1135 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1136 * and reschedule. In the next iteration, i9e->post_select returns an error and
1137 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1138 * are allowed to call i9e_close() and terminate as well.
1139 */
1140 static int session_post_select(__a_unused struct sched *s, struct play_task *pt)
1141 {
1142 int ret;
1143
1144 if (pt->background)
1145 detach_stdout(pt);
1146 else
1147 attach_stdout(pt, __FUNCTION__);
1148 ret = i9e_get_error();
1149 if (ret < 0) {
1150 kill_stream(pt);
1151 i9e_close();
1152 para_log = stderr_log;
1153 free(ici.history_file);
1154 return ret;
1155 }
1156 if (get_playback_state(pt) == 'X')
1157 i9e_signal_dispatch(SIGTERM);
1158 return 0;
1159 }
1160
1161 #else /* HAVE_READLINE */
1162
1163 static int session_post_select(struct sched *s, struct play_task *pt)
1164 {
1165 char c;
1166
1167 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1168 return 0;
1169 if (read(STDIN_FILENO, &c, 1))
1170 do_nothing;
1171 kill_stream(pt);
1172 return 1;
1173 }
1174
1175 static void session_open(__a_unused struct play_task *pt)
1176 {
1177 }
1178
1179 static void session_update_time_string(__a_unused struct play_task *pt,
1180 char *str, __a_unused unsigned len)
1181 {
1182 printf("\r%s ", str);
1183 fflush(stdout);
1184 }
1185 #endif /* HAVE_READLINE */
1186
1187 static void play_pre_select(struct sched *s, void *context)
1188 {
1189 struct play_task *pt = context;
1190 char state;
1191
1192 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1193 state = get_playback_state(pt);
1194 if (state == 'R' || state == 'F' || state == 'X')
1195 return sched_min_delay(s);
1196 sched_request_barrier_or_min_delay(&pt->next_update, s);
1197 }
1198
1199 static unsigned get_time_string(struct play_task *pt, char **result)
1200 {
1201 int seconds, length;
1202 char state = get_playback_state(pt);
1203
1204 /* do not return anything if things are about to change */
1205 if (state != 'P' && state != 'U') {
1206 *result = NULL;
1207 return 0;
1208 }
1209 length = pt->seconds;
1210 if (length == 0)
1211 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1212 seconds = get_play_time(pt);
1213 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1214 pt->current_file,
1215 seconds / 60,
1216 seconds % 60,
1217 (length - seconds) / 60,
1218 (length - seconds) % 60,
1219 length? (seconds * 100 + length / 2) / length : 0,
1220 length / 60,
1221 length % 60,
1222 conf.inputs[pt->current_file]
1223 );
1224 }
1225
1226 static int play_post_select(struct sched *s, void *context)
1227 {
1228 struct play_task *pt = context;
1229 int ret;
1230
1231 ret = eof_cleanup(pt);
1232 if (ret < 0) {
1233 pt->rq = CRT_TERM_RQ;
1234 return 0;
1235 }
1236 ret = session_post_select(s, pt);
1237 if (ret < 0)
1238 goto out;
1239 if (!pt->wn.btrn && !pt->fn.btrn) {
1240 char state = get_playback_state(pt);
1241 if (state == 'P' || state == 'R' || state == 'F') {
1242 PARA_NOTICE_LOG("state: %c\n", state);
1243 ret = load_next_file(pt);
1244 if (ret < 0) {
1245 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1246 pt->rq = CRT_TERM_RQ;
1247 ret = 1;
1248 goto out;
1249 }
1250 pt->next_update = *now;
1251 }
1252 }
1253 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1254 char *str;
1255 unsigned len = get_time_string(pt, &str);
1256 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1257 if (str && len > 0)
1258 session_update_time_string(pt, str, len);
1259 free(str);
1260 tv_add(now, &delay, &pt->next_update);
1261 }
1262 ret = 1;
1263 out:
1264 return ret;
1265 }
1266
1267 /**
1268 * The main function of para_play.
1269 *
1270 * \param argc Standard.
1271 * \param argv Standard.
1272 *
1273 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1274 */
1275 int main(int argc, char *argv[])
1276 {
1277 int ret;
1278 struct play_task *pt = &play_task;
1279
1280 /* needed this early to make help work */
1281 recv_init();
1282 filter_init();
1283 writer_init();
1284
1285 sched.default_timeout.tv_sec = 5;
1286
1287 parse_config_or_die(argc, argv);
1288 if (conf.inputs_num == 0)
1289 print_help_and_die();
1290 check_afh_receiver_or_die();
1291
1292 session_open(pt);
1293 if (conf.randomize_given)
1294 shuffle(conf.inputs, conf.inputs_num);
1295 pt->invalid = para_calloc(sizeof(*pt->invalid) * conf.inputs_num);
1296 pt->rq = CRT_FILE_CHANGE;
1297 pt->current_file = conf.inputs_num - 1;
1298 pt->playing = true;
1299 pt->task = task_register(&(struct task_info){
1300 .name = "play",
1301 .pre_select = play_pre_select,
1302 .post_select = play_post_select,
1303 .context = pt,
1304 }, &sched);
1305 ret = schedule(&sched);
1306 sched_shutdown(&sched);
1307 if (ret < 0)
1308 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1309 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1310 }