ovos-media-plugin-cli 0.0.3a1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,203 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2022 Casimiro Ferreira
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
203
+
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: ovos-media-plugin-cli
3
+ Version: 0.0.3a1
4
+ Summary: Generic CLI-command playback plugin for ovos-media (and the legacy ovos-audio service)
5
+ Author-email: JarbasAi <jarbasai@mailfence.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/OpenVoiceOS/ovos-media-plugin-cli
8
+ Keywords: ovos,audio,OCP,plugin,cli
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: ovos-plugin-manager<3.0.0,>=2.1.0
12
+ Requires-Dist: requests
13
+ Provides-Extra: test
14
+ Requires-Dist: pytest; extra == "test"
15
+ Requires-Dist: ovoscope[media]>=0.20.0a1; extra == "test"
16
+ Dynamic: license-file
17
+
18
+ # ovos-media-plugin-cli
19
+
20
+ Generic **command-line playback** plugin for
21
+ [ovos-media](https://github.com/OpenVoiceOS/ovos-media), and for the legacy
22
+ `ovos-audio` service.
23
+
24
+ The plugin plays a track by running a command-line media player as a
25
+ subprocess. Point it at any player command, or let it auto-detect the best
26
+ available one for your platform.
27
+
28
+ - **Explicit command**: set `command` (for example `"mpv --no-terminal"`,
29
+ `"cvlc --play-and-exit"`, `"ffplay -nodisp -autoexit"`). The plugin appends
30
+ the track URI as the final argument.
31
+ - **Auto-detect** (default): when you do not set a command, the plugin picks
32
+ the best available player for your platform through `shutil.which`. It
33
+ prefers `sox` (`play`), then tries `mpg123`, `paplay`, or `aplay` on Linux,
34
+ and `afplay` on macOS.
35
+
36
+ Pause and resume use process signals (`SIGSTOP`/`SIGCONT`). Stop terminates
37
+ the child process.
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pip install ovos-media-plugin-cli
43
+ ```
44
+
45
+ Install `sox` too. It gives the widest format and URL coverage when the
46
+ plugin auto-detects a player.
47
+
48
+ ## Configuration
49
+
50
+ New `ovos-media`:
51
+
52
+ ```json
53
+ {
54
+ "media": {
55
+ "preferred_audio_services": ["mplayer", "vlc", "cli"],
56
+ "audio_players": {
57
+ "cli": {
58
+ "module": "ovos-media-audio-plugin-cli",
59
+ "aliases": ["Command line", "CLI Player"],
60
+ "active": true,
61
+ "command": "mpv --no-terminal"
62
+ }
63
+ }
64
+ }
65
+ }
66
+ ```
67
+
68
+ Omit `command` to auto-detect. Legacy `ovos-audio`:
69
+
70
+ ```json
71
+ {
72
+ "Audio": {
73
+ "backends": {
74
+ "cli": { "type": "cli", "active": true, "command": "mpv --no-terminal" }
75
+ }
76
+ }
77
+ }
78
+ ```
79
+
80
+ ### Keys
81
+
82
+ | Key | Type | Default | Description |
83
+ |-----|------|---------|-------------|
84
+ | `command` (alias `play_cmd`) | str | _auto-detect_ | CLI player command. The plugin appends the URI as the last argument. |
85
+ | `active` | bool | `true` | Enable or disable this backend instance. |
86
+
87
+ ## Entry points
88
+
89
+ | Group | Name | Object |
90
+ |-------|------|--------|
91
+ | `opm.media.audio` | `ovos-media-audio-plugin-cli` | `ovos_media_plugin_cli:CLIAudioService` |
92
+ | `mycroft.plugin.audioservice` | `ovos_cli` | `ovos_media_plugin_cli.audio` |
93
+
94
+ ## Related projects
95
+
96
+ - [ovos-media](https://github.com/OpenVoiceOS/ovos-media): the media service this plugin's `opm.media.audio` entry point serves.
97
+ - [ovos-plugin-manager](https://github.com/OpenVoiceOS/ovos-plugin-manager): defines the `MediaBackend`/`AudioPlayerBackend` and legacy `AudioBackend` base classes this plugin implements.
98
+ - [ovos-media-plugin-mpv](https://github.com/OpenVoiceOS/ovos-media-plugin-mpv), [ovos-media-plugin-vlc](https://github.com/OpenVoiceOS/ovos-media-plugin-vlc), [ovos-media-plugin-mplayer](https://github.com/OpenVoiceOS/ovos-media-plugin-mplayer), and [ovos-media-plugin-ffplay](https://github.com/OpenVoiceOS/ovos-media-plugin-ffplay): sibling audio-playback plugins for one specific player, instead of the generic CLI command this plugin wraps.
99
+
100
+ ## License
101
+
102
+ Apache-2.0, see [LICENSE](LICENSE).
@@ -0,0 +1,85 @@
1
+ # ovos-media-plugin-cli
2
+
3
+ Generic **command-line playback** plugin for
4
+ [ovos-media](https://github.com/OpenVoiceOS/ovos-media), and for the legacy
5
+ `ovos-audio` service.
6
+
7
+ The plugin plays a track by running a command-line media player as a
8
+ subprocess. Point it at any player command, or let it auto-detect the best
9
+ available one for your platform.
10
+
11
+ - **Explicit command**: set `command` (for example `"mpv --no-terminal"`,
12
+ `"cvlc --play-and-exit"`, `"ffplay -nodisp -autoexit"`). The plugin appends
13
+ the track URI as the final argument.
14
+ - **Auto-detect** (default): when you do not set a command, the plugin picks
15
+ the best available player for your platform through `shutil.which`. It
16
+ prefers `sox` (`play`), then tries `mpg123`, `paplay`, or `aplay` on Linux,
17
+ and `afplay` on macOS.
18
+
19
+ Pause and resume use process signals (`SIGSTOP`/`SIGCONT`). Stop terminates
20
+ the child process.
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ pip install ovos-media-plugin-cli
26
+ ```
27
+
28
+ Install `sox` too. It gives the widest format and URL coverage when the
29
+ plugin auto-detects a player.
30
+
31
+ ## Configuration
32
+
33
+ New `ovos-media`:
34
+
35
+ ```json
36
+ {
37
+ "media": {
38
+ "preferred_audio_services": ["mplayer", "vlc", "cli"],
39
+ "audio_players": {
40
+ "cli": {
41
+ "module": "ovos-media-audio-plugin-cli",
42
+ "aliases": ["Command line", "CLI Player"],
43
+ "active": true,
44
+ "command": "mpv --no-terminal"
45
+ }
46
+ }
47
+ }
48
+ }
49
+ ```
50
+
51
+ Omit `command` to auto-detect. Legacy `ovos-audio`:
52
+
53
+ ```json
54
+ {
55
+ "Audio": {
56
+ "backends": {
57
+ "cli": { "type": "cli", "active": true, "command": "mpv --no-terminal" }
58
+ }
59
+ }
60
+ }
61
+ ```
62
+
63
+ ### Keys
64
+
65
+ | Key | Type | Default | Description |
66
+ |-----|------|---------|-------------|
67
+ | `command` (alias `play_cmd`) | str | _auto-detect_ | CLI player command. The plugin appends the URI as the last argument. |
68
+ | `active` | bool | `true` | Enable or disable this backend instance. |
69
+
70
+ ## Entry points
71
+
72
+ | Group | Name | Object |
73
+ |-------|------|--------|
74
+ | `opm.media.audio` | `ovos-media-audio-plugin-cli` | `ovos_media_plugin_cli:CLIAudioService` |
75
+ | `mycroft.plugin.audioservice` | `ovos_cli` | `ovos_media_plugin_cli.audio` |
76
+
77
+ ## Related projects
78
+
79
+ - [ovos-media](https://github.com/OpenVoiceOS/ovos-media): the media service this plugin's `opm.media.audio` entry point serves.
80
+ - [ovos-plugin-manager](https://github.com/OpenVoiceOS/ovos-plugin-manager): defines the `MediaBackend`/`AudioPlayerBackend` and legacy `AudioBackend` base classes this plugin implements.
81
+ - [ovos-media-plugin-mpv](https://github.com/OpenVoiceOS/ovos-media-plugin-mpv), [ovos-media-plugin-vlc](https://github.com/OpenVoiceOS/ovos-media-plugin-vlc), [ovos-media-plugin-mplayer](https://github.com/OpenVoiceOS/ovos-media-plugin-mplayer), and [ovos-media-plugin-ffplay](https://github.com/OpenVoiceOS/ovos-media-plugin-ffplay): sibling audio-playback plugins for one specific player, instead of the generic CLI command this plugin wraps.
82
+
83
+ ## License
84
+
85
+ Apache-2.0, see [LICENSE](LICENSE).
@@ -0,0 +1,283 @@
1
+ import mimetypes
2
+ import platform
3
+ import re
4
+ import shutil
5
+ import signal
6
+ import subprocess
7
+ import time
8
+ from time import sleep
9
+
10
+ from ovos_plugin_manager.templates.media import MediaBackend, AudioPlayerBackend
11
+ from ovos_utils.log import LOG
12
+ from requests import Session
13
+
14
+
15
+ def find_mime(path):
16
+ mime = None
17
+ if path.startswith('http'):
18
+ response = Session().head(path, allow_redirects=True)
19
+ if 200 <= response.status_code < 300:
20
+ mime = response.headers['content-type']
21
+ if not mime:
22
+ mime = mimetypes.guess_type(path)[0]
23
+ # Remove any http address arguments
24
+ if not mime:
25
+ mime = mimetypes.guess_type(re.sub(r'\?.*$', '', path))[0]
26
+
27
+ if mime:
28
+ return mime.split('/')
29
+ else:
30
+ return (None, None)
31
+
32
+
33
+ def play_audio(uri, play_cmd):
34
+ """ Play a audio file.
35
+
36
+ Returns: subprocess.Popen object
37
+ """
38
+ play_wav_cmd = play_cmd.split() + [uri]
39
+
40
+ try:
41
+ return subprocess.Popen(play_wav_cmd)
42
+ except Exception as e:
43
+ LOG.error(f"Failed to play: {play_wav_cmd}")
44
+ LOG.debug(f"Error: {e}")
45
+ return None
46
+
47
+
48
+ class CLIBaseService(MediaBackend):
49
+ """Framework-agnostic subprocess-based audio player.
50
+
51
+ Holds all the playback logic (spawning/stopping a CLI player such as
52
+ ``play``/``paplay``/``aplay``/``mpg123``, pause/resume via process signals,
53
+ position estimation). It is shared by both backend flavours:
54
+
55
+ * new ``ovos-media`` — :class:`CLIAudioService` (``AudioPlayerBackend``)
56
+ * legacy ``ovos-audio`` — :class:`~ovos_media_plugin_cli.audio.CLIOldAudioService`
57
+ (``AudioBackend``)
58
+
59
+ so the two entry points drive the same engine with no duplicated logic.
60
+ """
61
+ sox_play = shutil.which("play")
62
+ pulse_play = shutil.which("paplay")
63
+ alsa_play = shutil.which("aplay")
64
+ mpg123_play = shutil.which("mpg123")
65
+ afplay = shutil.which("afplay") # macOS
66
+
67
+ def __init__(self, config, bus=None):
68
+ super().__init__(config, bus)
69
+ self.process = None
70
+ self._stop_signal = False
71
+ self._is_playing = False
72
+ self._paused = False
73
+ self.ts = 0
74
+
75
+ self.supports_mime_hints = True
76
+ mimetypes.init()
77
+
78
+ def on_track_start(self):
79
+ self.ts = time.time()
80
+ # Indicate to audio service which track is being played
81
+ if self._track_start_callback:
82
+ self._track_start_callback(self._now_playing)
83
+
84
+ def on_track_end(self):
85
+ self._is_playing = False
86
+ self._paused = False
87
+ self.process = None
88
+ self.ts = 0
89
+ if self._track_start_callback:
90
+ self._track_start_callback(None)
91
+
92
+ def on_track_error(self):
93
+ self._is_playing = False
94
+ self._paused = False
95
+ self.process = None
96
+ self.ts = 0
97
+ self.ocp_error()
98
+
99
+ # player internals
100
+ def _get_track(self, track_data):
101
+ if isinstance(track_data, list):
102
+ track = track_data[0]
103
+ mime = track_data[1]
104
+ mime = mime.split('/')
105
+ else: # Assume string
106
+ track = track_data
107
+ mime = find_mime(track)
108
+ return track, mime
109
+
110
+ def _is_process_running(self):
111
+ return self.process and self.process.poll() is None
112
+
113
+ def _stop_running_process(self):
114
+ if self._is_process_running():
115
+ if self._paused:
116
+ # The child process must be "unpaused" in order to be stopped
117
+ self.process.send_signal(signal.SIGCONT)
118
+ self.process.terminate()
119
+ countdown = 10
120
+ while self._is_process_running() and countdown > 0:
121
+ sleep(0.1)
122
+ countdown -= 1
123
+
124
+ if self._is_process_running():
125
+ # Failed to shutdown when asked nicely. Force the issue.
126
+ LOG.debug("Killing currently playing audio...")
127
+ self.process.kill()
128
+ self.process = None
129
+
130
+ @property
131
+ def player_cmd(self):
132
+ """The CLI command used to play a stream.
133
+
134
+ Resolution order:
135
+
136
+ 1. an explicit command from config (``command`` / ``play_cmd``) — the
137
+ generic case: any CLI player you want, e.g. ``"mpv --no-terminal"`` or
138
+ ``"cvlc --play-and-exit"``. The track URI is appended as the last arg.
139
+ 2. otherwise, the best available player is auto-detected for this platform
140
+ via :func:`shutil.which` (sox ``play`` → mpg123/paplay/aplay on Linux,
141
+ ``afplay`` on macOS).
142
+ """
143
+ # 1. explicit, user-configured command — fully generic
144
+ cmd = self.config.get("command") or self.config.get("play_cmd")
145
+ if cmd:
146
+ return cmd
147
+
148
+ # 2. auto-detect the best CLI player for this platform
149
+ # sox should handle almost every format, but fails on some urls
150
+ if self.sox_play:
151
+ track = self._now_playing
152
+ # NOTE: some urls like youtube streams will cause extension detection
153
+ # to fail, let's handle it explicitly
154
+ ext = track.split("?")[0].split(".")[-1]
155
+ return self.sox_play + f" --type {ext}"
156
+
157
+ # macOS
158
+ if platform.system() == "Darwin" and self.afplay:
159
+ return self.afplay
160
+
161
+ track, mime = self._get_track(self._now_playing)
162
+ LOG.debug(f'Mime info: {mime}')
163
+ player = None
164
+ if 'wav' in mime[1]:
165
+ player = self.pulse_play
166
+ elif self.mpg123_play:
167
+ player = self.mpg123_play
168
+ # fallback to alsa, only wav files will play correctly
169
+ return player or self.alsa_play
170
+
171
+ # audio service
172
+ def supported_uris(self):
173
+ uris = ['file', 'http']
174
+ if self.sox_play:
175
+ uris.append("https")
176
+ return uris
177
+
178
+ def play(self, repeat=False):
179
+ """ Play the track via the configured/auto-detected CLI command. """
180
+ # Stop any existing audio playback
181
+ self._stop_running_process()
182
+
183
+ self._is_playing = True
184
+ self._paused = False
185
+
186
+ # Replace file:// uri's with normal paths
187
+ uri = self._now_playing.replace('file://', '')
188
+
189
+ self.on_track_start()
190
+ try:
191
+ self.process = play_audio(uri, self.player_cmd)
192
+ except FileNotFoundError as e:
193
+ LOG.error(f'Couldn\'t play audio, {e}')
194
+ self.process = None
195
+ self.on_track_error()
196
+ except Exception as e:
197
+ LOG.exception(repr(e))
198
+ self.process = None
199
+ self.on_track_error()
200
+
201
+ # Wait for completion or stop request
202
+ while (self._is_process_running() and not self._stop_signal):
203
+ sleep(0.25)
204
+
205
+ if self._stop_signal:
206
+ self._stop_running_process()
207
+
208
+ self.on_track_end()
209
+
210
+ def stop(self):
211
+ """ Stop playback. """
212
+ LOG.info('CLI player stop')
213
+ if self._is_playing:
214
+ self._stop_signal = True
215
+ while self._is_playing:
216
+ sleep(0.1)
217
+ self._stop_signal = False
218
+ return True
219
+ return False
220
+
221
+ def pause(self):
222
+ """ Pause playback. """
223
+ if self.process and not self._paused:
224
+ # Suspend the playback process
225
+ self.process.send_signal(signal.SIGSTOP)
226
+ self._paused = True
227
+
228
+ def resume(self):
229
+ """ Resume paused playback. """
230
+ if self.process and self._paused:
231
+ # Resume the playback process
232
+ self.process.send_signal(signal.SIGCONT)
233
+ self._paused = False
234
+
235
+ def lower_volume(self):
236
+ """Lower volume.
237
+
238
+ This method is used to implement audio ducking. It will be called when
239
+ OpenVoiceOS is listening or speaking to make sure the media playing isn't
240
+ interfering.
241
+ """
242
+ # Not available in this plugin
243
+
244
+ def restore_volume(self):
245
+ """Restore normal volume.
246
+
247
+ Called when to restore the playback volume to previous level after
248
+ OpenVoiceOS has lowered it using lower_volume().
249
+ """
250
+ # Not available in this plugin
251
+
252
+ def get_track_length(self) -> int:
253
+ """
254
+ getting the duration of the audio in milliseconds
255
+ """
256
+ # we only can estimate how much we already played as a minimum value
257
+ return self.get_track_position()
258
+
259
+ def get_track_position(self) -> int:
260
+ """
261
+ get current position in milliseconds
262
+ """
263
+ # approximate given timestamp of playback start
264
+ if self.ts:
265
+ return int((time.time() - self.ts) * 1000)
266
+ return 0
267
+
268
+ def set_track_position(self, milliseconds):
269
+ """
270
+ go to position in milliseconds
271
+ Args:
272
+ milliseconds (int): number of milliseconds of final position
273
+ """
274
+ # Not available in this plugin
275
+
276
+
277
+ class CLIAudioService(AudioPlayerBackend, CLIBaseService):
278
+ """Subprocess CLI-command audio backend for the new ovos-media service.
279
+
280
+ ``CLIBaseService`` is listed second; its concrete methods satisfy the
281
+ abstract playback methods declared on ``AudioPlayerBackend``. All behaviour
282
+ lives in :class:`CLIBaseService`.
283
+ """
@@ -0,0 +1,50 @@
1
+ """Legacy ``ovos-audio`` (mycroft.plugin.audioservice) adapter.
2
+
3
+ The same subprocess player engine as the new ovos-media
4
+ :class:`~ovos_media_plugin_cli.CLIAudioService`, exposed under the legacy
5
+ audio-service contract so this plugin works on both stacks:
6
+
7
+ * new ``ovos-media`` — ``opm.media.audio`` → :class:`~ovos_media_plugin_cli.CLIAudioService`
8
+ * legacy ``ovos-audio`` — ``mycroft.plugin.audioservice`` → :class:`CLIOldAudioService`
9
+ (discovered via :func:`load_service`)
10
+ """
11
+ from ovos_plugin_manager.templates.audio import AudioBackend
12
+ from ovos_utils.log import LOG
13
+
14
+ from ovos_media_plugin_cli import CLIBaseService
15
+
16
+
17
+ class CLIOldAudioService(CLIBaseService, AudioBackend):
18
+ """Subprocess CLI-command backend for the legacy ovos-audio service.
19
+
20
+ Reuses every playback method (``play``/``stop``/``pause``/``resume``/
21
+ seek/volume/position) from :class:`CLIBaseService`; only the constructor
22
+ differs because the legacy ``AudioBackend`` takes a ``name``.
23
+
24
+ ``CLIBaseService`` is listed first so its concrete methods satisfy the
25
+ abstract playback methods declared on ``AudioBackend`` (MRO order matters).
26
+ """
27
+
28
+ def __init__(self, config, bus=None, name='cli'):
29
+ AudioBackend.__init__(self, config, bus, name)
30
+ # set up the shared subprocess player engine without the new
31
+ # MediaBackend constructor
32
+ self.process = None
33
+ self._stop_signal = False
34
+ self._is_playing = False
35
+ self._paused = False
36
+ self.ts = 0
37
+ self.supports_mime_hints = True
38
+ import mimetypes
39
+ mimetypes.init()
40
+
41
+
42
+ def load_service(base_config, bus):
43
+ backends = base_config.get('backends', {})
44
+ services = [(b, backends[b]) for b in backends
45
+ if backends[b].get('type') in ['cli', 'ovos_cli'] and
46
+ backends[b].get('active', True)]
47
+ instances = [CLIOldAudioService(s[1], bus, s[0]) for s in services]
48
+ if len(instances) == 0:
49
+ LOG.warning("No CLI backends have been configured")
50
+ return instances
@@ -0,0 +1,11 @@
1
+ # The following lines are replaced during the release process.
2
+ # START_VERSION_BLOCK
3
+ VERSION_MAJOR = 0
4
+ VERSION_MINOR = 0
5
+ VERSION_BUILD = 3
6
+ VERSION_ALPHA = 1
7
+ # END_VERSION_BLOCK
8
+
9
+ __version__ = f"{VERSION_MAJOR}.{VERSION_MINOR}.{VERSION_BUILD}"
10
+ if VERSION_ALPHA:
11
+ __version__ += f"a{VERSION_ALPHA}"
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: ovos-media-plugin-cli
3
+ Version: 0.0.3a1
4
+ Summary: Generic CLI-command playback plugin for ovos-media (and the legacy ovos-audio service)
5
+ Author-email: JarbasAi <jarbasai@mailfence.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/OpenVoiceOS/ovos-media-plugin-cli
8
+ Keywords: ovos,audio,OCP,plugin,cli
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: ovos-plugin-manager<3.0.0,>=2.1.0
12
+ Requires-Dist: requests
13
+ Provides-Extra: test
14
+ Requires-Dist: pytest; extra == "test"
15
+ Requires-Dist: ovoscope[media]>=0.20.0a1; extra == "test"
16
+ Dynamic: license-file
17
+
18
+ # ovos-media-plugin-cli
19
+
20
+ Generic **command-line playback** plugin for
21
+ [ovos-media](https://github.com/OpenVoiceOS/ovos-media), and for the legacy
22
+ `ovos-audio` service.
23
+
24
+ The plugin plays a track by running a command-line media player as a
25
+ subprocess. Point it at any player command, or let it auto-detect the best
26
+ available one for your platform.
27
+
28
+ - **Explicit command**: set `command` (for example `"mpv --no-terminal"`,
29
+ `"cvlc --play-and-exit"`, `"ffplay -nodisp -autoexit"`). The plugin appends
30
+ the track URI as the final argument.
31
+ - **Auto-detect** (default): when you do not set a command, the plugin picks
32
+ the best available player for your platform through `shutil.which`. It
33
+ prefers `sox` (`play`), then tries `mpg123`, `paplay`, or `aplay` on Linux,
34
+ and `afplay` on macOS.
35
+
36
+ Pause and resume use process signals (`SIGSTOP`/`SIGCONT`). Stop terminates
37
+ the child process.
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pip install ovos-media-plugin-cli
43
+ ```
44
+
45
+ Install `sox` too. It gives the widest format and URL coverage when the
46
+ plugin auto-detects a player.
47
+
48
+ ## Configuration
49
+
50
+ New `ovos-media`:
51
+
52
+ ```json
53
+ {
54
+ "media": {
55
+ "preferred_audio_services": ["mplayer", "vlc", "cli"],
56
+ "audio_players": {
57
+ "cli": {
58
+ "module": "ovos-media-audio-plugin-cli",
59
+ "aliases": ["Command line", "CLI Player"],
60
+ "active": true,
61
+ "command": "mpv --no-terminal"
62
+ }
63
+ }
64
+ }
65
+ }
66
+ ```
67
+
68
+ Omit `command` to auto-detect. Legacy `ovos-audio`:
69
+
70
+ ```json
71
+ {
72
+ "Audio": {
73
+ "backends": {
74
+ "cli": { "type": "cli", "active": true, "command": "mpv --no-terminal" }
75
+ }
76
+ }
77
+ }
78
+ ```
79
+
80
+ ### Keys
81
+
82
+ | Key | Type | Default | Description |
83
+ |-----|------|---------|-------------|
84
+ | `command` (alias `play_cmd`) | str | _auto-detect_ | CLI player command. The plugin appends the URI as the last argument. |
85
+ | `active` | bool | `true` | Enable or disable this backend instance. |
86
+
87
+ ## Entry points
88
+
89
+ | Group | Name | Object |
90
+ |-------|------|--------|
91
+ | `opm.media.audio` | `ovos-media-audio-plugin-cli` | `ovos_media_plugin_cli:CLIAudioService` |
92
+ | `mycroft.plugin.audioservice` | `ovos_cli` | `ovos_media_plugin_cli.audio` |
93
+
94
+ ## Related projects
95
+
96
+ - [ovos-media](https://github.com/OpenVoiceOS/ovos-media): the media service this plugin's `opm.media.audio` entry point serves.
97
+ - [ovos-plugin-manager](https://github.com/OpenVoiceOS/ovos-plugin-manager): defines the `MediaBackend`/`AudioPlayerBackend` and legacy `AudioBackend` base classes this plugin implements.
98
+ - [ovos-media-plugin-mpv](https://github.com/OpenVoiceOS/ovos-media-plugin-mpv), [ovos-media-plugin-vlc](https://github.com/OpenVoiceOS/ovos-media-plugin-vlc), [ovos-media-plugin-mplayer](https://github.com/OpenVoiceOS/ovos-media-plugin-mplayer), and [ovos-media-plugin-ffplay](https://github.com/OpenVoiceOS/ovos-media-plugin-ffplay): sibling audio-playback plugins for one specific player, instead of the generic CLI command this plugin wraps.
99
+
100
+ ## License
101
+
102
+ Apache-2.0, see [LICENSE](LICENSE).
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ ovos_media_plugin_cli/__init__.py
5
+ ovos_media_plugin_cli/audio.py
6
+ ovos_media_plugin_cli/version.py
7
+ ovos_media_plugin_cli.egg-info/PKG-INFO
8
+ ovos_media_plugin_cli.egg-info/SOURCES.txt
9
+ ovos_media_plugin_cli.egg-info/dependency_links.txt
10
+ ovos_media_plugin_cli.egg-info/entry_points.txt
11
+ ovos_media_plugin_cli.egg-info/requires.txt
12
+ ovos_media_plugin_cli.egg-info/top_level.txt
13
+ test/test_e2e.py
@@ -0,0 +1,5 @@
1
+ [mycroft.plugin.audioservice]
2
+ ovos_cli = ovos_media_plugin_cli.audio
3
+
4
+ [opm.media.audio]
5
+ ovos-media-audio-plugin-cli = ovos_media_plugin_cli:CLIAudioService
@@ -0,0 +1,6 @@
1
+ ovos-plugin-manager<3.0.0,>=2.1.0
2
+ requests
3
+
4
+ [test]
5
+ pytest
6
+ ovoscope[media]>=0.20.0a1
@@ -0,0 +1 @@
1
+ ovos_media_plugin_cli
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ovos-media-plugin-cli"
7
+ dynamic = ["version"]
8
+ description = "Generic CLI-command playback plugin for ovos-media (and the legacy ovos-audio service)"
9
+ readme = "README.md"
10
+ license = { text = "Apache-2.0" }
11
+ authors = [
12
+ { name = "JarbasAi", email = "jarbasai@mailfence.com" },
13
+ ]
14
+ keywords = ["ovos", "audio", "OCP", "plugin", "cli"]
15
+ dependencies = [
16
+ "ovos-plugin-manager>=2.1.0,<3.0.0",
17
+ "requests",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/OpenVoiceOS/ovos-media-plugin-cli"
22
+
23
+ [project.optional-dependencies]
24
+ test = [
25
+ "pytest",
26
+ # end-to-end harness: drives the real backend through a real OCPMediaPlayer.
27
+ # [media] (the OCPPlayerHarness) lands in ovoscope 0.20.x; floor-pin so pip
28
+ # resolves it without --pre once published.
29
+ "ovoscope[media]>=0.20.0a1",
30
+ ]
31
+
32
+ [project.entry-points."opm.media.audio"]
33
+ ovos-media-audio-plugin-cli = "ovos_media_plugin_cli:CLIAudioService"
34
+
35
+ # legacy ovos-audio service backend (so the plugin works on both stacks)
36
+ [project.entry-points."mycroft.plugin.audioservice"]
37
+ ovos_cli = "ovos_media_plugin_cli.audio"
38
+
39
+ [tool.setuptools.dynamic]
40
+ version = { attr = "ovos_media_plugin_cli.version.__version__" }
41
+
42
+ [tool.setuptools.packages.find]
43
+ where = ["."]
44
+ include = ["ovos_media_plugin_cli*"]
45
+
46
+ [tool.setuptools.package-data]
47
+ "*" = ["*.json", "*.voc", "*.intent", "*.dialog"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,85 @@
1
+ """End-to-end tests: drive the real CLI OCP backend through a real
2
+ ``OCPMediaPlayer`` on a FakeBus via ovoscope's media harness.
3
+
4
+ The plugin shells out to a CLI player via ``subprocess.Popen``, so
5
+ ``ovos_media_plugin_cli.subprocess`` is mocked: no real player is launched.
6
+ The spawned (mocked) process reports itself as already finished
7
+ (``poll()`` -> 0) so the backend's blocking ``play()`` loop returns promptly
8
+ instead of waiting on a real child. Everything else is real: the OCP player
9
+ routes the play/pause/stop requests to ``CLIAudioService`` exactly as
10
+ ovos-media would at runtime. A deterministic ``command`` is configured so
11
+ ``player_cmd`` never depends on which players happen to be installed.
12
+
13
+ Requires ``ovoscope[media]`` (pulls ovos-media).
14
+ """
15
+ import unittest
16
+ from unittest.mock import MagicMock, patch
17
+
18
+ try:
19
+ from ovoscope import OCPPlayerHarness
20
+ from ovos_utils.ocp import MediaEntry, PlaybackType, PlayerState
21
+ HAVE_HARNESS = True
22
+ except Exception:
23
+ HAVE_HARNESS = False
24
+
25
+ import ovos_media_plugin_cli
26
+ from ovos_media_plugin_cli import CLIAudioService
27
+
28
+ URI = "http://example.com/song.mp3"
29
+ # a real, always-present no-op command so player_cmd is deterministic
30
+ CONFIG = {"command": "true"}
31
+
32
+
33
+ def _factory(bus):
34
+ """Build the real CLI audio backend for injection into the OCP player."""
35
+ return CLIAudioService(CONFIG, bus)
36
+
37
+
38
+ def _mock_subprocess():
39
+ """A subprocess mock whose spawned process reports itself as finished.
40
+
41
+ ``poll()`` returning a non-``None`` value makes ``_is_process_running()``
42
+ False, so the backend's blocking ``play()`` loop exits immediately (the bus
43
+ handler that calls ``play()`` runs synchronously, so a live process would
44
+ deadlock the harness).
45
+ """
46
+ sub = MagicMock()
47
+ sub.Popen.return_value.poll.return_value = 0
48
+ return sub
49
+
50
+
51
+ @unittest.skipUnless(HAVE_HARNESS, "ovoscope[media] not installed")
52
+ class TestCLIEndToEnd(unittest.TestCase):
53
+ def test_play_pause_resume_stop_through_ocp(self):
54
+ mock_sub = _mock_subprocess()
55
+ with patch.object(ovos_media_plugin_cli, "subprocess", mock_sub):
56
+ with OCPPlayerHarness(backend_factory=_factory) as h:
57
+ entry = MediaEntry(uri=URI, playback=PlaybackType.AUDIO)
58
+
59
+ h.play(entry)
60
+ h.assert_player_state(PlayerState.PLAYING)
61
+ h.assert_now_playing_uri(URI)
62
+ # the real backend actually shelled out via its (mocked) engine
63
+ mock_sub.Popen.assert_called()
64
+ self.assertIn(URI, mock_sub.Popen.call_args[0][0])
65
+
66
+ h.pause()
67
+ h.assert_player_state(PlayerState.PAUSED)
68
+
69
+ h.resume()
70
+ h.assert_player_state(PlayerState.PLAYING)
71
+
72
+ h.stop()
73
+ h.assert_player_state(PlayerState.STOPPED)
74
+
75
+ def test_backend_is_the_real_cli_plugin(self):
76
+ with patch.object(ovos_media_plugin_cli, "subprocess", _mock_subprocess()):
77
+ with OCPPlayerHarness(backend_factory=_factory) as h:
78
+ self.assertIsInstance(h.backend, CLIAudioService)
79
+ self.assertEqual(h.backend.player_cmd, "true")
80
+ self.assertIn("file", h.backend.supported_uris())
81
+ self.assertIn("http", h.backend.supported_uris())
82
+
83
+
84
+ if __name__ == "__main__":
85
+ unittest.main()