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