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