time-parser.ts•3.03 kB
/**
* SRT time format parsing and manipulation utilities
*/
import { SRTTime } from '../types/srt.js';
/**
* Parse SRT time format (HH:MM:SS,mmm) to SRTTime object
*/
export function parseSRTTime(timeString: string): SRTTime {
const match = timeString.match(/^(\d{2}):(\d{2}):(\d{2}),(\d{3})$/);
if (!match) {
throw new Error(`Invalid SRT time format: ${timeString}`);
}
const [, hours, minutes, seconds, milliseconds] = match;
return {
hours: parseInt(hours, 10),
minutes: parseInt(minutes, 10),
seconds: parseInt(seconds, 10),
milliseconds: parseInt(milliseconds, 10)
};
}
/**
* Convert SRTTime object to SRT time format string
*/
export function formatSRTTime(time: SRTTime): string {
const pad = (num: number, length: number) => num.toString().padStart(length, '0');
return `${pad(time.hours, 2)}:${pad(time.minutes, 2)}:${pad(time.seconds, 2)},${pad(time.milliseconds, 3)}`;
}
/**
* Convert SRTTime to milliseconds for calculations
*/
export function timeToMilliseconds(time: SRTTime): number {
return (time.hours * 3600 + time.minutes * 60 + time.seconds) * 1000 + time.milliseconds;
}
/**
* Convert milliseconds to SRTTime
*/
export function millisecondsToTime(ms: number): SRTTime {
const hours = Math.floor(ms / 3600000);
const minutes = Math.floor((ms % 3600000) / 60000);
const seconds = Math.floor((ms % 60000) / 1000);
const milliseconds = ms % 1000;
return { hours, minutes, seconds, milliseconds };
}
/**
* Validate that end time is after start time
*/
export function validateTimeSequence(startTime: SRTTime, endTime: SRTTime): boolean {
const startMs = timeToMilliseconds(startTime);
const endMs = timeToMilliseconds(endTime);
return endMs > startMs;
}
/**
* Calculate duration between two times
*/
export function calculateDuration(startTime: SRTTime, endTime: SRTTime): SRTTime {
const startMs = timeToMilliseconds(startTime);
const endMs = timeToMilliseconds(endTime);
const durationMs = endMs - startMs;
if (durationMs < 0) {
throw new Error('End time must be after start time');
}
return millisecondsToTime(durationMs);
}
/**
* Add time offset to SRTTime
*/
export function addTimeOffset(time: SRTTime, offsetMs: number): SRTTime {
const currentMs = timeToMilliseconds(time);
const newMs = currentMs + offsetMs;
if (newMs < 0) {
throw new Error('Time offset would result in negative time');
}
return millisecondsToTime(newMs);
}
/**
* Parse SRT time range (start --> end)
*/
export function parseSRTTimeRange(timeRange: string): { start: SRTTime; end: SRTTime } {
const parts = timeRange.split(' --> ');
if (parts.length !== 2) {
throw new Error(`Invalid SRT time range format: ${timeRange}`);
}
return {
start: parseSRTTime(parts[0].trim()),
end: parseSRTTime(parts[1].trim())
};
}
/**
* Format SRT time range
*/
export function formatSRTTimeRange(start: SRTTime, end: SRTTime): string {
return `${formatSRTTime(start)} --> ${formatSRTTime(end)}`;
}