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