audio_convert.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2021 Tulir Asokan, Sumner Evans
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. from typing import Optional
  17. import asyncio
  18. import logging
  19. import mimetypes
  20. import os
  21. import shutil
  22. import tempfile
  23. log = logging.getLogger("mau.util.audio")
  24. def abswhich(program: Optional[str]) -> Optional[str]:
  25. if program is None:
  26. return None
  27. path = shutil.which(program)
  28. return os.path.abspath(path) if path else None
  29. async def to_ogg(data: bytes, mime: str) -> Optional[bytes]:
  30. default_ext = mimetypes.guess_extension(mime)
  31. with tempfile.TemporaryDirectory(prefix="mxsignal_audio_") as tmpdir:
  32. input_file_name = os.path.join(tmpdir, f"input{default_ext}")
  33. output_file_name = os.path.join(tmpdir, "output.ogg")
  34. with open(input_file_name, "wb") as file:
  35. file.write(data)
  36. proc = await asyncio.create_subprocess_exec(
  37. "ffmpeg",
  38. "-i",
  39. input_file_name,
  40. "-c:a",
  41. "libvorbis",
  42. output_file_name,
  43. stdout=asyncio.subprocess.PIPE,
  44. stdin=asyncio.subprocess.PIPE,
  45. )
  46. _, stderr = await proc.communicate()
  47. if proc.returncode == 0:
  48. with open(output_file_name, "rb") as file:
  49. return file.read()
  50. else:
  51. err_text = (
  52. stderr.decode("utf-8") if stderr is not None else f"unknown ({proc.returncode})"
  53. )
  54. raise ChildProcessError(f"ffmpeg error: {err_text}")