subtlefixer
Version:
Will adjust SRT files with the specified offset
64 lines (57 loc) • 2.28 kB
JavaScript
const
fs = require('fs'),
argv = require('minimist')(process.argv.slice(3))
const glob = require("glob");
const NEWLINE = '\r\n' // apparently this is the most used one
const SKIP_ME = {}
let ofs = process.argv[2] // the minus with negative numbers drives minimist crazy
ofs = ofs && Number(ofs.replace(',','.'))
if (!ofs) {
print('subtlefixer <offset-in-seconds> [<files>] [--overwrite]')
process.exit()
}
const mask = argv._[0] || '*.srt'
print('Working on',mask)
const { overwrite } = argv
print(overwrite ? 'overwrite mode' : `I'll append "-fixed" to destination files`)
let index = 1
const files = glob.sync(mask)
if (!files.length)
return print('No matching file found')
for (const fn of files) {
print('file', fn.startsWith(mask) ? fn.substr(mask.length + 1) : fn, '...')
const content = fs.readFileSync(fn, {encoding:'utf8', flag:'r'})
const normalized = content.replace(/\r/g,'') // make it easy
const pieces = normalized.split('\n\n')
const newPieces = pieces.map(piece=>{
if (!piece.trim())
return ''
const lines = piece.split('\n')
const times = lines[1].split(/ *-+> */,2)
const newTimes = times.map(time=> {
const [hours,minutes,seconds] = time.split(':')
const totalSeconds = 3600*hours + 60*minutes + 1*seconds.replace(',','.')
const newSecs = totalSeconds + ofs
return newSecs >= 0 && secsToSRT(newSecs)
})
if (newTimes.some(x=> !x)) // whole piece must be discarded
return SKIP_ME
lines[0] = index++
lines[1] = newTimes.join(' --> ')
return lines.join(NEWLINE)
}).filter(x => x !== SKIP_ME)
const newContent = newPieces.join(NEWLINE+NEWLINE)
const dest = overwrite ? fn : fn + '-fixed'
fs.writeFileSync(dest, newContent)
const discarded = pieces.length - newPieces.length
print('done', discarded ? ` (${discarded} discarded)` : '')
}
function print(...args) {
console.log(...args)
}
function secsToSRT(secs) {
return new Date(secs*1000).toISOString().split('T')[1]
.replace('.',',') // "this is the way"
.substr(0,12) // remove final Z
}