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