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