Tweak previous.
[libsub.git] / src / ssa_reader.cc
1 /*
2     Copyright (C) 2016 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include "ssa_reader.h"
21 #include "util.h"
22 #include "sub_assert.h"
23 #include "raw_convert.h"
24 #include "subtitle.h"
25 #include <locked_sstream.h>
26 #include <boost/algorithm/string.hpp>
27 #include <boost/bind.hpp>
28 #include <boost/foreach.hpp>
29 #include <iostream>
30 #include <vector>
31
32 using std::string;
33 using std::vector;
34 using std::map;
35 using std::cout;
36 using std::list;
37 using boost::optional;
38 using boost::function;
39 using namespace boost::algorithm;
40 using namespace sub;
41
42 /** @param s Subtitle string encoded in UTF-8 */
43 SSAReader::SSAReader (string const & s)
44 {
45         locked_stringstream str (s);
46         this->read (boost::bind (&get_line_stringstream, &str));
47 }
48
49 /** @param f Subtitle file encoded in UTF-8 */
50 SSAReader::SSAReader (FILE* f)
51 {
52         this->read (boost::bind (&get_line_file, f));
53 }
54
55 class Style
56 {
57 public:
58         Style ()
59                 : font_size (72)
60                 , primary_colour (255, 255, 255)
61                 , bold (false)
62                 , italic (false)
63                 , underline (false)
64                 , horizontal_reference (HORIZONTAL_CENTRE_OF_SCREEN)
65                 , vertical_reference (BOTTOM_OF_SCREEN)
66                 , vertical_margin (0)
67         {}
68
69         Style (string format_line, string style_line)
70                 : font_size (72)
71                 , primary_colour (255, 255, 255)
72                 , bold (false)
73                 , italic (false)
74                 , underline (false)
75                 , horizontal_reference (HORIZONTAL_CENTRE_OF_SCREEN)
76                 , vertical_reference (BOTTOM_OF_SCREEN)
77                 , vertical_margin (0)
78         {
79                 vector<string> keys;
80                 split (keys, format_line, boost::is_any_of (","));
81                 vector<string> style;
82                 split (style, style_line, boost::is_any_of (","));
83
84                 SUB_ASSERT (!keys.empty());
85                 SUB_ASSERT (!style.empty());
86                 SUB_ASSERT (keys.size() == style.size());
87
88                 for (size_t i = 0; i < style.size(); ++i) {
89                         trim (keys[i]);
90                         trim (style[i]);
91                         if (keys[i] == "Name") {
92                                 name = style[i];
93                         } else if (keys[i] == "Fontname") {
94                                 font_name = style[i];
95                         } else if (keys[i] == "Fontsize") {
96                                 font_size = raw_convert<int> (style[i]);
97                         } else if (keys[i] == "PrimaryColour") {
98                                 primary_colour = colour (raw_convert<int> (style[i]));
99                         } else if (keys[i] == "BackColour") {
100                                 back_colour = colour (raw_convert<int> (style[i]));
101                         } else if (keys[i] == "Bold") {
102                                 bold = style[i] == "-1";
103                         } else if (keys[i] == "Italic") {
104                                 italic = style[i] == "-1";
105                         } else if (keys[i] == "Underline") {
106                                 underline = style[i] == "-1";
107                         } else if (keys[i] == "BorderStyle") {
108                                 if (style[i] == "1") {
109                                         effect = SHADOW;
110                                 }
111                         } else if (keys[i] == "Alignment") {
112                                 /* These values from libass' source code */
113                                 switch ((raw_convert<int> (style[i]) - 1) % 3) {
114                                 case 0:
115                                         horizontal_reference = LEFT_OF_SCREEN;
116                                         break;
117                                 case 1:
118                                         horizontal_reference = HORIZONTAL_CENTRE_OF_SCREEN;
119                                         break;
120                                 case 2:
121                                         horizontal_reference = RIGHT_OF_SCREEN;
122                                         break;
123                                 }
124                                 switch (raw_convert<int> (style[i]) & 12) {
125                                 case 4:
126                                         vertical_reference = TOP_OF_SCREEN;
127                                         break;
128                                 case 8:
129                                         vertical_reference = VERTICAL_CENTRE_OF_SCREEN;
130                                         break;
131                                 case 0:
132                                         vertical_reference = BOTTOM_OF_SCREEN;
133                                         break;
134                                 }
135                         } else if (keys[i] == "MarginV") {
136                                 vertical_margin = raw_convert<int> (style[i]);
137                         }
138                 }
139         }
140
141         string name;
142         optional<string> font_name;
143         int font_size;
144         Colour primary_colour;
145         /** outline colour */
146         optional<Colour> back_colour;
147         bool bold;
148         bool italic;
149         bool underline;
150         optional<Effect> effect;
151         HorizontalReference horizontal_reference;
152         VerticalReference vertical_reference;
153         int vertical_margin;
154
155 private:
156         Colour colour (int c) const
157         {
158                 return Colour (
159                         ((c & 0x0000ff) >>  0) / 255.0,
160                         ((c & 0x00ff00) >>  8) / 255.0,
161                         ((c & 0xff0000) >> 16) / 255.0
162                         );
163         }
164 };
165
166 Time
167 SSAReader::parse_time (string t) const
168 {
169         vector<string> bits;
170         split (bits, t, is_any_of (":."));
171         SUB_ASSERT (bits.size() == 4);
172         return Time::from_hms (
173                 raw_convert<int> (bits[0]),
174                 raw_convert<int> (bits[1]),
175                 raw_convert<int> (bits[2]),
176                 raw_convert<int> (bits[3]) * 10
177                 );
178 }
179
180 /** @param base RawSubtitle filled in with any required common values.
181  *  @param line SSA line string (i.e. just the subtitle, possibly with embedded stuff)
182  *  @return List of RawSubtitles to represent line with vertical reference TOP_OF_SUBTITLE.
183  */
184 list<RawSubtitle>
185 SSAReader::parse_line (RawSubtitle base, string line, int play_res_x, int play_res_y)
186 {
187         enum {
188                 TEXT,
189                 STYLE,
190                 BACKSLASH
191         } state = TEXT;
192
193         list<RawSubtitle> subs;
194         RawSubtitle current = base;
195         string style;
196
197         if (!current.vertical_position.reference) {
198                 current.vertical_position.reference = BOTTOM_OF_SCREEN;
199         }
200
201         if (!current.vertical_position.proportional) {
202                 current.vertical_position.proportional = 0;
203         }
204
205         /* We must have a font size, as there could be a margin specified
206            in pixels and in that case we must know how big the subtitle
207            lines are to work out the position on screen.
208         */
209         if (!current.font_size.points()) {
210                 current.font_size.set_points (72);
211         }
212
213         /* Count the number of line breaks */
214         int line_breaks = 0;
215         if (line.length() > 0) {
216                 for (size_t i = 0; i < line.length() - 1; ++i) {
217                         if (line[i] == '\\' && (line[i+1] == 'n' || line[i+1] == 'N')) {
218                                 ++line_breaks;
219                         }
220                 }
221         }
222
223         /* Imagine that the screen is 792 points (i.e. 11 inches) high (as with DCP) */
224         double const line_size = current.font_size.proportional(792) * 1.2;
225
226         /* Tweak vertical_position accordingly */
227         switch (current.vertical_position.reference.get()) {
228         case TOP_OF_SCREEN:
229         case TOP_OF_SUBTITLE:
230                 /* Nothing to do */
231                 break;
232         case VERTICAL_CENTRE_OF_SCREEN:
233                 current.vertical_position.proportional = current.vertical_position.proportional.get() - ((line_breaks + 1) * line_size) / 2;
234                 break;
235         case BOTTOM_OF_SCREEN:
236                 current.vertical_position.proportional = current.vertical_position.proportional.get() + line_breaks * line_size;
237                 break;
238         }
239
240         for (size_t i = 0; i < line.length(); ++i) {
241                 char const c = line[i];
242                 switch (state) {
243                 case TEXT:
244                         if (c == '{') {
245                                 state = STYLE;
246                         } else if (c == '\\') {
247                                 state = BACKSLASH;
248                         } else if (c != '\r' && c != '\n') {
249                                 current.text += c;
250                         }
251                         break;
252                 case STYLE:
253                         if (c == '}' || c == '\\') {
254                                 if (!current.text.empty ()) {
255                                         subs.push_back (current);
256                                         current.text = "";
257                                 }
258                                 if (style == "\\i1") {
259                                         current.italic = true;
260                                 } else if (style == "\\i0" || style == "\\i") {
261                                         current.italic = false;
262                                 } else if (style == "\\b1") {
263                                         current.bold = true;
264                                 } else if (style == "\\b0") {
265                                         current.bold = false;
266                                 } else if (style == "\\u1") {
267                                         current.underline = true;
268                                 } else if (style == "\\u0") {
269                                         current.underline = false;
270                                 } else if (style == "\\an1" || style == "\\an2" || style == "\\an3") {
271                                         current.vertical_position.reference = sub::BOTTOM_OF_SCREEN;
272                                 } else if (style == "\\an4" || style == "\\an5" || style == "\\an6") {
273                                         current.vertical_position.reference = sub::VERTICAL_CENTRE_OF_SCREEN;
274                                 } else if (style == "\\an7" || style == "\\an8" || style == "\\an9") {
275                                         current.vertical_position.reference = sub::TOP_OF_SCREEN;
276                                 } else if (boost::starts_with(style, "\\pos")) {
277                                         vector<string> bits;
278                                         boost::algorithm::split (bits, style, boost::is_any_of("(,"));
279                                         SUB_ASSERT (bits.size() == 3);
280                                         current.horizontal_position.reference = sub::LEFT_OF_SCREEN;
281                                         current.horizontal_position.proportional = raw_convert<float>(bits[1]) / play_res_x;
282                                         current.vertical_position.reference = sub::TOP_OF_SCREEN;
283                                         current.vertical_position.proportional = raw_convert<float>(bits[2]) / play_res_y;
284                                 } else if (boost::starts_with(style, "\\fs")) {
285                                         SUB_ASSERT (style.length() > 3);
286                                         current.font_size.set_points (raw_convert<int>(style.substr(3)));
287                                 }
288                                 style = "";
289                         }
290
291                         if (c == '}') {
292                                 state = TEXT;
293                         } else {
294                                 style += c;
295                         }
296                         break;
297                 case BACKSLASH:
298                         if (c == 'n' || c == 'N') {
299                                 if (!current.text.empty ()) {
300                                         subs.push_back (current);
301                                         current.text = "";
302                                 }
303                                 /* Move down one line (1.2 times the font size) */
304                                 if (current.vertical_position.reference.get() == BOTTOM_OF_SCREEN) {
305                                         current.vertical_position.proportional = current.vertical_position.proportional.get() - line_size;
306                                 } else {
307                                         current.vertical_position.proportional = current.vertical_position.proportional.get() + line_size;
308                                 }
309                         }
310                         state = TEXT;
311                         break;
312                 }
313         }
314
315         if (!current.text.empty ()) {
316                 subs.push_back (current);
317         }
318
319         return subs;
320 }
321
322 void
323 SSAReader::read (function<optional<string> ()> get_line)
324 {
325         enum {
326                 INFO,
327                 STYLES,
328                 EVENTS
329         } part = INFO;
330
331         int play_res_x = 288;
332         int play_res_y = 288;
333         map<string, Style> styles;
334         string style_format_line;
335         vector<string> event_format;
336
337         while (true) {
338                 optional<string> line = get_line ();
339                 if (!line) {
340                         break;
341                 }
342
343                 trim (*line);
344                 remove_unicode_bom (line);
345
346                 if (starts_with (*line, ";") || line->empty ()) {
347                         continue;
348                 }
349
350                 if (starts_with (*line, "[")) {
351                         /* Section heading */
352                         if (line.get() == "[Script Info]") {
353                                 part = INFO;
354                         } else if (line.get() == "[V4 Styles]" || line.get() == "[V4+ Styles]") {
355                                 part = STYLES;
356                         } else if (line.get() == "[Events]") {
357                                 part = EVENTS;
358                         }
359                         continue;
360                 }
361
362                 size_t const colon = line->find (":");
363                 SUB_ASSERT (colon != string::npos);
364                 string const type = line->substr (0, colon);
365                 string body = line->substr (colon + 1);
366                 trim (body);
367
368                 switch (part) {
369                 case INFO:
370                         if (type == "PlayResX") {
371                                 play_res_x = raw_convert<int> (body);
372                         } else if (type == "PlayResY") {
373                                 play_res_y = raw_convert<int> (body);
374                         }
375                         break;
376                 case STYLES:
377                         if (type == "Format") {
378                                 style_format_line = body;
379                         } else if (type == "Style") {
380                                 SUB_ASSERT (!style_format_line.empty ());
381                                 Style s (style_format_line, body);
382                                 styles[s.name] = s;
383                         }
384                         break;
385                 case EVENTS:
386                         if (type == "Format") {
387                                 split (event_format, body, is_any_of (","));
388                                 BOOST_FOREACH (string& i, event_format) {
389                                         trim (i);
390                                 }
391                         } else if (type == "Dialogue") {
392                                 SUB_ASSERT (!event_format.empty ());
393                                 vector<string> event;
394                                 split (event, body, is_any_of (","));
395
396                                 /* There may be commas in the subtitle part; reassemble any extra parts
397                                    from when we just split it.
398                                 */
399                                 while (event.size() > event_format.size()) {
400                                         string const ex = event.back ();
401                                         event.pop_back ();
402                                         event.back() += "," + ex;
403                                 }
404
405                                 SUB_ASSERT (!event.empty());
406                                 SUB_ASSERT (event_format.size() == event.size());
407
408                                 RawSubtitle sub;
409
410                                 for (size_t i = 0; i < event.size(); ++i) {
411                                         trim (event[i]);
412                                         if (event_format[i] == "Start") {
413                                                 sub.from = parse_time (event[i]);
414                                         } else if (event_format[i] == "End") {
415                                                 sub.to = parse_time (event[i]);
416                                         } else if (event_format[i] == "Style") {
417                                                 /* libass trims leading '*'s from style names, commenting that
418                                                    "they seem to mean literally nothing".  Go figure...
419                                                 */
420                                                 trim_left_if (event[i], boost::is_any_of ("*"));
421                                                 SUB_ASSERT (styles.find(event[i]) != styles.end());
422                                                 Style style = styles[event[i]];
423                                                 sub.font = style.font_name;
424                                                 sub.font_size = FontSize::from_points (style.font_size);
425                                                 sub.colour = style.primary_colour;
426                                                 sub.effect_colour = style.back_colour;
427                                                 sub.bold = style.bold;
428                                                 sub.italic = style.italic;
429                                                 sub.underline = style.underline;
430                                                 sub.effect = style.effect;
431                                                 sub.horizontal_position.reference = style.horizontal_reference;
432                                                 sub.vertical_position.reference = style.vertical_reference;
433                                                 sub.vertical_position.proportional = float(style.vertical_margin) / play_res_y;
434                                         } else if (event_format[i] == "MarginV") {
435                                                 sub.vertical_position.proportional = raw_convert<float>(event[i]) / play_res_y;
436                                         } else if (event_format[i] == "Text") {
437                                                 BOOST_FOREACH (sub::RawSubtitle j, parse_line (sub, event[i], play_res_x, play_res_y)) {
438                                                         _subs.push_back (j);
439                                                 }
440                                         }
441                                 }
442                         }
443                 }
444
445         }
446 }