video-downscale.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import { execFile } from 'node:child_process'
  2. import crypto from 'node:crypto'
  3. import { stat } from 'node:fs/promises'
  4. import path from 'node:path'
  5. import { promisify } from 'node:util'
  6. import { db } from '@/lib/db'
  7. import { discardUnsavedUpload, releaseFiles } from '@/lib/files/manager'
  8. import { uploadsRoot } from '@/lib/upload-root'
  9. import { ffmpegInputFormat, type VideoContainer } from '@/lib/video-sniff'
  10. /**
  11. * Brings a video shot above 1080p down to 1080p, after it has been saved.
  12. *
  13. * A clip picked from a phone's library was shot by the phone's own camera at
  14. * whatever it was set to, and at 4K a minute of it is hundreds of megabytes
  15. * that nobody looking at a worn brake disc needs. The technician's app records
  16. * at 1080p itself; this is for everything that did not come from it.
  17. *
  18. * It runs after the upload has been answered, never during it. Re-encoding 4K
  19. * takes minutes, and a phone holding a request open that long with nothing
  20. * coming back gives up and reports a failure for a file that arrived. So the
  21. * original is saved and served straight away, and the row is pointed at the
  22. * smaller copy when there is one.
  23. *
  24. * Anything that goes wrong leaves the original where it was: no ffmpeg on
  25. * this install, a take it cannot read, an attachment deleted in the meantime.
  26. */
  27. const execFileAsync = promisify(execFile)
  28. /** The shorter side of a 1080p picture, whichever way the phone was held. */
  29. export const MAX_SHORT_SIDE = 1080
  30. const PROBE_TIMEOUT_MS = 30_000
  31. const ENCODE_TIMEOUT_MS = 15 * 60_000
  32. /** Whether a picture of this size is larger than 1080p in either orientation. */
  33. export function needsDownscale(width: number, height: number): boolean {
  34. return Math.min(width, height) > MAX_SHORT_SIDE
  35. }
  36. /** The picture size out of ffprobe's `WIDTHxHEIGHT` line, or null for anything else. */
  37. export function parseProbedSize(output: string): { width: number; height: number } | null {
  38. const match = /^(\d+)x(\d+)/.exec(output.trim())
  39. if (!match) return null
  40. const width = Number(match[1])
  41. const height = Number(match[2])
  42. return width > 0 && height > 0 ? { width, height } : null
  43. }
  44. /**
  45. * The arguments for the re-encode.
  46. *
  47. * The demuxer is pinned and only local files may be opened, for the reasons
  48. * given in video-sniff. The shorter side becomes 1080 and the other follows,
  49. * so a clip filmed upright stays upright: ffmpeg applies the phone's rotation
  50. * before the filter sees the picture. Eight-bit H.264 with the index at the
  51. * front, because that is what every browser and both phones play.
  52. */
  53. export function downscaleArgs(
  54. inputPath: string,
  55. container: VideoContainer,
  56. outputPath: string
  57. ): string[] {
  58. const side = MAX_SHORT_SIDE
  59. return [
  60. '-nostdin',
  61. '-protocol_whitelist',
  62. 'file,crypto',
  63. '-f',
  64. ffmpegInputFormat(container),
  65. '-i',
  66. inputPath,
  67. '-map',
  68. '0:v:0',
  69. '-map',
  70. '0:a:0?',
  71. '-sn',
  72. '-dn',
  73. '-vf',
  74. `scale='if(gt(iw,ih),-2,${side})':'if(gt(iw,ih),${side},-2)'`,
  75. '-c:v',
  76. 'libx264',
  77. '-preset',
  78. 'veryfast',
  79. '-crf',
  80. '23',
  81. '-pix_fmt',
  82. 'yuv420p',
  83. // Two threads: this shares a small machine with the app itself, and a
  84. // clip that takes twice as long is better than a workshop that stalls.
  85. '-threads',
  86. '2',
  87. '-c:a',
  88. 'aac',
  89. '-b:a',
  90. '128k',
  91. '-movflags',
  92. '+faststart',
  93. '-y',
  94. outputPath,
  95. ]
  96. }
  97. async function probeSize(
  98. inputPath: string,
  99. container: VideoContainer
  100. ): Promise<{ width: number; height: number } | null> {
  101. try {
  102. const { stdout } = await execFileAsync(
  103. 'ffprobe',
  104. [
  105. '-v',
  106. 'error',
  107. '-protocol_whitelist',
  108. 'file,crypto',
  109. '-f',
  110. ffmpegInputFormat(container),
  111. '-select_streams',
  112. 'v:0',
  113. '-show_entries',
  114. 'stream=width,height',
  115. '-of',
  116. 'csv=p=0:s=x',
  117. inputPath,
  118. ],
  119. { timeout: PROBE_TIMEOUT_MS }
  120. )
  121. return parseProbedSize(stdout)
  122. } catch {
  123. return null
  124. }
  125. }
  126. export interface DownscaleJob {
  127. attachmentId: string
  128. organizationId: string
  129. /** The attachment's URL as it was saved: `/api/protected/files/<org>/services/<name>`. */
  130. fileUrl: string
  131. container: VideoContainer
  132. }
  133. const FOLDER = 'services'
  134. async function run(job: DownscaleJob): Promise<void> {
  135. const name = job.fileUrl.split('/').pop()
  136. if (!name) return
  137. const dir = path.join(uploadsRoot(), job.organizationId, FOLDER)
  138. const inputPath = path.join(dir, name)
  139. const size = await probeSize(inputPath, job.container)
  140. if (!size || !needsDownscale(size.width, size.height)) return
  141. const outputName = `${crypto.randomUUID()}.mp4`
  142. const outputPath = path.join(dir, outputName)
  143. let fileSize: number
  144. try {
  145. await execFileAsync('ffmpeg', downscaleArgs(inputPath, job.container, outputPath), {
  146. timeout: ENCODE_TIMEOUT_MS,
  147. })
  148. fileSize = (await stat(outputPath)).size
  149. } catch {
  150. // Whatever ffmpeg left behind is half a file that no row points at.
  151. await discardUnsavedUpload(job.organizationId, FOLDER, outputName)
  152. return
  153. }
  154. // Only if the row still points at the file that was re-encoded. An
  155. // attachment deleted while this ran must not come back as a file on disk.
  156. const swapped = await db.serviceAttachment.updateMany({
  157. where: { id: job.attachmentId, fileUrl: job.fileUrl },
  158. data: {
  159. fileUrl: `/api/protected/files/${job.organizationId}/${FOLDER}/${outputName}`,
  160. fileType: 'video/mp4',
  161. fileSize,
  162. },
  163. })
  164. if (swapped.count === 0) {
  165. await discardUnsavedUpload(job.organizationId, FOLDER, outputName)
  166. return
  167. }
  168. // Through the file manager, not deleted outright: it checks that no other
  169. // row picked the original up in the minutes this took.
  170. await releaseFiles([job.fileUrl], {
  171. organizationId: job.organizationId,
  172. reason: 'video replaced by its 1080p copy',
  173. })
  174. }
  175. // On globalThis, so the one queue survives a module being loaded twice.
  176. const state = globalThis as unknown as { __videoDownscaleQueue?: Promise<void> }
  177. /**
  178. * Queues a saved video to be checked and, when it is above 1080p, re-encoded.
  179. *
  180. * One at a time. Two 4K encodes side by side on the machine that also serves
  181. * the workshop is how an upload turns into an outage.
  182. */
  183. export function queueVideoDownscale(job: DownscaleJob): Promise<void> {
  184. const next = (state.__videoDownscaleQueue ?? Promise.resolve()).then(() =>
  185. run(job).catch((err) => {
  186. console.error(`[video] could not downscale attachment ${job.attachmentId}:`, err)
  187. })
  188. )
  189. state.__videoDownscaleQueue = next
  190. return next
  191. }