2019-02-05 04:59:03 +01:00
|
|
|
# Copyright: Ankitects Pty Ltd and contributors
|
2012-12-21 08:51:59 +01:00
|
|
|
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|
|
|
|
2019-12-20 10:19:03 +01:00
|
|
|
import atexit
|
|
|
|
import os
|
2020-01-21 05:47:03 +01:00
|
|
|
import re
|
2019-12-20 10:19:03 +01:00
|
|
|
import subprocess
|
|
|
|
import sys
|
|
|
|
import threading
|
|
|
|
import time
|
2020-01-20 10:52:58 +01:00
|
|
|
import wave
|
|
|
|
from abc import ABC, abstractmethod
|
2020-01-20 22:28:19 +01:00
|
|
|
from concurrent.futures import Future
|
2020-01-21 11:39:25 +01:00
|
|
|
from operator import itemgetter
|
2020-01-21 02:34:16 +01:00
|
|
|
from typing import Any, Callable, Dict, List, Optional, Tuple
|
2019-12-19 04:02:45 +01:00
|
|
|
|
2020-01-20 10:21:24 +01:00
|
|
|
import pyaudio
|
2020-01-20 10:52:58 +01:00
|
|
|
|
2020-01-20 13:01:38 +01:00
|
|
|
import aqt
|
2020-01-24 02:06:11 +01:00
|
|
|
from anki.cards import Card
|
2019-03-04 02:22:40 +01:00
|
|
|
from anki.lang import _
|
2020-01-24 06:48:40 +01:00
|
|
|
from anki.sound import AV_REF_RE, AVTag, SoundOrVideoTag
|
2020-01-20 23:55:15 +01:00
|
|
|
from anki.utils import isLin, isMac, isWin
|
2020-01-13 05:38:05 +01:00
|
|
|
from aqt import gui_hooks
|
2020-01-02 10:43:19 +01:00
|
|
|
from aqt.mpv import MPV, MPVBase
|
|
|
|
from aqt.qt import *
|
2020-01-20 10:52:58 +01:00
|
|
|
from aqt.taskman import TaskManager
|
2020-01-23 07:10:41 +01:00
|
|
|
from aqt.utils import restoreGeom, saveGeom, startup_info
|
2020-01-20 10:52:58 +01:00
|
|
|
|
|
|
|
# AV player protocol
|
|
|
|
##########################################################################
|
|
|
|
|
|
|
|
OnDoneCallback = Callable[[], None]
|
|
|
|
|
|
|
|
|
|
|
|
class Player(ABC):
|
|
|
|
@abstractmethod
|
2020-01-21 02:34:16 +01:00
|
|
|
def play(self, tag: AVTag, on_done: OnDoneCallback) -> None:
|
2020-01-22 05:39:18 +01:00
|
|
|
"""Play a file.
|
|
|
|
|
|
|
|
When reimplementing, make sure to call
|
|
|
|
gui_hooks.av_player_did_begin_playing(self, tag)
|
|
|
|
on the main thread after playback begins.
|
|
|
|
"""
|
2020-01-02 10:43:19 +01:00
|
|
|
|
2020-01-20 10:52:58 +01:00
|
|
|
@abstractmethod
|
2020-01-21 02:34:16 +01:00
|
|
|
def rank_for_tag(self, tag: AVTag) -> Optional[int]:
|
|
|
|
"""How suited this player is to playing tag.
|
|
|
|
|
|
|
|
AVPlayer will choose the player that returns the highest rank
|
|
|
|
for a given tag.
|
|
|
|
|
|
|
|
If None, this player can not play the tag.
|
|
|
|
"""
|
2020-01-02 10:43:19 +01:00
|
|
|
|
2020-01-20 10:52:58 +01:00
|
|
|
def stop(self) -> None:
|
2020-01-20 22:28:19 +01:00
|
|
|
"""Optional.
|
|
|
|
|
|
|
|
If implemented, the player must not call on_done() when the audio is stopped."""
|
2020-01-02 10:43:19 +01:00
|
|
|
|
2020-01-20 23:55:15 +01:00
|
|
|
def seek_relative(self, secs: int) -> None:
|
|
|
|
"Jump forward or back by secs. Optional."
|
|
|
|
|
|
|
|
def toggle_pause(self) -> None:
|
|
|
|
"Optional."
|
|
|
|
|
|
|
|
def shutdown(self) -> None:
|
|
|
|
"Do any cleanup required at program termination. Optional."
|
|
|
|
|
2020-01-02 10:43:19 +01:00
|
|
|
|
2020-01-20 10:52:58 +01:00
|
|
|
class SoundOrVideoPlayer(Player): # pylint: disable=abstract-method
|
2020-01-21 02:34:16 +01:00
|
|
|
default_rank = 0
|
|
|
|
|
|
|
|
def rank_for_tag(self, tag: AVTag) -> Optional[int]:
|
|
|
|
if isinstance(tag, SoundOrVideoTag):
|
|
|
|
return self.default_rank
|
|
|
|
else:
|
|
|
|
return None
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2020-01-20 10:52:58 +01:00
|
|
|
|
|
|
|
# Main playing interface
|
2012-12-21 08:51:59 +01:00
|
|
|
##########################################################################
|
|
|
|
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2020-01-20 10:52:58 +01:00
|
|
|
class AVPlayer:
|
|
|
|
players: List[Player] = []
|
2020-01-20 21:45:32 +01:00
|
|
|
# when a new batch of audio is played, shoud the currently playing
|
|
|
|
# audio be stopped?
|
|
|
|
interrupt_current_audio = True
|
2020-01-20 10:52:58 +01:00
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self._enqueued: List[AVTag] = []
|
2020-01-20 23:55:15 +01:00
|
|
|
self.current_player: Optional[Player] = None
|
2020-01-20 10:52:58 +01:00
|
|
|
|
|
|
|
def play_tags(self, tags: List[AVTag]) -> None:
|
|
|
|
"""Clear the existing queue, then start playing provided tags."""
|
2020-01-21 05:43:33 +01:00
|
|
|
self._enqueued = tags[:]
|
2020-02-25 08:49:06 +01:00
|
|
|
self.maybe_interrupt()
|
2020-01-20 10:52:58 +01:00
|
|
|
self._play_next_if_idle()
|
|
|
|
|
|
|
|
def stop_and_clear_queue(self) -> None:
|
|
|
|
self._enqueued = []
|
|
|
|
self._stop_if_playing()
|
|
|
|
|
2020-02-25 08:49:06 +01:00
|
|
|
def maybe_interrupt(self) -> None:
|
|
|
|
if self.interrupt_current_audio:
|
|
|
|
self._stop_if_playing()
|
|
|
|
|
2020-01-20 10:52:58 +01:00
|
|
|
def play_file(self, filename: str) -> None:
|
|
|
|
self.play_tags([SoundOrVideoTag(filename=filename)])
|
|
|
|
|
2020-01-21 04:21:43 +01:00
|
|
|
def insert_file(self, filename: str) -> None:
|
|
|
|
self._enqueued.insert(0, SoundOrVideoTag(filename=filename))
|
|
|
|
self._play_next_if_idle()
|
|
|
|
|
2020-01-20 23:55:15 +01:00
|
|
|
def toggle_pause(self):
|
|
|
|
if self.current_player:
|
|
|
|
self.current_player.toggle_pause()
|
|
|
|
|
|
|
|
def seek_relative(self, secs: int) -> None:
|
|
|
|
if self.current_player:
|
|
|
|
self.current_player.seek_relative(secs)
|
|
|
|
|
|
|
|
def shutdown(self) -> None:
|
|
|
|
self.stop_and_clear_queue()
|
|
|
|
for player in self.players:
|
|
|
|
player.shutdown()
|
|
|
|
|
2020-01-20 10:52:58 +01:00
|
|
|
def _stop_if_playing(self) -> None:
|
2020-01-20 23:55:15 +01:00
|
|
|
if self.current_player:
|
|
|
|
self.current_player.stop()
|
|
|
|
self.current_player = None
|
2020-01-20 10:52:58 +01:00
|
|
|
|
|
|
|
def _pop_next(self) -> Optional[AVTag]:
|
|
|
|
if not self._enqueued:
|
|
|
|
return None
|
|
|
|
return self._enqueued.pop(0)
|
|
|
|
|
|
|
|
def _on_play_finished(self) -> None:
|
2020-01-22 05:39:18 +01:00
|
|
|
gui_hooks.av_player_did_end_playing(self.current_player)
|
2020-01-20 23:55:15 +01:00
|
|
|
self.current_player = None
|
2020-01-20 10:52:58 +01:00
|
|
|
self._play_next_if_idle()
|
|
|
|
|
|
|
|
def _play_next_if_idle(self) -> None:
|
2020-01-20 23:55:15 +01:00
|
|
|
if self.current_player:
|
2020-01-20 10:52:58 +01:00
|
|
|
return
|
|
|
|
|
|
|
|
next = self._pop_next()
|
|
|
|
if next is not None:
|
|
|
|
self._play(next)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2020-01-20 10:52:58 +01:00
|
|
|
def _play(self, tag: AVTag) -> None:
|
2020-01-21 02:34:16 +01:00
|
|
|
best_player = self._best_player_for_tag(tag)
|
|
|
|
if best_player:
|
|
|
|
self.current_player = best_player
|
|
|
|
gui_hooks.av_player_will_play(tag)
|
|
|
|
self.current_player.play(tag, self._on_play_finished)
|
|
|
|
else:
|
|
|
|
print("no players found for", tag)
|
|
|
|
|
|
|
|
def _best_player_for_tag(self, tag: AVTag) -> Optional[Player]:
|
|
|
|
ranked = []
|
|
|
|
for p in self.players:
|
|
|
|
rank = p.rank_for_tag(tag)
|
|
|
|
if rank is not None:
|
|
|
|
ranked.append((rank, p))
|
|
|
|
|
2020-01-21 09:32:53 +01:00
|
|
|
ranked.sort(key=itemgetter(0))
|
2020-01-21 02:34:16 +01:00
|
|
|
|
|
|
|
if ranked:
|
|
|
|
return ranked[-1][1]
|
|
|
|
else:
|
|
|
|
return None
|
2020-01-20 10:52:58 +01:00
|
|
|
|
|
|
|
|
|
|
|
av_player = AVPlayer()
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2016-07-26 04:15:43 +02:00
|
|
|
# Packaged commands
|
|
|
|
##########################################################################
|
|
|
|
|
|
|
|
# return modified command array that points to bundled command, and return
|
|
|
|
# required environment
|
2019-12-19 04:02:45 +01:00
|
|
|
def _packagedCmd(cmd) -> Tuple[Any, Dict[str, str]]:
|
2016-07-26 04:15:43 +02:00
|
|
|
cmd = cmd[:]
|
|
|
|
env = os.environ.copy()
|
2017-05-22 07:40:04 +02:00
|
|
|
if "LD_LIBRARY_PATH" in env:
|
2019-12-23 01:34:10 +01:00
|
|
|
del env["LD_LIBRARY_PATH"]
|
2016-07-26 04:15:43 +02:00
|
|
|
if isMac:
|
|
|
|
dir = os.path.dirname(os.path.abspath(__file__))
|
2017-01-09 03:52:52 +01:00
|
|
|
exeDir = os.path.abspath(dir + "/../../Resources/audio")
|
2016-07-26 04:15:43 +02:00
|
|
|
else:
|
|
|
|
exeDir = os.path.dirname(os.path.abspath(sys.argv[0]))
|
|
|
|
if isWin and not cmd[0].endswith(".exe"):
|
|
|
|
cmd[0] += ".exe"
|
|
|
|
path = os.path.join(exeDir, cmd[0])
|
|
|
|
if not os.path.exists(path):
|
|
|
|
return cmd, env
|
|
|
|
cmd[0] = path
|
|
|
|
return cmd, env
|
|
|
|
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2020-01-23 07:10:41 +01:00
|
|
|
# Platform hacks
|
|
|
|
##########################################################################
|
|
|
|
|
|
|
|
# legacy global for add-ons
|
|
|
|
si = startup_info()
|
|
|
|
|
|
|
|
# osx throws interrupted system call errors frequently
|
|
|
|
def retryWait(proc) -> Any:
|
|
|
|
while 1:
|
|
|
|
try:
|
|
|
|
return proc.wait()
|
|
|
|
except OSError:
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
2020-01-20 10:52:58 +01:00
|
|
|
# Simple player implementations
|
|
|
|
##########################################################################
|
|
|
|
|
|
|
|
|
2020-01-20 22:28:19 +01:00
|
|
|
class PlayerInterrupted(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2020-01-21 02:34:16 +01:00
|
|
|
class SimpleProcessPlayer(Player): # pylint: disable=abstract-method
|
|
|
|
"A player that invokes a new process for each tag to play."
|
2020-01-20 10:52:58 +01:00
|
|
|
|
|
|
|
args: List[str] = []
|
|
|
|
env: Optional[Dict[str, str]] = None
|
|
|
|
|
2020-01-20 21:49:09 +01:00
|
|
|
def __init__(self, taskman: TaskManager):
|
|
|
|
self._taskman = taskman
|
2020-01-21 02:34:16 +01:00
|
|
|
self._terminate_flag = False
|
|
|
|
self._process: Optional[subprocess.Popen] = None
|
2020-02-21 06:14:09 +01:00
|
|
|
self._lock = threading.Lock()
|
2020-01-20 21:49:09 +01:00
|
|
|
|
2020-01-20 10:52:58 +01:00
|
|
|
def play(self, tag: AVTag, on_done: OnDoneCallback) -> None:
|
2020-01-22 05:09:51 +01:00
|
|
|
self._taskman.run_in_background(
|
2020-01-21 02:34:16 +01:00
|
|
|
lambda: self._play(tag), lambda res: self._on_done(res, on_done)
|
2020-01-20 22:28:19 +01:00
|
|
|
)
|
2020-01-20 10:52:58 +01:00
|
|
|
|
|
|
|
def stop(self):
|
|
|
|
self._terminate_flag = True
|
2020-01-20 22:28:19 +01:00
|
|
|
# block until stopped
|
2020-01-21 02:34:16 +01:00
|
|
|
t = time.time()
|
2020-02-21 06:14:09 +01:00
|
|
|
while self._terminate_flag and time.time() - t < 3:
|
2020-01-20 22:28:19 +01:00
|
|
|
time.sleep(0.1)
|
2020-01-20 10:52:58 +01:00
|
|
|
|
2020-01-21 02:34:16 +01:00
|
|
|
def _play(self, tag: AVTag) -> None:
|
|
|
|
assert isinstance(tag, SoundOrVideoTag)
|
2020-01-23 07:10:41 +01:00
|
|
|
self._process = subprocess.Popen(
|
|
|
|
self.args + [tag.filename], env=self.env, startupinfo=startup_info()
|
|
|
|
)
|
2020-01-22 05:39:18 +01:00
|
|
|
self._wait_for_termination(tag)
|
|
|
|
|
|
|
|
def _wait_for_termination(self, tag: AVTag):
|
|
|
|
self._taskman.run_on_main(
|
|
|
|
lambda: gui_hooks.av_player_did_begin_playing(self, tag)
|
|
|
|
)
|
2020-01-21 02:34:16 +01:00
|
|
|
|
2020-02-21 06:14:09 +01:00
|
|
|
while True:
|
|
|
|
with self._lock:
|
|
|
|
# if .stop() timed out, another thread may run when
|
|
|
|
# there is no process
|
|
|
|
if not self._process:
|
|
|
|
self._process = None
|
|
|
|
self._terminate_flag = False
|
|
|
|
return
|
|
|
|
|
|
|
|
# should we abort playing?
|
|
|
|
if self._terminate_flag:
|
|
|
|
self._process.terminate()
|
|
|
|
self._process = None
|
|
|
|
self._terminate_flag = False
|
|
|
|
raise PlayerInterrupted()
|
|
|
|
|
|
|
|
# wait for completion
|
2020-01-21 02:34:16 +01:00
|
|
|
try:
|
|
|
|
self._process.wait(0.1)
|
|
|
|
if self._process.returncode != 0:
|
|
|
|
print(f"player got return code: {self._process.returncode}")
|
2020-02-21 06:14:09 +01:00
|
|
|
self._process = None
|
|
|
|
self._terminate_flag = False
|
2020-01-21 02:34:16 +01:00
|
|
|
return
|
|
|
|
except subprocess.TimeoutExpired:
|
|
|
|
pass
|
2020-01-20 22:28:19 +01:00
|
|
|
|
|
|
|
def _on_done(self, ret: Future, cb: OnDoneCallback) -> None:
|
|
|
|
try:
|
|
|
|
ret.result()
|
|
|
|
except PlayerInterrupted:
|
|
|
|
# don't fire done callback when interrupted
|
|
|
|
return
|
|
|
|
cb()
|
2020-01-20 10:52:58 +01:00
|
|
|
|
|
|
|
|
2020-01-21 02:34:16 +01:00
|
|
|
class SimpleMpvPlayer(SimpleProcessPlayer, SoundOrVideoPlayer):
|
2020-01-20 10:52:58 +01:00
|
|
|
args, env = _packagedCmd(
|
|
|
|
[
|
|
|
|
"mpv",
|
|
|
|
"--no-terminal",
|
|
|
|
"--force-window=no",
|
|
|
|
"--ontop",
|
|
|
|
"--audio-display=no",
|
|
|
|
"--keep-open=no",
|
|
|
|
"--input-media-keys=no",
|
|
|
|
"--no-config",
|
|
|
|
]
|
|
|
|
)
|
|
|
|
|
2020-01-20 21:49:09 +01:00
|
|
|
def __init__(self, taskman: TaskManager, base_folder: str) -> None:
|
|
|
|
super().__init__(taskman)
|
2020-01-20 13:01:38 +01:00
|
|
|
conf_path = os.path.join(base_folder, "mpv.conf")
|
2020-01-21 10:29:50 +01:00
|
|
|
self.args += ["--include=" + conf_path]
|
2020-01-20 13:01:38 +01:00
|
|
|
|
2020-01-20 10:52:58 +01:00
|
|
|
|
2020-01-21 02:34:16 +01:00
|
|
|
class SimpleMplayerPlayer(SimpleProcessPlayer, SoundOrVideoPlayer):
|
2020-01-20 10:52:58 +01:00
|
|
|
args, env = _packagedCmd(["mplayer", "-really-quiet", "-noautosub"])
|
|
|
|
if isWin:
|
|
|
|
args += ["-ao", "win32"]
|
|
|
|
|
|
|
|
|
2017-09-30 09:24:56 +02:00
|
|
|
# MPV
|
2012-12-21 08:51:59 +01:00
|
|
|
##########################################################################
|
|
|
|
|
2017-09-30 09:24:56 +02:00
|
|
|
|
2020-01-20 13:01:38 +01:00
|
|
|
class MpvManager(MPV, SoundOrVideoPlayer):
|
2017-10-02 08:37:52 +02:00
|
|
|
|
2018-01-21 01:34:29 +01:00
|
|
|
if not isLin:
|
|
|
|
default_argv = MPVBase.default_argv + [
|
|
|
|
"--input-media-keys=no",
|
|
|
|
]
|
|
|
|
|
2020-01-20 13:01:38 +01:00
|
|
|
def __init__(self, base_path: str) -> None:
|
|
|
|
mpvPath, self.popenEnv = _packagedCmd(["mpv"])
|
|
|
|
self.executable = mpvPath[0]
|
|
|
|
self._on_done: Optional[OnDoneCallback] = None
|
|
|
|
conf_path = os.path.join(base_path, "mpv.conf")
|
|
|
|
self.default_argv += ["--no-config", "--include=" + conf_path]
|
2020-01-23 22:06:59 +01:00
|
|
|
super().__init__(window_id=None, debug=False)
|
2017-09-30 09:24:56 +02:00
|
|
|
|
2020-01-20 13:01:38 +01:00
|
|
|
def play(self, tag: AVTag, on_done: OnDoneCallback) -> None:
|
2020-01-21 02:34:16 +01:00
|
|
|
assert isinstance(tag, SoundOrVideoTag)
|
2020-01-20 13:01:38 +01:00
|
|
|
self._on_done = on_done
|
2020-01-21 02:34:16 +01:00
|
|
|
path = os.path.join(os.getcwd(), tag.filename)
|
2017-11-10 10:52:20 +01:00
|
|
|
self.command("loadfile", path, "append-play")
|
2020-01-22 05:39:18 +01:00
|
|
|
gui_hooks.av_player_did_begin_playing(self, tag)
|
2017-09-30 09:24:56 +02:00
|
|
|
|
2020-01-20 21:45:32 +01:00
|
|
|
def stop(self) -> None:
|
|
|
|
self.command("stop")
|
|
|
|
|
2020-01-20 23:55:15 +01:00
|
|
|
def toggle_pause(self) -> None:
|
2017-09-30 09:24:56 +02:00
|
|
|
self.set_property("pause", not self.get_property("pause"))
|
|
|
|
|
2020-01-20 23:55:15 +01:00
|
|
|
def seek_relative(self, secs) -> None:
|
2017-09-30 09:24:56 +02:00
|
|
|
self.command("seek", secs, "relative")
|
|
|
|
|
2019-12-19 04:02:45 +01:00
|
|
|
def on_idle(self) -> None:
|
2020-01-20 13:01:38 +01:00
|
|
|
if self._on_done:
|
|
|
|
self._on_done()
|
2018-04-30 09:12:26 +02:00
|
|
|
|
2020-01-20 23:55:15 +01:00
|
|
|
def shutdown(self) -> None:
|
|
|
|
self.close()
|
|
|
|
|
2020-01-20 13:01:38 +01:00
|
|
|
# Legacy, not used
|
|
|
|
##################################################
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2020-01-20 23:55:15 +01:00
|
|
|
togglePause = toggle_pause
|
|
|
|
seekRelative = seek_relative
|
|
|
|
|
2020-01-20 13:01:38 +01:00
|
|
|
def queueFile(self, file: str) -> None:
|
2020-01-20 23:55:15 +01:00
|
|
|
return
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2020-01-20 13:01:38 +01:00
|
|
|
def clearQueue(self) -> None:
|
2020-01-20 23:55:15 +01:00
|
|
|
return
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
# Mplayer in slave mode
|
|
|
|
##########################################################################
|
|
|
|
|
2019-02-06 00:03:39 +01:00
|
|
|
|
2020-01-20 23:55:15 +01:00
|
|
|
class SimpleMplayerSlaveModePlayer(SimpleMplayerPlayer):
|
|
|
|
def __init__(self, taskman: TaskManager):
|
|
|
|
super().__init__(taskman)
|
|
|
|
self.args.append("-slave")
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2020-01-21 02:34:16 +01:00
|
|
|
def _play(self, tag: AVTag) -> None:
|
|
|
|
assert isinstance(tag, SoundOrVideoTag)
|
2020-01-20 23:55:15 +01:00
|
|
|
self._process = subprocess.Popen(
|
2020-01-23 07:10:41 +01:00
|
|
|
self.args + [tag.filename],
|
|
|
|
env=self.env,
|
|
|
|
stdin=subprocess.PIPE,
|
|
|
|
startupinfo=startup_info(),
|
2020-01-20 23:55:15 +01:00
|
|
|
)
|
2020-01-22 05:39:18 +01:00
|
|
|
self._wait_for_termination(tag)
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2020-01-22 05:11:25 +01:00
|
|
|
def command(self, *args) -> None:
|
2020-01-20 23:55:15 +01:00
|
|
|
"""Send a command over the slave interface.
|
2019-12-20 06:07:40 +01:00
|
|
|
|
2020-01-20 23:55:15 +01:00
|
|
|
The trailing newline is automatically added."""
|
2020-01-22 05:11:25 +01:00
|
|
|
str_args = [str(x) for x in args]
|
|
|
|
self._process.stdin.write(" ".join(str_args).encode("utf8") + b"\n")
|
2020-01-20 23:55:15 +01:00
|
|
|
self._process.stdin.flush()
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2020-01-20 23:55:15 +01:00
|
|
|
def seek_relative(self, secs: int) -> None:
|
2020-01-22 05:11:25 +01:00
|
|
|
self.command("seek", secs, 0)
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2020-01-20 23:55:15 +01:00
|
|
|
def toggle_pause(self):
|
|
|
|
self.command("pause")
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
|
|
|
|
# PyAudio recording
|
|
|
|
##########################################################################
|
|
|
|
|
2014-04-17 21:17:05 +02:00
|
|
|
|
2020-01-20 10:21:24 +01:00
|
|
|
PYAU_FORMAT = pyaudio.paInt16
|
|
|
|
PYAU_CHANNELS = 1
|
|
|
|
PYAU_INPUT_INDEX: Optional[int] = None
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2020-01-20 12:03:22 +01:00
|
|
|
processingSrc = "rec.wav"
|
|
|
|
processingDst = "rec.mp3"
|
|
|
|
recFiles: List[str] = []
|
|
|
|
|
|
|
|
processingChain: List[List[str]] = [
|
|
|
|
["lame", processingSrc, processingDst, "--noreplaygain", "--quiet"],
|
|
|
|
]
|
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2019-12-23 01:34:10 +01:00
|
|
|
class _Recorder:
|
2019-12-19 04:02:45 +01:00
|
|
|
def postprocess(self, encode=True) -> None:
|
2012-12-21 08:51:59 +01:00
|
|
|
self.encode = encode
|
|
|
|
for c in processingChain:
|
2019-12-23 01:34:10 +01:00
|
|
|
# print c
|
|
|
|
if not self.encode and c[0] == "lame":
|
2012-12-21 08:51:59 +01:00
|
|
|
continue
|
|
|
|
try:
|
2016-07-26 04:15:43 +02:00
|
|
|
cmd, env = _packagedCmd(c)
|
2020-01-23 07:10:41 +01:00
|
|
|
ret = retryWait(
|
|
|
|
subprocess.Popen(cmd, startupinfo=startup_info(), env=env)
|
|
|
|
)
|
2012-12-21 08:51:59 +01:00
|
|
|
except:
|
|
|
|
ret = True
|
2017-10-25 10:35:39 +02:00
|
|
|
finally:
|
2019-07-14 03:19:29 +02:00
|
|
|
self.cleanup()
|
2012-12-21 08:51:59 +01:00
|
|
|
if ret:
|
2019-12-23 01:34:10 +01:00
|
|
|
raise Exception(_("Error running %s") % " ".join(cmd))
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2019-12-19 04:02:45 +01:00
|
|
|
def cleanup(self) -> None:
|
2019-07-14 03:19:29 +02:00
|
|
|
if os.path.exists(processingSrc):
|
|
|
|
os.unlink(processingSrc)
|
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2019-12-23 01:34:10 +01:00
|
|
|
class PyAudioThreadedRecorder(threading.Thread):
|
2019-12-19 04:02:45 +01:00
|
|
|
def __init__(self, startupDelay) -> None:
|
2012-12-21 08:51:59 +01:00
|
|
|
threading.Thread.__init__(self)
|
2017-12-05 02:07:52 +01:00
|
|
|
self.startupDelay = startupDelay
|
2012-12-21 08:51:59 +01:00
|
|
|
self.finish = False
|
|
|
|
|
2019-12-19 04:02:45 +01:00
|
|
|
def run(self) -> Any:
|
2012-12-21 08:51:59 +01:00
|
|
|
chunk = 1024
|
2016-06-23 04:04:48 +02:00
|
|
|
p = pyaudio.PyAudio()
|
2014-04-17 21:17:05 +02:00
|
|
|
|
2019-12-23 01:34:10 +01:00
|
|
|
rate = int(p.get_default_input_device_info()["defaultSampleRate"])
|
2017-12-05 02:07:52 +01:00
|
|
|
wait = int(rate * self.startupDelay)
|
2014-04-17 21:17:05 +02:00
|
|
|
|
2019-12-23 01:34:10 +01:00
|
|
|
stream = p.open(
|
|
|
|
format=PYAU_FORMAT,
|
|
|
|
channels=PYAU_CHANNELS,
|
|
|
|
rate=rate,
|
|
|
|
input=True,
|
|
|
|
input_device_index=PYAU_INPUT_INDEX,
|
|
|
|
frames_per_buffer=chunk,
|
|
|
|
)
|
2014-04-17 21:17:05 +02:00
|
|
|
|
2017-12-05 02:07:52 +01:00
|
|
|
stream.read(wait)
|
|
|
|
|
2016-05-31 09:51:16 +02:00
|
|
|
data = b""
|
2012-12-21 08:51:59 +01:00
|
|
|
while not self.finish:
|
2018-12-22 04:41:35 +01:00
|
|
|
data += stream.read(chunk, exception_on_overflow=False)
|
2012-12-21 08:51:59 +01:00
|
|
|
stream.close()
|
|
|
|
p.terminate()
|
2019-12-23 01:34:10 +01:00
|
|
|
wf = wave.open(processingSrc, "wb")
|
2012-12-21 08:51:59 +01:00
|
|
|
wf.setnchannels(PYAU_CHANNELS)
|
|
|
|
wf.setsampwidth(p.get_sample_size(PYAU_FORMAT))
|
2014-04-17 21:17:05 +02:00
|
|
|
wf.setframerate(rate)
|
2012-12-21 08:51:59 +01:00
|
|
|
wf.writeframes(data)
|
|
|
|
wf.close()
|
|
|
|
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
class PyAudioRecorder(_Recorder):
|
|
|
|
|
2017-12-05 02:07:52 +01:00
|
|
|
# discard first 250ms which may have pops/cracks
|
|
|
|
startupDelay = 0.25
|
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
def __init__(self):
|
|
|
|
for t in recFiles + [processingSrc, processingDst]:
|
|
|
|
try:
|
|
|
|
os.unlink(t)
|
|
|
|
except OSError:
|
|
|
|
pass
|
|
|
|
self.encode = False
|
|
|
|
|
|
|
|
def start(self):
|
2017-12-05 02:07:52 +01:00
|
|
|
self.thread = PyAudioThreadedRecorder(startupDelay=self.startupDelay)
|
2012-12-21 08:51:59 +01:00
|
|
|
self.thread.start()
|
|
|
|
|
|
|
|
def stop(self):
|
|
|
|
self.thread.finish = True
|
|
|
|
self.thread.join()
|
|
|
|
|
|
|
|
def file(self):
|
|
|
|
if self.encode:
|
2016-05-12 06:45:35 +02:00
|
|
|
tgt = "rec%d.mp3" % time.time()
|
2012-12-21 08:51:59 +01:00
|
|
|
os.rename(processingDst, tgt)
|
|
|
|
return tgt
|
|
|
|
else:
|
|
|
|
return processingSrc
|
|
|
|
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2020-01-20 10:21:24 +01:00
|
|
|
Recorder = PyAudioRecorder
|
2019-02-13 00:36:39 +01:00
|
|
|
|
2020-01-20 10:21:24 +01:00
|
|
|
# Recording dialog
|
2012-12-21 08:51:59 +01:00
|
|
|
##########################################################################
|
|
|
|
|
|
|
|
|
2020-01-20 10:21:24 +01:00
|
|
|
def getAudio(parent, encode=True):
|
|
|
|
"Record and return filename"
|
|
|
|
# record first
|
|
|
|
r = Recorder()
|
|
|
|
mb = QMessageBox(parent)
|
|
|
|
restoreGeom(mb, "audioRecorder")
|
|
|
|
mb.setWindowTitle("Anki")
|
|
|
|
mb.setIconPixmap(QPixmap(":/icons/media-record.png"))
|
|
|
|
but = QPushButton(_("Save"))
|
|
|
|
mb.addButton(but, QMessageBox.AcceptRole)
|
|
|
|
but.setDefault(True)
|
|
|
|
but = QPushButton(_("Cancel"))
|
|
|
|
mb.addButton(but, QMessageBox.RejectRole)
|
|
|
|
mb.setEscapeButton(but)
|
|
|
|
t = time.time()
|
|
|
|
r.start()
|
|
|
|
time.sleep(r.startupDelay)
|
|
|
|
QApplication.instance().processEvents()
|
|
|
|
while not mb.clickedButton():
|
|
|
|
txt = _("Recording...<br>Time: %0.1f")
|
|
|
|
mb.setText(txt % (time.time() - t))
|
|
|
|
mb.show()
|
|
|
|
QApplication.instance().processEvents()
|
|
|
|
if mb.clickedButton() == mb.escapeButton():
|
|
|
|
r.stop()
|
|
|
|
r.cleanup()
|
|
|
|
return
|
|
|
|
saveGeom(mb, "audioRecorder")
|
|
|
|
# ensure at least a second captured
|
|
|
|
while time.time() - t < 1:
|
|
|
|
time.sleep(0.1)
|
|
|
|
r.stop()
|
|
|
|
# process
|
|
|
|
r.postprocess(encode)
|
|
|
|
return r.file()
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2020-01-20 10:52:58 +01:00
|
|
|
|
|
|
|
# Legacy audio interface
|
|
|
|
##########################################################################
|
|
|
|
# these will be removed in the future
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2019-12-19 04:02:45 +01:00
|
|
|
def clearAudioQueue() -> None:
|
2020-01-20 10:52:58 +01:00
|
|
|
av_player.stop_and_clear_queue()
|
|
|
|
|
|
|
|
|
|
|
|
def play(filename: str) -> None:
|
|
|
|
av_player.play_file(filename)
|
|
|
|
|
|
|
|
|
|
|
|
def playFromText(text) -> None:
|
2020-01-24 02:06:11 +01:00
|
|
|
print("playFromText() deprecated")
|
2020-01-20 10:52:58 +01:00
|
|
|
|
2012-12-21 08:51:59 +01:00
|
|
|
|
2020-01-20 13:01:38 +01:00
|
|
|
# legacy globals
|
2020-01-20 10:52:58 +01:00
|
|
|
_player = play
|
|
|
|
_queueEraser = clearAudioQueue
|
2020-01-20 13:01:38 +01:00
|
|
|
mpvManager: Optional["MpvManager"] = None
|
2019-12-23 01:34:10 +01:00
|
|
|
|
2020-01-02 10:43:19 +01:00
|
|
|
# add everything from this module into anki.sound for backwards compat
|
|
|
|
_exports = [i for i in locals().items() if not i[0].startswith("__")]
|
|
|
|
for (k, v) in _exports:
|
|
|
|
sys.modules["anki.sound"].__dict__[k] = v
|
2020-01-20 13:01:38 +01:00
|
|
|
|
2020-01-21 05:47:03 +01:00
|
|
|
# Tag handling
|
|
|
|
##########################################################################
|
|
|
|
|
|
|
|
|
2020-01-24 02:06:11 +01:00
|
|
|
def av_refs_to_play_icons(text: str) -> str:
|
|
|
|
"""Add play icons into the HTML.
|
|
|
|
|
|
|
|
When clicked, the icon will call eg pycmd('play:q:1').
|
|
|
|
"""
|
|
|
|
|
2020-01-21 05:47:03 +01:00
|
|
|
def repl(match: re.Match) -> str:
|
|
|
|
return f"""
|
2020-01-30 22:01:22 +01:00
|
|
|
<a class="replay-button soundLink" href=# onclick="pycmd('{match.group(1)}'); return false;">
|
2020-01-28 01:11:29 +01:00
|
|
|
<svg class="playImage" viewBox="0 0 64 64" version="1.1">
|
2020-01-30 22:23:35 +01:00
|
|
|
<circle cx="32" cy="32" r="29" />
|
|
|
|
<path d="M56.502,32.301l-37.502,20.101l0.329,-40.804l37.173,20.703Z" />
|
2020-01-28 01:11:29 +01:00
|
|
|
</svg>
|
2020-01-21 05:47:03 +01:00
|
|
|
</a>"""
|
|
|
|
|
2020-01-24 06:48:40 +01:00
|
|
|
return AV_REF_RE.sub(repl, text)
|
2020-01-21 05:47:03 +01:00
|
|
|
|
|
|
|
|
2020-01-24 02:06:11 +01:00
|
|
|
def play_clicked_audio(pycmd: str, card: Card) -> None:
|
|
|
|
"""eg. if pycmd is 'play:q:0', play the first audio on the question side."""
|
|
|
|
play, context, str_idx = pycmd.split(":")
|
|
|
|
idx = int(str_idx)
|
|
|
|
if context == "q":
|
|
|
|
tags = card.question_av_tags()
|
|
|
|
else:
|
|
|
|
tags = card.answer_av_tags()
|
|
|
|
av_player.play_tags([tags[idx]])
|
|
|
|
|
|
|
|
|
2020-01-20 13:01:38 +01:00
|
|
|
# Init defaults
|
|
|
|
##########################################################################
|
|
|
|
|
|
|
|
|
2020-01-20 21:49:09 +01:00
|
|
|
def setup_audio(taskman: TaskManager, base_folder: str) -> None:
|
2020-01-20 13:01:38 +01:00
|
|
|
# legacy global var
|
|
|
|
global mpvManager
|
|
|
|
|
|
|
|
if not isWin:
|
|
|
|
try:
|
|
|
|
mpvManager = MpvManager(base_folder)
|
|
|
|
except FileNotFoundError:
|
|
|
|
print("mpv not found, reverting to mplayer")
|
|
|
|
except aqt.mpv.MPVProcessError:
|
|
|
|
print("mpv too old, reverting to mplayer")
|
|
|
|
|
|
|
|
if mpvManager is not None:
|
|
|
|
av_player.players.append(mpvManager)
|
|
|
|
else:
|
2020-01-20 23:55:15 +01:00
|
|
|
mplayer = SimpleMplayerSlaveModePlayer(taskman)
|
2020-01-20 13:01:38 +01:00
|
|
|
av_player.players.append(mplayer)
|
|
|
|
|
|
|
|
# tts support
|
|
|
|
if isMac:
|
|
|
|
from aqt.tts import MacTTSPlayer
|
|
|
|
|
2020-01-20 21:49:09 +01:00
|
|
|
av_player.players.append(MacTTSPlayer(taskman))
|
2020-01-21 08:34:47 +01:00
|
|
|
elif isWin:
|
|
|
|
from aqt.tts import WindowsTTSPlayer
|
2020-01-20 23:55:15 +01:00
|
|
|
|
2020-01-21 08:34:47 +01:00
|
|
|
av_player.players.append(WindowsTTSPlayer(taskman))
|
|
|
|
|
|
|
|
# cleanup at shutdown
|
2020-01-20 23:55:15 +01:00
|
|
|
atexit.register(av_player.shutdown)
|