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