1 ;;; srt2vtt --- SRT to WebVTT converter
2 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
4 ;;; srt2vtt is free software; you can redistribute it and/or modify it
5 ;;; under the terms of the GNU General Public License as published by
6 ;;; the Free Software Foundation; either version 3 of the License, or
7 ;;; (at your option) any later version.
9 ;;; srt2vtt is distributed in the hope that it will be useful, but
10 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
11 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 ;;; General Public License for more details.
14 ;;; You should have received a copy of the GNU General Public License
15 ;;; along with srt2vtt. If not, see <http://www.gnu.org/licenses/>.
17 (define-module (srt2vtt subrip)
18 #:use-module (ice-9 match)
19 #:use-module (ice-9 rdelim)
20 #:use-module (ice-9 regex)
21 #:use-module (srfi srfi-1)
22 #:use-module (srfi srfi-11)
23 #:use-module (srfi srfi-26)
24 #:use-module (srt2vtt)
29 (let ((regexp (make-regexp "^([0-9]+):([0-9]+):([0-9]+),([0-9]+)$")))
31 "Parse the SubRip formatted timestamp in the string S into a 4
32 element list. Valid input looks like '00:00:03.417'."
33 (let ((match (regexp-exec regexp s)))
35 (map (cut match:substring match <>) '(1 2 3 4))
36 (error "Invalid SubRip timestamp: " s))))))
38 (define parse-time-span
39 (let ((regexp (make-regexp "^([0-9:,]+) --> ([0-9:,]+)$")))
41 "Parse the SubRip formatted time span in the string S and return
42 two values: the start time and the end time. Valid input looks like
43 '00:00:03.417 --> 00:00:04.936'."
44 (let ((match (regexp-exec regexp s)))
46 (values (parse-time (match:substring match 1))
47 (parse-time (match:substring match 2)))
48 (error "Invalid SubRip time range: " s))))))
50 (define (read-subrip port)
51 "Read a SubRip formatted subtitle from PORT."
52 (let-values (((id) (string->number (read-line port)))
53 ((start end) (parse-time-span (read-line port)))
54 ((lines) (let loop ((lines '()))
55 (let ((line (read-line port)))
56 (if (or (eof-object? line)
57 (and (string-null? line)
58 ;; A subtitle may be a blank line!
61 (loop (cons line lines)))))))
62 (make-subtitle id start end lines)))
64 (define (read-subrips port)
65 "Read all SubRip formatted subtitles from PORT."
67 (let loop ((subs '()))
68 (if (eof-object? (peek-char port))
70 (loop (cons (read-subrip port) subs))))))