audio_convert.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. from pathlib import Path
  18. import asyncio
  19. import logging
  20. import mimetypes
  21. import os
  22. import shutil
  23. import tempfile
  24. log = logging.getLogger("mau.util.audio")
  25. def abswhich(program: Optional[str]) -> Optional[str]:
  26. if program is None:
  27. return None
  28. path = shutil.which(program)
  29. return os.path.abspath(path) if path else None
  30. async def to_ogg(data: bytes, mime: str) -> Optional[bytes]:
  31. default_ext = mimetypes.guess_extension(mime)
  32. with tempfile.TemporaryDirectory(prefix="mxsignal_audio_") as tmpdir:
  33. input_file_name = os.path.join(tmpdir, f"input{default_ext}")
  34. output_file_name = os.path.join(tmpdir, "output.ogg")
  35. with open(input_file_name, "wb") as file:
  36. file.write(data)
  37. proc = await asyncio.create_subprocess_exec(
  38. "ffmpeg",
  39. "-i",
  40. input_file_name,
  41. "-c:a",
  42. "libvorbis",
  43. output_file_name,
  44. stdout=asyncio.subprocess.PIPE,
  45. stdin=asyncio.subprocess.PIPE,
  46. )
  47. _, stderr = await proc.communicate()
  48. if proc.returncode == 0:
  49. with open(output_file_name, "rb") as file:
  50. return file.read()
  51. else:
  52. err_text = (
  53. stderr.decode("utf-8") if stderr is not None else f"unknown ({proc.returncode})"
  54. )
  55. raise ChildProcessError(f"ffmpeg error: {err_text}")
  56. async def to_m4a(path_str: str) -> Optional[str]:
  57. path = Path(path_str)
  58. output_file_name = (path.parent / (path.stem + ".m4a")).absolute().as_posix()
  59. proc = await asyncio.create_subprocess_exec(
  60. "ffmpeg",
  61. "-i",
  62. path,
  63. "-c:a",
  64. "aac",
  65. output_file_name,
  66. stdout=asyncio.subprocess.PIPE,
  67. stdin=asyncio.subprocess.PIPE,
  68. )
  69. _, stderr = await proc.communicate()
  70. if proc.returncode == 0:
  71. path.unlink(missing_ok=True)
  72. return output_file_name
  73. else:
  74. err_text = stderr.decode("utf-8") if stderr is not None else f"unknown ({proc.returncode})"
  75. raise ChildProcessError(f"ffmpeg error: {err_text}")