ovos-audio-plugin-browser 0.1.0a1__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,202 @@
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 [yyyy] [name of copyright owner]
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.
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: ovos-audio-plugin-browser
3
+ Version: 0.1.0a1
4
+ Summary: OpenVoiceOS audio backend: plays music, radio and podcasts in a browser's <audio> element, over the messagebus
5
+ Author: Andreas Lorensen
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/emkay-voice/ovos-audio-plugin-browser
8
+ Project-URL: Issues, https://github.com/emkay-voice/ovos-audio-plugin-browser/issues
9
+ Project-URL: Emkay, https://github.com/emkay-voice/emkay
10
+ Keywords: ovos,openvoiceos,plugin,audio,audioservice,ocp,media,radio,browser,pyodide,emkay
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Environment :: WebAssembly :: Emscripten
15
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Players
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: ovos-plugin-manager>=0.0.26
20
+ Requires-Dist: ovos-bus-client>=0.0.8
21
+ Requires-Dist: ovos-utils>=0.0.38
22
+ Provides-Extra: test
23
+ Requires-Dist: pytest; extra == "test"
24
+ Dynamic: license-file
25
+
26
+ # ovos-audio-plugin-browser
27
+
28
+ An [OpenVoiceOS](https://openvoiceos.org) audio backend that plays music,
29
+ internet radio and podcasts in a **browser's `<audio>` element**, over the
30
+ messagebus.
31
+
32
+ It was made for [Emkay](https://github.com/emkay-voice/emkay), OpenVoiceOS in
33
+ the browser (Pyodide), where it is the player behind ovos-audio's classic
34
+ `AudioService`. There it takes the place of
35
+ [ovos-audio-plugin-mpv](https://github.com/OpenVoiceOS/ovos-audio-plugin-mpv)
36
+ and vlc, which start a program on the device, which a browser cannot do.
37
+
38
+ ## How it works
39
+
40
+ ovos-audio's `AudioService` (the `mycroft.audio.service.*` API that OCP uses
41
+ in legacy mode, and that skills reach through `AudioServiceInterface`) picks
42
+ a backend for each URI and tells it to play, pause, seek and so on. This
43
+ backend does not play anything itself: it hands each command to the page as
44
+ a bus message, and the page answers with what its player did.
45
+
46
+ So it never touches a browser API, and the same backend works
47
+
48
+ - in Emkay, where OVOS runs in a Web Worker and the page answers
49
+ ([`web/media.js`](https://github.com/emkay-voice/emkay/blob/main/web/media.js)),
50
+ - on a normal OVOS device, with a browser connected to its messagebus
51
+ websocket as the speaker.
52
+
53
+ Playlists, repeat, ducking while OVOS speaks or listens
54
+ (`ovos.audio.output.started`/`ended`, `recognizer_loop:record_begin`/`end`)
55
+ and the OCP status messages are handled by `AudioService` and OPM's
56
+ `AudioBackend` template, the same as for any other backend.
57
+
58
+ ## Install and configure
59
+
60
+ ```bash
61
+ pip install ovos-audio-plugin-browser
62
+ ```
63
+
64
+ ```json
65
+ {
66
+ "Audio": {
67
+ "default-backend": "browser",
68
+ "backends": {
69
+ "browser": {"type": "ovos_audio_browser", "active": true, "duck_factor": 0.3}
70
+ }
71
+ },
72
+ "intents": {
73
+ "ovos-ocp-pipeline-plugin": {"legacy": true}
74
+ }
75
+ }
76
+ ```
77
+
78
+ - `duck_factor`: the music's volume while OVOS speaks or listens, 0..1.
79
+ - Without a `backends` entry of this type, one called `browser` is made, so
80
+ installing the plugin is enough; set `default-backend` to make it the
81
+ first choice.
82
+ - `"legacy": true` makes OCP play through `AudioService` (and this backend)
83
+ instead of waiting for ovos-media.
84
+
85
+ ## The protocol
86
+
87
+ To the page, one track at a time:
88
+
89
+ | message | data |
90
+ |-------------------------------|----------------------------|
91
+ | `ovos.audio.browser.play` | `uri`, `position_ms` |
92
+ | `ovos.audio.browser.pause` | |
93
+ | `ovos.audio.browser.resume` | |
94
+ | `ovos.audio.browser.stop` | |
95
+ | `ovos.audio.browser.seek` | `position_ms` |
96
+ | `ovos.audio.browser.volume` | `ducked` (bool), `factor` (0..1) |
97
+
98
+ From the page, whenever something happens, and every few seconds while
99
+ playing:
100
+
101
+ | message | data |
102
+ |-------------------------------|------|
103
+ | `ovos.audio.browser.state` | `uri`, `state` (`playing`, `paused`, `ended`, `error`), `position_ms`, `length_ms` (0 for a live stream), `error` (a plain reason) |
104
+
105
+ On `ended` the backend goes on with the next track (or starts over with
106
+ repeat) and at the end of the list `AudioService` reports
107
+ `mycroft.audio.queue_end`. On `error` it reports the error to OCP the same
108
+ way.
109
+
110
+ A page that answers should play the stream in an `<audio>` element, not
111
+ through Web Audio: `<audio>` plays a stream from another site without that
112
+ site's CORS permission, while a Web Audio graph turns such a stream silent.
113
+
114
+ ## Limits
115
+
116
+ - **https pages cannot play `http://` streams.** Browsers block this "mixed
117
+ content". Many internet radio stations have an https address; those
118
+ that do not fail with a clear reason, and OCP moves on to its next result.
119
+ - **Formats** are whatever the browser plays: mp3, aac, ogg/opus, and HLS
120
+ in Safari. YouTube and the like need a stream extractor in OCP, which
121
+ needs a site's permission to read it from a browser.
122
+ - The backend uses ovos-audio's classic audio service (`mycroft.plugin.audioservice`),
123
+ which OPM marks as deprecated in favour of ovos-media. It is what OCP's
124
+ legacy mode uses today; an ovos-media plugin can follow when Emkay moves.
125
+
126
+ ## License
127
+
128
+ Apache-2.0
@@ -0,0 +1,103 @@
1
+ # ovos-audio-plugin-browser
2
+
3
+ An [OpenVoiceOS](https://openvoiceos.org) audio backend that plays music,
4
+ internet radio and podcasts in a **browser's `<audio>` element**, over the
5
+ messagebus.
6
+
7
+ It was made for [Emkay](https://github.com/emkay-voice/emkay), OpenVoiceOS in
8
+ the browser (Pyodide), where it is the player behind ovos-audio's classic
9
+ `AudioService`. There it takes the place of
10
+ [ovos-audio-plugin-mpv](https://github.com/OpenVoiceOS/ovos-audio-plugin-mpv)
11
+ and vlc, which start a program on the device, which a browser cannot do.
12
+
13
+ ## How it works
14
+
15
+ ovos-audio's `AudioService` (the `mycroft.audio.service.*` API that OCP uses
16
+ in legacy mode, and that skills reach through `AudioServiceInterface`) picks
17
+ a backend for each URI and tells it to play, pause, seek and so on. This
18
+ backend does not play anything itself: it hands each command to the page as
19
+ a bus message, and the page answers with what its player did.
20
+
21
+ So it never touches a browser API, and the same backend works
22
+
23
+ - in Emkay, where OVOS runs in a Web Worker and the page answers
24
+ ([`web/media.js`](https://github.com/emkay-voice/emkay/blob/main/web/media.js)),
25
+ - on a normal OVOS device, with a browser connected to its messagebus
26
+ websocket as the speaker.
27
+
28
+ Playlists, repeat, ducking while OVOS speaks or listens
29
+ (`ovos.audio.output.started`/`ended`, `recognizer_loop:record_begin`/`end`)
30
+ and the OCP status messages are handled by `AudioService` and OPM's
31
+ `AudioBackend` template, the same as for any other backend.
32
+
33
+ ## Install and configure
34
+
35
+ ```bash
36
+ pip install ovos-audio-plugin-browser
37
+ ```
38
+
39
+ ```json
40
+ {
41
+ "Audio": {
42
+ "default-backend": "browser",
43
+ "backends": {
44
+ "browser": {"type": "ovos_audio_browser", "active": true, "duck_factor": 0.3}
45
+ }
46
+ },
47
+ "intents": {
48
+ "ovos-ocp-pipeline-plugin": {"legacy": true}
49
+ }
50
+ }
51
+ ```
52
+
53
+ - `duck_factor`: the music's volume while OVOS speaks or listens, 0..1.
54
+ - Without a `backends` entry of this type, one called `browser` is made, so
55
+ installing the plugin is enough; set `default-backend` to make it the
56
+ first choice.
57
+ - `"legacy": true` makes OCP play through `AudioService` (and this backend)
58
+ instead of waiting for ovos-media.
59
+
60
+ ## The protocol
61
+
62
+ To the page, one track at a time:
63
+
64
+ | message | data |
65
+ |-------------------------------|----------------------------|
66
+ | `ovos.audio.browser.play` | `uri`, `position_ms` |
67
+ | `ovos.audio.browser.pause` | |
68
+ | `ovos.audio.browser.resume` | |
69
+ | `ovos.audio.browser.stop` | |
70
+ | `ovos.audio.browser.seek` | `position_ms` |
71
+ | `ovos.audio.browser.volume` | `ducked` (bool), `factor` (0..1) |
72
+
73
+ From the page, whenever something happens, and every few seconds while
74
+ playing:
75
+
76
+ | message | data |
77
+ |-------------------------------|------|
78
+ | `ovos.audio.browser.state` | `uri`, `state` (`playing`, `paused`, `ended`, `error`), `position_ms`, `length_ms` (0 for a live stream), `error` (a plain reason) |
79
+
80
+ On `ended` the backend goes on with the next track (or starts over with
81
+ repeat) and at the end of the list `AudioService` reports
82
+ `mycroft.audio.queue_end`. On `error` it reports the error to OCP the same
83
+ way.
84
+
85
+ A page that answers should play the stream in an `<audio>` element, not
86
+ through Web Audio: `<audio>` plays a stream from another site without that
87
+ site's CORS permission, while a Web Audio graph turns such a stream silent.
88
+
89
+ ## Limits
90
+
91
+ - **https pages cannot play `http://` streams.** Browsers block this "mixed
92
+ content". Many internet radio stations have an https address; those
93
+ that do not fail with a clear reason, and OCP moves on to its next result.
94
+ - **Formats** are whatever the browser plays: mp3, aac, ogg/opus, and HLS
95
+ in Safari. YouTube and the like need a stream extractor in OCP, which
96
+ needs a site's permission to read it from a browser.
97
+ - The backend uses ovos-audio's classic audio service (`mycroft.plugin.audioservice`),
98
+ which OPM marks as deprecated in favour of ovos-media. It is what OCP's
99
+ legacy mode uses today; an ovos-media plugin can follow when Emkay moves.
100
+
101
+ ## License
102
+
103
+ Apache-2.0
@@ -0,0 +1,207 @@
1
+ """An ovos-audio backend that plays in a browser's <audio> element.
2
+
3
+ ovos-audio's classic AudioService (`mycroft.audio.service.*`, what OCP
4
+ uses in "legacy" mode and what skills' AudioServiceInterface talks to)
5
+ plays through backend plugins: mpv, vlc, simple. Those start a process
6
+ on the device. In a browser there is no process to start, but there is
7
+ the page's own media player, `<audio>`, which plays mp3, aac, ogg and
8
+ most internet radio straight from its URL.
9
+
10
+ This backend is that player, spoken to over the messagebus. It never
11
+ touches the page itself; it sends `ovos.audio.browser.*` messages and
12
+ listens for one, `ovos.audio.browser.state`, coming back. Any page that
13
+ answers them is the speaker:
14
+
15
+ - Emkay (OVOS in the browser, Pyodide) answers them from its own page;
16
+ - a browser connected to a normal OVOS device over the messagebus
17
+ websocket could answer them as well.
18
+
19
+ The protocol is in README.md. Playlists, repeat, ducking while OVOS
20
+ speaks or listens, and the OCP status messages are the same as for any
21
+ other backend: AudioService and the AudioBackend template handle them,
22
+ this module only plays one track at a time and reports what happened.
23
+ """
24
+ import time
25
+ from typing import List
26
+
27
+ from ovos_bus_client.message import Message
28
+ from ovos_plugin_manager.templates.audio import AudioBackend
29
+ from ovos_utils.log import LOG
30
+
31
+ #: The backend `type` in mycroft.conf's Audio.backends.
32
+ BACKEND_TYPE = "ovos_audio_browser"
33
+
34
+ #: Message types, page bound ...
35
+ PLAY = "ovos.audio.browser.play" # {uri, position_ms}
36
+ PAUSE = "ovos.audio.browser.pause"
37
+ RESUME = "ovos.audio.browser.resume"
38
+ STOP = "ovos.audio.browser.stop"
39
+ SEEK = "ovos.audio.browser.seek" # {position_ms}
40
+ VOLUME = "ovos.audio.browser.volume" # {ducked, factor}
41
+ #: ... and the one coming back from the page.
42
+ STATE = "ovos.audio.browser.state" # {uri, state, position_ms, length_ms, error}
43
+
44
+
45
+ class BrowserAudioBackend(AudioBackend):
46
+ """Plays one track at a time in the page's <audio> element.
47
+
48
+ Config (Audio.backends.<name>):
49
+ type: "ovos_audio_browser"
50
+ active: true
51
+ duck_factor: volume while OVOS speaks or listens, 0..1 (default 0.3)
52
+ """
53
+
54
+ def __init__(self, config=None, bus=None, name="browser"):
55
+ super().__init__(config=config, bus=bus, name=name)
56
+ self.duck_factor = float(self.config.get("duck_factor", 0.3))
57
+ self._repeat = False
58
+ self._state = "stopped" # stopped | loading | playing | paused
59
+ self._position_ms = 0
60
+ self._length_ms = 0 # 0: not known yet, or a live stream
61
+ self._stamp = time.monotonic()
62
+ self._announced = False
63
+ self.bus.on(STATE, self._on_state)
64
+
65
+ # ------------------------------------------------------------ to the page
66
+ def _send(self, msg_type: str, data: dict = None):
67
+ """Hand a command to the page, keeping the utterance's context, so
68
+ it reaches the same client (session) the request came from."""
69
+ self.bus.emit(self._format_msg(msg_type, data or {}))
70
+
71
+ def supported_uris(self) -> List[str]:
72
+ # what <audio> fetches by itself; file:// is not reachable from a page
73
+ return ["http", "https", "blob", "data"]
74
+
75
+ def play(self, repeat=None):
76
+ """Start the current track (the template's load_track set it).
77
+
78
+ `repeat` is given by AudioService for the whole playlist; the
79
+ template's next()/previous() call play() without it, so None keeps
80
+ what was asked for at the start."""
81
+ if repeat is not None:
82
+ self._repeat = bool(repeat)
83
+ uri = self._now_playing
84
+ if isinstance(uri, list): # (uri, mime) when mime hints are on
85
+ uri = uri[0]
86
+ if not uri:
87
+ LOG.warning("browser audio: nothing to play")
88
+ return
89
+ self._state = "loading"
90
+ self._announced = False # track start not reported yet
91
+ self._position_ms = 0
92
+ self._length_ms = 0
93
+ self._stamp = time.monotonic()
94
+ LOG.info(f"browser audio: playing {uri}")
95
+ self._send(PLAY, {"uri": uri, "position_ms": 0})
96
+
97
+ def pause(self):
98
+ if self._state in ("playing", "loading"):
99
+ self._position_ms = self.get_track_position()
100
+ self._state = "paused"
101
+ self._send(PAUSE)
102
+
103
+ def resume(self):
104
+ if self._state == "paused":
105
+ self._state = "playing"
106
+ self._stamp = time.monotonic()
107
+ self._send(RESUME)
108
+
109
+ def stop(self) -> bool:
110
+ """Stop; True when something was playing (AudioService then
111
+ reports mycroft.stop.handled)."""
112
+ was_playing = self._state != "stopped"
113
+ self._state = "stopped"
114
+ self._send(STOP)
115
+ return was_playing
116
+
117
+ def lower_volume(self):
118
+ self._send(VOLUME, {"ducked": True, "factor": self.duck_factor})
119
+
120
+ def restore_volume(self):
121
+ self._send(VOLUME, {"ducked": False, "factor": 1.0})
122
+
123
+ def get_track_length(self) -> int:
124
+ """In milliseconds; 0 for a live stream or before the page knows."""
125
+ return int(self._length_ms)
126
+
127
+ def get_track_position(self) -> int:
128
+ """In milliseconds. The page reports the position now and then;
129
+ between reports it is counted on from the last one."""
130
+ if self._state == "playing":
131
+ return int(self._position_ms + (time.monotonic() - self._stamp) * 1000)
132
+ return int(self._position_ms)
133
+
134
+ def set_track_position(self, milliseconds):
135
+ milliseconds = max(0, int(milliseconds))
136
+ if self._length_ms:
137
+ milliseconds = min(milliseconds, int(self._length_ms))
138
+ self._position_ms = milliseconds
139
+ self._stamp = time.monotonic()
140
+ self._send(SEEK, {"position_ms": milliseconds})
141
+
142
+ def shutdown(self):
143
+ self.bus.remove(STATE, self._on_state)
144
+ super().shutdown()
145
+
146
+ # ---------------------------------------------------------- from the page
147
+ def _on_state(self, message: Message):
148
+ """What the page's player did: started, paused, ended, failed, or
149
+ just where it is now."""
150
+ data = message.data or {}
151
+ if self._state == "stopped" and data.get("state") != "stopped":
152
+ return # a late report about a track that was stopped
153
+ if "position_ms" in data:
154
+ self._position_ms = float(data["position_ms"] or 0)
155
+ self._stamp = time.monotonic()
156
+ if data.get("length_ms"):
157
+ self._length_ms = float(data["length_ms"])
158
+ state = data.get("state")
159
+ if state == "playing":
160
+ self._state = "playing"
161
+ if not self._announced:
162
+ self._announced = True
163
+ if self._track_start_callback:
164
+ # AudioService: mycroft.audio.playing_track + OCP "playing"
165
+ self._track_start_callback(self._now_playing)
166
+ elif state == "paused" and self._state != "loading":
167
+ # (a page switching streams may report the old one paused first)
168
+ self._state = "paused"
169
+ elif state == "ended":
170
+ self._track_done()
171
+ elif state == "error":
172
+ LOG.error(f"browser audio: the page could not play "
173
+ f"{self._now_playing}: {data.get('error')}")
174
+ self.ocp_error()
175
+ self._track_done()
176
+ if state in ("playing", "paused"):
177
+ self.ocp_sync_playback(self.get_track_position())
178
+
179
+ def _track_done(self):
180
+ """Go on with the playlist, start it over (repeat), or end it."""
181
+ if self._idx + 1 < len(self._tracks):
182
+ self.next() # template: load_track + play
183
+ return
184
+ if self._repeat and self._tracks:
185
+ self._idx = 0
186
+ self.load_track(self._tracks[0])
187
+ self.play(self._repeat)
188
+ return
189
+ self._state = "stopped"
190
+ if self._track_start_callback:
191
+ self._track_start_callback(None) # mycroft.audio.queue_end
192
+
193
+
194
+ def load_service(base_config, bus):
195
+ """OPM's entry point: one backend per Audio.backends entry of our type.
196
+
197
+ If mycroft.conf has none, one called "browser" is made, so installing
198
+ the plugin is enough; ovos-audio still picks Audio.default-backend
199
+ first when it can play the URI.
200
+ """
201
+ backends = (base_config or {}).get("backends", {}) or {}
202
+ mine = [(name, conf) for name, conf in backends.items()
203
+ if isinstance(conf, dict) and conf.get("type") == BACKEND_TYPE
204
+ and conf.get("active", True)]
205
+ if not mine:
206
+ mine = [("browser", {"type": BACKEND_TYPE, "active": True})]
207
+ return [BrowserAudioBackend(conf, bus, name) for name, conf in mine]
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: ovos-audio-plugin-browser
3
+ Version: 0.1.0a1
4
+ Summary: OpenVoiceOS audio backend: plays music, radio and podcasts in a browser's <audio> element, over the messagebus
5
+ Author: Andreas Lorensen
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/emkay-voice/ovos-audio-plugin-browser
8
+ Project-URL: Issues, https://github.com/emkay-voice/ovos-audio-plugin-browser/issues
9
+ Project-URL: Emkay, https://github.com/emkay-voice/emkay
10
+ Keywords: ovos,openvoiceos,plugin,audio,audioservice,ocp,media,radio,browser,pyodide,emkay
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Environment :: WebAssembly :: Emscripten
15
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Players
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: ovos-plugin-manager>=0.0.26
20
+ Requires-Dist: ovos-bus-client>=0.0.8
21
+ Requires-Dist: ovos-utils>=0.0.38
22
+ Provides-Extra: test
23
+ Requires-Dist: pytest; extra == "test"
24
+ Dynamic: license-file
25
+
26
+ # ovos-audio-plugin-browser
27
+
28
+ An [OpenVoiceOS](https://openvoiceos.org) audio backend that plays music,
29
+ internet radio and podcasts in a **browser's `<audio>` element**, over the
30
+ messagebus.
31
+
32
+ It was made for [Emkay](https://github.com/emkay-voice/emkay), OpenVoiceOS in
33
+ the browser (Pyodide), where it is the player behind ovos-audio's classic
34
+ `AudioService`. There it takes the place of
35
+ [ovos-audio-plugin-mpv](https://github.com/OpenVoiceOS/ovos-audio-plugin-mpv)
36
+ and vlc, which start a program on the device, which a browser cannot do.
37
+
38
+ ## How it works
39
+
40
+ ovos-audio's `AudioService` (the `mycroft.audio.service.*` API that OCP uses
41
+ in legacy mode, and that skills reach through `AudioServiceInterface`) picks
42
+ a backend for each URI and tells it to play, pause, seek and so on. This
43
+ backend does not play anything itself: it hands each command to the page as
44
+ a bus message, and the page answers with what its player did.
45
+
46
+ So it never touches a browser API, and the same backend works
47
+
48
+ - in Emkay, where OVOS runs in a Web Worker and the page answers
49
+ ([`web/media.js`](https://github.com/emkay-voice/emkay/blob/main/web/media.js)),
50
+ - on a normal OVOS device, with a browser connected to its messagebus
51
+ websocket as the speaker.
52
+
53
+ Playlists, repeat, ducking while OVOS speaks or listens
54
+ (`ovos.audio.output.started`/`ended`, `recognizer_loop:record_begin`/`end`)
55
+ and the OCP status messages are handled by `AudioService` and OPM's
56
+ `AudioBackend` template, the same as for any other backend.
57
+
58
+ ## Install and configure
59
+
60
+ ```bash
61
+ pip install ovos-audio-plugin-browser
62
+ ```
63
+
64
+ ```json
65
+ {
66
+ "Audio": {
67
+ "default-backend": "browser",
68
+ "backends": {
69
+ "browser": {"type": "ovos_audio_browser", "active": true, "duck_factor": 0.3}
70
+ }
71
+ },
72
+ "intents": {
73
+ "ovos-ocp-pipeline-plugin": {"legacy": true}
74
+ }
75
+ }
76
+ ```
77
+
78
+ - `duck_factor`: the music's volume while OVOS speaks or listens, 0..1.
79
+ - Without a `backends` entry of this type, one called `browser` is made, so
80
+ installing the plugin is enough; set `default-backend` to make it the
81
+ first choice.
82
+ - `"legacy": true` makes OCP play through `AudioService` (and this backend)
83
+ instead of waiting for ovos-media.
84
+
85
+ ## The protocol
86
+
87
+ To the page, one track at a time:
88
+
89
+ | message | data |
90
+ |-------------------------------|----------------------------|
91
+ | `ovos.audio.browser.play` | `uri`, `position_ms` |
92
+ | `ovos.audio.browser.pause` | |
93
+ | `ovos.audio.browser.resume` | |
94
+ | `ovos.audio.browser.stop` | |
95
+ | `ovos.audio.browser.seek` | `position_ms` |
96
+ | `ovos.audio.browser.volume` | `ducked` (bool), `factor` (0..1) |
97
+
98
+ From the page, whenever something happens, and every few seconds while
99
+ playing:
100
+
101
+ | message | data |
102
+ |-------------------------------|------|
103
+ | `ovos.audio.browser.state` | `uri`, `state` (`playing`, `paused`, `ended`, `error`), `position_ms`, `length_ms` (0 for a live stream), `error` (a plain reason) |
104
+
105
+ On `ended` the backend goes on with the next track (or starts over with
106
+ repeat) and at the end of the list `AudioService` reports
107
+ `mycroft.audio.queue_end`. On `error` it reports the error to OCP the same
108
+ way.
109
+
110
+ A page that answers should play the stream in an `<audio>` element, not
111
+ through Web Audio: `<audio>` plays a stream from another site without that
112
+ site's CORS permission, while a Web Audio graph turns such a stream silent.
113
+
114
+ ## Limits
115
+
116
+ - **https pages cannot play `http://` streams.** Browsers block this "mixed
117
+ content". Many internet radio stations have an https address; those
118
+ that do not fail with a clear reason, and OCP moves on to its next result.
119
+ - **Formats** are whatever the browser plays: mp3, aac, ogg/opus, and HLS
120
+ in Safari. YouTube and the like need a stream extractor in OCP, which
121
+ needs a site's permission to read it from a browser.
122
+ - The backend uses ovos-audio's classic audio service (`mycroft.plugin.audioservice`),
123
+ which OPM marks as deprecated in favour of ovos-media. It is what OCP's
124
+ legacy mode uses today; an ovos-media plugin can follow when Emkay moves.
125
+
126
+ ## License
127
+
128
+ Apache-2.0
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ ovos_audio_plugin_browser/__init__.py
5
+ ovos_audio_plugin_browser.egg-info/PKG-INFO
6
+ ovos_audio_plugin_browser.egg-info/SOURCES.txt
7
+ ovos_audio_plugin_browser.egg-info/dependency_links.txt
8
+ ovos_audio_plugin_browser.egg-info/entry_points.txt
9
+ ovos_audio_plugin_browser.egg-info/requires.txt
10
+ ovos_audio_plugin_browser.egg-info/top_level.txt
11
+ tests/test_audioservice.py
12
+ tests/test_backend.py
@@ -0,0 +1,2 @@
1
+ [mycroft.plugin.audioservice]
2
+ ovos_audio_browser = ovos_audio_plugin_browser
@@ -0,0 +1,6 @@
1
+ ovos-plugin-manager>=0.0.26
2
+ ovos-bus-client>=0.0.8
3
+ ovos-utils>=0.0.38
4
+
5
+ [test]
6
+ pytest
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ovos-audio-plugin-browser"
7
+ version = "0.1.0a1"
8
+ description = "OpenVoiceOS audio backend: plays music, radio and podcasts in a browser's <audio> element, over the messagebus"
9
+ readme = "README.md"
10
+ license = {text = "Apache-2.0"}
11
+ authors = [{name = "Andreas Lorensen"}]
12
+ requires-python = ">=3.10"
13
+ keywords = ["ovos", "openvoiceos", "plugin", "audio", "audioservice", "ocp", "media", "radio", "browser", "pyodide", "emkay"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "License :: OSI Approved :: Apache Software License",
17
+ "Programming Language :: Python :: 3",
18
+ "Environment :: WebAssembly :: Emscripten",
19
+ "Topic :: Multimedia :: Sound/Audio :: Players",
20
+ ]
21
+ dependencies = [
22
+ "ovos-plugin-manager>=0.0.26",
23
+ "ovos-bus-client>=0.0.8",
24
+ "ovos-utils>=0.0.38",
25
+ ]
26
+
27
+ [project.optional-dependencies]
28
+ test = ["pytest"]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/emkay-voice/ovos-audio-plugin-browser"
32
+ Issues = "https://github.com/emkay-voice/ovos-audio-plugin-browser/issues"
33
+ Emkay = "https://github.com/emkay-voice/emkay"
34
+
35
+ # ovos-audio's classic AudioService finds its backends here
36
+ [project.entry-points."mycroft.plugin.audioservice"]
37
+ ovos_audio_browser = "ovos_audio_plugin_browser"
38
+
39
+ [tool.setuptools]
40
+ packages = ["ovos_audio_plugin_browser"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,37 @@
1
+ """With ovos-audio's own AudioService: found, chosen, ducked, stopped."""
2
+ import time
3
+
4
+ import pytest
5
+ from ovos_bus_client.message import Message
6
+ from ovos_utils.fakebus import FakeBus
7
+
8
+ AudioService = pytest.importorskip("ovos_audio.audio").AudioService
9
+ try:
10
+ from ovos_spec_tools import SpecMessage
11
+ SPEAKING = SpecMessage.AUDIO_OUTPUT_STARTED
12
+ except ImportError:
13
+ SPEAKING = "recognizer_loop:audio_output_start"
14
+
15
+
16
+ def test_audioservice_plays_through_the_page():
17
+ bus = FakeBus()
18
+ seen = []
19
+ bus.on("message", lambda m: seen.append(Message.deserialize(m) if isinstance(m, str) else m))
20
+ service = AudioService(bus, disable_ocp=True)
21
+ assert "browser" in [s.name for s in service.service]
22
+
23
+ bus.emit(Message("mycroft.audio.service.play", {"tracks": ["https://radio.example/live.mp3"]}))
24
+ bus.emit(Message("ovos.audio.browser.state", {"state": "playing", "position_ms": 0}))
25
+ bus.emit(Message(SPEAKING))
26
+ time.sleep(1.1) # AudioService ignores a stop within 1 s of play
27
+ bus.emit(Message("mycroft.audio.service.stop"))
28
+
29
+ types = [m.msg_type for m in seen]
30
+ plays = [m for m in seen if m.msg_type == "ovos.audio.browser.play"]
31
+ assert plays and plays[0].data["uri"] == "https://radio.example/live.mp3"
32
+ assert "mycroft.audio.playing_track" in types
33
+ ducks = [m.data for m in seen if m.msg_type == "ovos.audio.browser.volume"]
34
+ assert {"ducked": True, "factor": 0.3} in ducks
35
+ assert "ovos.audio.browser.stop" in types
36
+ assert "mycroft.stop.handled" in types
37
+ service.shutdown()
@@ -0,0 +1,99 @@
1
+ """The backend against a FakeBus, with a pretend page answering it."""
2
+ from ovos_bus_client.message import Message
3
+ from ovos_utils.fakebus import FakeBus
4
+
5
+ import ovos_audio_plugin_browser as plugin
6
+
7
+
8
+ def make():
9
+ bus = FakeBus()
10
+ sent = []
11
+ bus.on("message", lambda raw: sent.append(Message.deserialize(raw)
12
+ if isinstance(raw, str) else raw))
13
+ (backend,) = plugin.load_service({}, bus)
14
+ started = []
15
+ backend.set_track_start_callback(started.append)
16
+ return bus, backend, sent, started
17
+
18
+
19
+ def page(bus, **data):
20
+ bus.emit(Message(plugin.STATE, data))
21
+
22
+
23
+ def of(sent, msg_type):
24
+ return [m for m in sent if m.msg_type == msg_type]
25
+
26
+
27
+ def test_default_backend_without_config():
28
+ bus = FakeBus()
29
+ (b,) = plugin.load_service({}, bus)
30
+ assert b.name == "browser"
31
+ assert "https" in b.supported_uris()
32
+
33
+
34
+ def test_config_names_the_backends():
35
+ conf = {"backends": {"tab": {"type": plugin.BACKEND_TYPE, "active": True},
36
+ "off": {"type": plugin.BACKEND_TYPE, "active": False},
37
+ "mpv": {"type": "ovos_mpv"}}}
38
+ names = [b.name for b in plugin.load_service(conf, FakeBus())]
39
+ assert names == ["tab"]
40
+
41
+
42
+ def test_play_start_and_end():
43
+ bus, b, sent, started = make()
44
+ b.add_list(["https://radio.example/stream.mp3"])
45
+ b.play()
46
+ assert of(sent, plugin.PLAY)[-1].data["uri"] == "https://radio.example/stream.mp3"
47
+ page(bus, state="playing", position_ms=0)
48
+ assert started == ["https://radio.example/stream.mp3"]
49
+ page(bus, state="ended", position_ms=1000)
50
+ assert started[-1] is None # end of the queue
51
+
52
+
53
+ def test_playlist_goes_on_and_repeats():
54
+ bus, b, sent, started = make()
55
+ b.add_list(["https://a.example/1.mp3", "https://a.example/2.mp3"])
56
+ b.play(repeat=True)
57
+ page(bus, state="playing")
58
+ page(bus, state="ended")
59
+ assert of(sent, plugin.PLAY)[-1].data["uri"].endswith("2.mp3")
60
+ page(bus, state="playing")
61
+ page(bus, state="ended")
62
+ assert of(sent, plugin.PLAY)[-1].data["uri"].endswith("1.mp3") # repeat
63
+
64
+
65
+ def test_error_ends_the_queue():
66
+ bus, b, sent, started = make()
67
+ b.add_list(["http://insecure.example/stream"])
68
+ b.play()
69
+ page(bus, state="error", error="mixed content")
70
+ assert started == [None]
71
+ assert b.stop() is False # nothing playing any more
72
+
73
+
74
+ def test_pause_resume_seek_and_duck():
75
+ bus, b, sent, started = make()
76
+ b.add_list(["https://a.example/1.mp3"])
77
+ b.play()
78
+ page(bus, state="playing", position_ms=5000, length_ms=60000)
79
+ b.pause()
80
+ assert of(sent, plugin.PAUSE)
81
+ assert 5000 <= b.get_track_position() < 6000
82
+ b.resume()
83
+ assert of(sent, plugin.RESUME)
84
+ b.set_track_position(90000)
85
+ assert of(sent, plugin.SEEK)[-1].data["position_ms"] == 60000 # kept in the track
86
+ b.lower_volume()
87
+ assert of(sent, plugin.VOLUME)[-1].data == {"ducked": True, "factor": 0.3}
88
+ b.restore_volume()
89
+ assert of(sent, plugin.VOLUME)[-1].data["ducked"] is False
90
+ assert b.stop() is True
91
+
92
+
93
+ def test_late_report_after_stop_is_ignored():
94
+ bus, b, sent, started = make()
95
+ b.add_list(["https://a.example/1.mp3"])
96
+ b.play()
97
+ b.stop()
98
+ page(bus, state="playing")
99
+ assert started == []