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