All files / src process.ts

86.93% Statements 153/176
87.87% Branches 29/33
100% Functions 4/4
86.93% Lines 153/176

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 1771x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x         16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 1x 16x 16x 1x 5x 5x 2x 2x 1x 1x 16x 16x 1x 1x 11x 7x 7x 1x 1x 16x 16x 16x 16x 14x 14x 14x 14x 1x 14x 2x 2x 2x 2x 1x 1x 2x 2x 13x 11x 11x 11x 11x 11x 16x 16x 16x                       16x 16x 16x 16x                 16x 1x 1x 16x 16x 16x 2x 2x 2x 2x 2x 16x 16x 16x 16x  
import { spawn } from 'node:child_process'
 
import { isWindows } from './utils/platform'
import {
  extractErrorMessage,
  extractProgress,
  CodecDataExtractor
} from './utils/parsing'
import LineBuffer from './utils/line-buffer'
import { InputCodecInformation, ProgressInformation } from './utils/data-types'
import { Readable, Writable } from 'node:stream'
 
export type RunResult = {
  stderr: string
  stdout: string
}
 
export type RunOptions = {
  nice?: number
  cwd?: string
  timeout?: number
  onProgress?: (progress: ProgressInformation) => void
  onCodecData?: (data: InputCodecInformation) => void
  onStderr?: (line: string) => void
}
 
export type ProcessOptions = RunOptions & {
  args: string[]
  captureStdout?: boolean
  inputStream?: Readable
  outputStream?: Writable
}
 
export class FfmpegProcess implements ProcessOptions {
  args: string[]
  nice?: number
  cwd?: string
  timeout?: number
  captureStdout?: boolean
  inputStream?: Readable
  outputStream?: Writable
  onProgress?: (progress: ProgressInformation) => void
  onCodecData?: (data: InputCodecInformation) => void
  onStderr?: (line: string) => void
 
  constructor(options: ProcessOptions) {
    this.args = options.args
    this.nice = options.nice
    this.cwd = options.cwd
    this.timeout = options.timeout
    this.captureStdout = options.captureStdout
    this.inputStream = options.inputStream
    this.outputStream = options.outputStream
    this.onProgress = options.onProgress
    this.onCodecData = options.onCodecData
    this.onStderr = options.onStderr
 
    this.#validateOptions()
  }
 
  #validateOptions() {
    if (this.outputStream && this.captureStdout) {
      throw new Error(
        "Cannot use 'captureStdout' when a stream output is present"
      )
    }
  }
 
  // TODO return a compound type that is PromiseLike and has methods on the process (like kill)
  run(callback?: (err: any, result?: any) => any): Promise<RunResult> {
    let cmd = process.env.FFMPEG_PATH || 'ffmpeg'
    let args: string[] = [...this.args]
 
    let { onProgress, onCodecData, onStderr } = this
 
    if (this.nice && this.nice !== 0 && !isWindows) {
      args = ['-n', this.nice.toString(), cmd, ...args]
      cmd = 'nice'
    }
 
    let promise: Promise<RunResult> = new Promise((resolve, reject) => {
      let child = spawn(cmd, args, {
        cwd: this.cwd,
        timeout: this.timeout,
        windowsHide: true
      })
 
      let stderr = new LineBuffer()
      let stdout = new LineBuffer()
 
      if (onStderr) {
        stderr.on('line', onStderr)
      }
 
      if (onProgress) {
        stderr.on('line', (line: string) => {
          let progress = extractProgress(line)
          if (progress) {
            onProgress?.(progress)
          }
        })
      }
 
      if (onCodecData) {
        let extractor = new CodecDataExtractor(onCodecData)
        stderr.on('line', (line: string) => {
          if (!extractor.done) {
            extractor.processLine(line)
          }
        })
      }
 
      child.on('error', (err) => reject(err))
 
      child.on('close', (code, signal) => {
        stderr.close()
        stdout.close()
 
        if (signal) {
          reject(new Error(`ffmpeg was killed with signal ${signal}`))
        } else if (code) {
          let message = `ffmpeg exited with code ${code}`
          let error = extractErrorMessage(stderr.lines)
 
          if (error) {
            message = `${message}:\n${error}`
          }
 
          reject(new Error(message))
        } else {
          resolve({
            stdout: stdout.toString(),
            stderr: stderr.toString()
          })
        }
      })
 
      if (this.inputStream) {
        this.inputStream.pipe(child.stdin)
        this.inputStream.on('error', (err) => {
          // TODO make a specific error type
          reject(err)

          child.kill()
        })

        // Prevent stdin errors from bubbling up, ffmpeg will crash anyway
        child.stdin.on('error', () => {})
      }
 
      child.stderr.on('data', (data) => stderr.append(data.toString()))
 
      if (this.outputStream) {
        child.stdout.pipe(this.outputStream)

        this.outputStream.on('error', (err) => {
          // TODO make a specific error type
          reject(err)

          child.kill()
        })
      } else if (this.captureStdout) {
        child.stdout.on('data', (data) => stdout.append(data.toString()))
      }
    })
 
    if (callback) {
      promise.then(
        (value) => callback(null, value),
        (reason) => callback(reason)
      )
    }
 
    return promise
  }
}