1"""
2Usage
3
4    playmany.py
5
6Uses media_player to play a sequence of samples and record debug info
7
8A configuration must be active, see command configure.py
9If the active configuration has disallowed dbg overwrites it will do nothing.
10
11If a playlist was provided at session creation, then only the samples in the
12playlist will be played, otherwise all files in samples_dir.
13
14"""
15
16import os
17import subprocess
18import sys
19
20import fs
21import mpexceptions
22
23
24def main():
25    try:
26        pathserv = fs.get_path_info_for_active_session()
27    except mpexceptions.ExceptionUndefinedSamplesDir:
28        print("The env var 'pyglet_mp_samples_dir' is not defined.")
29        return 1
30    except mpexceptions.ExceptionNoSessionIsActive:
31        print("*** Error, no session active.")
32        return 1
33
34    try:
35        play_many(pathserv, timeout=120)
36    except mpexceptions.ExceptionAttemptToBreakRawDataProtection:
37        print("*** Error, attempt to overwrite raw data when protect_raw_data is True.")
38        return 1
39
40    return 0
41
42
43def play_many(pathserv, timeout=120):
44    """plays the samples in the session playlist for the current active session
45       timeout: max time allowed to play a sample, default is 120 seconds
46    """
47    conf = fs.get_session_configuration(pathserv)
48    if conf["dev_debug"]:
49        pass
50    else:
51        if conf["protect_raw_data"]:
52            raise mpexceptions.ExceptionAttemptToBreakRawDataProtection()
53
54    playlist_gen = pathserv.session_playlist_generator()
55    core_play_many(pathserv, playlist_gen, timeout=timeout)
56
57
58def core_play_many(pathserv, playlist_gen, timeout=120):
59    for sample, filename in playlist_gen:
60        dbg_file = pathserv.dbg_filename(sample)
61
62        print("playmany playing:", filename)
63
64        cmdline = [os.path.join(fs.get_media_player_path(), "media_player.py"),
65                   "--debug",
66                   "--outfile=" + dbg_file,
67                   filename]
68        killed, returncode = cmd__py3(cmdline, timeout=timeout)
69        if killed:
70            print("WARNING: killed by timeout, file: %s" % filename)
71
72
73def cmd__py3(cmdline, bufsize=-1, cwd=None, timeout=60):
74    """runs a .py script as a subprocess with the same python as the caller
75
76       cmdline: list [<scriptname>, arg1, ...]
77       timeout: time in seconds; subprocess wil be killed if it is still running
78                at that time.
79    """
80    # use the same python as the caller to run the script
81    cmdline.insert(0, "-u")
82    cmdline.insert(0, sys.executable)
83
84    p = subprocess.Popen(
85        cmdline,
86        bufsize = bufsize,
87        shell   = False,
88        stdout  = subprocess.PIPE,
89        stderr  = subprocess.PIPE,
90        cwd     = cwd
91    )
92    killed = True
93    try:
94        out, err = p.communicate(timeout=timeout)
95        killed = False
96    except subprocess.TimeoutExpired:
97        p.kill()
98        out, err = p.communicate()
99##    print("out:", out)
100##    print("err:", err)
101
102    returncode = p.returncode
103
104    return killed, returncode
105
106
107def sysargs_to_mainargs():
108    """builds main args from sys.argv"""
109    if len(sys.argv) > 1 and sys.argv[1].startswith("--help"):
110        print(__doc__)
111        sys.exit(1)
112
113if __name__ == "__main__":
114    sysargs_to_mainargs()
115    main()
116