+async function hlsPlaylistToFragmentedMP4 (hlsDirectory: string, segmentFiles: string[], outputPath: string) {
+ const concatFilePath = join(hlsDirectory, 'concat.txt')
+
+ function cleaner () {
+ remove(concatFilePath)
+ .catch(err => logger.error('Cannot remove concat file in %s.', hlsDirectory, { err }))
+ }
+
+ // First concat the ts files to a mp4 file
+ const content = segmentFiles.map(f => 'file ' + f)
+ .join('\n')
+
+ await writeFile(concatFilePath, content + '\n')
+
+ const command = getFFmpeg(concatFilePath)
+ command.inputOption('-safe 0')
+ command.inputOption('-f concat')
+
+ command.outputOption('-c:v copy')
+ command.audioFilter('aresample=async=1:first_pts=0')
+ command.output(outputPath)
+
+ return runCommand(command, cleaner)
+}
+
+async function runCommand (command: ffmpeg.FfmpegCommand, onEnd?: Function) {
+ command.run()
+
+ return new Promise<string>((res, rej) => {
+ command.on('error', err => {
+ if (onEnd) onEnd()
+
+ rej(err)
+ })
+
+ command.on('end', () => {
+ if (onEnd) onEnd()
+
+ res()
+ })
+ })
+}
+