Modularize!
[srt2vtt.git] / srt2vtt / subrip.scm
1 ;;; srt2vtt --- SRT to WebVTT converter
2 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
3 ;;;
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.
8 ;;;
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.
13 ;;;
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/>.
16
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)
25   #:export (read-subrip
26             read-subrips))
27
28 (define parse-time
29   (let ((regexp (make-regexp "([0-9]+):([0-9]+):([0-9]+),([0-9]+)")))
30     (lambda (s)
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)))
34         (map (cut match:substring match <>) '(1 2 3 4))))))
35
36 (define parse-time-span
37   (let ((regexp (make-regexp "([0-9:,]+) --> ([0-9:,]+)")))
38     (lambda (s)
39       "Parse the SubRip formatted time span in the string S and return
40 two values: the start time and the end time.  Valid input looks like
41 '00:00:03.417 --> 00:00:04.936'."
42       (let ((match (regexp-exec regexp s)))
43         (values (parse-time (match:substring match 1))
44                 (parse-time (match:substring match 2)))))))
45
46 (define (read-subrip port)
47   "Read a SubRip formatted subtitle from PORT."
48   (let-values (((id) (string->number (read-line port)))
49                ((start end) (parse-time-span (read-line port)))
50                ((lines) (let loop ((lines '()))
51                           (let ((line (read-line port)))
52                             (if (or (eof-object? line)
53                                     (and (string-null? line)
54                                          ;; A subtitle may be a blank line!
55                                          (not (null? lines))))
56                                 lines
57                                 (loop (cons line lines)))))))
58     (make-subtitle id start end lines)))
59
60 (define (read-subrips port)
61   "Read all SubRip formatted subtitles from PORT."
62   (reverse
63    (let loop ((subs '()))
64      (if (eof-object? (peek-char port))
65          subs
66          (loop (cons (read-subrip port) subs))))))