transcoder.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. package transcoder
  2. /*
  3. Transcoder.go
  4. This module handle real-time transcoding of media files
  5. that is not supported by playing on web.
  6. */
  7. import (
  8. "encoding/json"
  9. "fmt"
  10. "io"
  11. "net/http"
  12. "os/exec"
  13. "strconv"
  14. "time"
  15. "imuslab.com/arozos/mod/info/logger"
  16. )
  17. type TranscodeOutputResolution string
  18. // Output resolutions offered by the player; see quality.go for what each means.
  19. const (
  20. TranscodeResolution_360p TranscodeOutputResolution = "360p"
  21. TranscodeResolution_480p TranscodeOutputResolution = "480p"
  22. TranscodeResolution_720p TranscodeOutputResolution = "720p"
  23. TranscodeResolution_1080p TranscodeOutputResolution = "1080p"
  24. TranscodeResolution_original TranscodeOutputResolution = ""
  25. )
  26. // Transcode and stream the given file. Make sure ffmpeg is installed before calling to transcoder.
  27. // startTime is a seek offset in seconds; pass 0 to start from the beginning.
  28. // When the host has a usable hardware H.264 encoder - NVENC / VAAPI / Quick
  29. // Sync / AMF on Linux and Windows, VideoToolbox on macOS - it is used in place
  30. // of libx264 to keep CPU load down (probed once and cached by
  31. // getHWEncoderProfile); otherwise this falls back to the original software path.
  32. // With VAAPI the source is decoded and scaled on the GPU as well, which is what
  33. // keeps an HEVC source from saturating a low-end CPU.
  34. func TranscodeAndStream(w http.ResponseWriter, r *http.Request, inputFile string, resolution TranscodeOutputResolution, startTime float64) {
  35. // Build the FFmpeg command based on the resolution parameter
  36. args, err := buildMP4Args(inputFile, resolution, startTime, getHWEncoderProfile())
  37. if err != nil {
  38. http.Error(w, "Invalid resolution parameter", http.StatusBadRequest)
  39. return
  40. }
  41. cmd := exec.Command("ffmpeg", args...)
  42. // Set response headers for streaming MP4 video
  43. w.Header().Set("Content-Type", "video/mp4")
  44. w.Header().Set("Transfer-Encoding", "chunked")
  45. w.Header().Set("Cache-Control", "public, max-age=3600, s-maxage=3600, must-revalidate")
  46. w.Header().Set("Accept-Ranges", "bytes")
  47. // Get the command output pipe
  48. stdout, err := cmd.StdoutPipe()
  49. if err != nil {
  50. http.Error(w, "Failed to create output pipe", http.StatusInternalServerError)
  51. return
  52. }
  53. // Get the command error pipe to capture standard error
  54. stderr, err := cmd.StderrPipe()
  55. if err != nil {
  56. http.Error(w, "Failed to create error pipe", http.StatusInternalServerError)
  57. logger.PrintAndLog("Transcoder", fmt.Sprintf("Failed to create error pipe: %v", err), nil)
  58. return
  59. }
  60. // Start the command
  61. if err := cmd.Start(); err != nil {
  62. http.Error(w, "Failed to start FFmpeg", http.StatusInternalServerError)
  63. return
  64. }
  65. // Buffered so both the natural-end goroutine and the client-disconnect goroutine
  66. // can send without blocking — only the first signal is consumed.
  67. done := make(chan struct{}, 2)
  68. // Monitor client connection close
  69. go func() {
  70. <-r.Context().Done()
  71. time.Sleep(300 * time.Millisecond)
  72. cmd.Process.Kill()
  73. done <- struct{}{}
  74. }()
  75. // Copy the command output to the HTTP response in a separate goroutine
  76. go func() {
  77. if _, err := io.Copy(w, stdout); err != nil {
  78. cmd.Process.Kill()
  79. }
  80. // Signal natural end so the handler returns and the chunked-transfer
  81. // terminator is flushed to the client.
  82. done <- struct{}{}
  83. }()
  84. // Read and log the command standard error
  85. go func() {
  86. errOutput, _ := io.ReadAll(stderr)
  87. if len(errOutput) > 0 {
  88. logger.PrintAndLog("Transcoder", fmt.Sprintf("FFmpeg error output: %s", string(errOutput)), nil)
  89. }
  90. }()
  91. go func() {
  92. if err := cmd.Wait(); err != nil {
  93. logger.PrintAndLog("Transcoder", fmt.Sprintf("FFmpeg process exited: %v", err), nil)
  94. return
  95. }
  96. }()
  97. // Wait for the command to finish or client disconnect
  98. <-done
  99. logger.PrintAndLog("Transcoder", "[Media Server] Transcode client disconnected", nil)
  100. }
  101. // buildMP4Args assembles the ffmpeg command line of TranscodeAndStream: the
  102. // hardware profile when one is given, libx264 otherwise, muxed into a
  103. // fragmented MP4 on stdout. buildHLSArgs is its HLS counterpart.
  104. func buildMP4Args(inputFile string, resolution TranscodeOutputResolution, startTime float64, hw *hwEncoderProfile) ([]string, error) {
  105. scale, err := resolutionScaleFilter(resolution)
  106. if err != nil {
  107. return nil, err
  108. }
  109. var preInputArgs []string
  110. if startTime > 0.001 {
  111. preInputArgs = append(preInputArgs, "-ss", fmt.Sprintf("%.3f", startTime))
  112. }
  113. var videoCodecArgs []string
  114. var vf string
  115. if hw != nil {
  116. preInputArgs = append(append([]string{}, hw.PreInput...), preInputArgs...)
  117. preInputArgs = append(preInputArgs, hw.DecodeArgs...)
  118. vf = hw.ScaleFilter(scale)
  119. videoCodecArgs = append([]string{"-vcodec", hw.Codec}, hw.EncodeArgs...)
  120. videoCodecArgs = append(videoCodecArgs, rateControlArgs(resolution, true)...)
  121. } else {
  122. vf = scale
  123. // -pix_fmt yuv420p is not optional. libx264 otherwise matches the source
  124. // bit depth, so a 10-bit input (routine in anime releases) produces a
  125. // High 10 stream that Chrome and Firefox cannot decode — the transcode
  126. // would appear to succeed and then fail to play, which is the whole
  127. // problem transcoding exists to avoid.
  128. videoCodecArgs = []string{"-vcodec", "libx264", "-preset", "superfast", "-pix_fmt", "yuv420p"}
  129. videoCodecArgs = append(videoCodecArgs, rateControlArgs(resolution, false)...)
  130. }
  131. middleArgs := []string{"-i", inputFile}
  132. if vf != "" {
  133. middleArgs = append(middleArgs, "-vf", vf)
  134. }
  135. transcodeFormatArgs := []string{"-f", "mp4"}
  136. transcodeFormatArgs = append(transcodeFormatArgs, videoCodecArgs...)
  137. transcodeFormatArgs = append(transcodeFormatArgs, "-g", "60", "-movflags", "frag_keyframe+empty_moov+faststart", "pipe:1")
  138. var args []string
  139. args = append(args, preInputArgs...)
  140. args = append(args, middleArgs...)
  141. args = append(args, transcodeFormatArgs...)
  142. return args, nil
  143. }
  144. type TranscodeAudioSampleRate int
  145. const (
  146. TranscodeAudio_16kHz TranscodeAudioSampleRate = 16000
  147. TranscodeAudio_24kHz TranscodeAudioSampleRate = 24000
  148. TranscodeAudio_48kHz TranscodeAudioSampleRate = 48000
  149. )
  150. // TranscodeAndStreamAudio transcodes an audio file to MP3 and streams it.
  151. // startTime is the seek offset in seconds; pass 0 to start from the beginning.
  152. func TranscodeAndStreamAudio(w http.ResponseWriter, r *http.Request, inputFile string, sampleRate TranscodeAudioSampleRate, startTime float64) {
  153. var args []string
  154. if startTime > 0.001 {
  155. args = append(args, "-ss", fmt.Sprintf("%.3f", startTime))
  156. }
  157. args = append(args,
  158. "-i", inputFile,
  159. "-vn",
  160. "-acodec", "libmp3lame",
  161. "-ar", fmt.Sprintf("%d", int(sampleRate)),
  162. "-b:a", "128k",
  163. "-f", "mp3",
  164. "pipe:1",
  165. )
  166. cmd := exec.Command("ffmpeg", args...)
  167. w.Header().Set("Content-Type", "audio/mpeg")
  168. w.Header().Set("Transfer-Encoding", "chunked")
  169. w.Header().Set("Cache-Control", "no-cache, no-store")
  170. w.Header().Set("X-Content-Type-Options", "nosniff")
  171. stdout, err := cmd.StdoutPipe()
  172. if err != nil {
  173. http.Error(w, "Failed to create output pipe", http.StatusInternalServerError)
  174. return
  175. }
  176. stderr, err := cmd.StderrPipe()
  177. if err != nil {
  178. http.Error(w, "Failed to create error pipe", http.StatusInternalServerError)
  179. return
  180. }
  181. if err := cmd.Start(); err != nil {
  182. http.Error(w, "Failed to start FFmpeg", http.StatusInternalServerError)
  183. return
  184. }
  185. // Buffered so both the natural-end goroutine and the client-disconnect goroutine
  186. // can send without blocking — only the first signal is consumed.
  187. done := make(chan struct{}, 2)
  188. go func() {
  189. <-r.Context().Done()
  190. time.Sleep(300 * time.Millisecond)
  191. cmd.Process.Kill()
  192. done <- struct{}{}
  193. }()
  194. go func() {
  195. if _, err := io.Copy(w, stdout); err != nil {
  196. cmd.Process.Kill()
  197. }
  198. // Signal even on a clean finish so the handler returns and the HTTP
  199. // chunked-transfer terminator (final zero-length frame) is flushed to
  200. // the client. Without this the browser never receives EOF and the
  201. // audio element's 'ended' event does not fire reliably.
  202. done <- struct{}{}
  203. }()
  204. go func() {
  205. errOutput, _ := io.ReadAll(stderr)
  206. if len(errOutput) > 0 {
  207. logger.PrintAndLog("Transcoder", fmt.Sprintf("FFmpeg audio error output: %s", string(errOutput)), nil)
  208. }
  209. }()
  210. go func() {
  211. if err := cmd.Wait(); err != nil {
  212. logger.PrintAndLog("Transcoder", fmt.Sprintf("FFmpeg audio process exited: %v", err), nil)
  213. }
  214. }()
  215. <-done
  216. logger.PrintAndLog("Transcoder", "[Media Server] Audio transcode client disconnected", nil)
  217. }
  218. // GetAudioDuration returns the duration of a local audio file in seconds using ffprobe.
  219. func GetAudioDuration(inputFile string) (float64, error) {
  220. cmd := exec.Command("ffprobe",
  221. "-v", "quiet",
  222. "-print_format", "json",
  223. "-show_format",
  224. inputFile,
  225. )
  226. output, err := cmd.Output()
  227. if err != nil {
  228. return 0, fmt.Errorf("ffprobe failed: %w", err)
  229. }
  230. var result struct {
  231. Format struct {
  232. Duration string `json:"duration"`
  233. } `json:"format"`
  234. }
  235. if err := json.Unmarshal(output, &result); err != nil {
  236. return 0, fmt.Errorf("failed to parse ffprobe output: %w", err)
  237. }
  238. duration, err := strconv.ParseFloat(result.Format.Duration, 64)
  239. if err != nil {
  240. return 0, fmt.Errorf("invalid duration value: %w", err)
  241. }
  242. return duration, nil
  243. }