Use libcxml. Lump all static configuration flags into one.
[libdcp.git] / src / subtitle_asset.cc
1 /*
2     Copyright (C) 2012 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 <fstream>
21 #include <boost/lexical_cast.hpp>
22 #include <boost/algorithm/string.hpp>
23 #include "subtitle_asset.h"
24 #include "util.h"
25 #include "xml.h"
26
27 using std::string;
28 using std::list;
29 using std::ostream;
30 using std::ofstream;
31 using std::stringstream;
32 using boost::shared_ptr;
33 using boost::lexical_cast;
34 using boost::optional;
35 using namespace libdcp;
36
37 SubtitleAsset::SubtitleAsset (string directory, string xml_file)
38         : Asset (directory, xml_file)
39         , _need_sort (false)
40 {
41         read_xml (path().string());
42 }
43
44 SubtitleAsset::SubtitleAsset (string directory, string movie_title, string language)
45         : Asset (directory)
46         , _movie_title (movie_title)
47         , _reel_number ("1")
48         , _language (language)
49         , _need_sort (false)
50 {
51
52 }
53
54 void
55 SubtitleAsset::read_xml (string xml_file)
56 {
57         shared_ptr<cxml::File> xml (new cxml::File (xml_file, "DCSubtitle"));
58         
59         _uuid = xml->string_child ("SubtitleID");
60         _movie_title = xml->string_child ("MovieTitle");
61         _reel_number = xml->string_child ("ReelNumber");
62         _language = xml->string_child ("Language");
63
64         xml->ignore_child ("LoadFont");
65
66         list<shared_ptr<FontNode> > font_nodes = type_children<FontNode> (xml, "Font");
67         _load_font_nodes = type_children<LoadFontNode> (xml, "LoadFont");
68
69         /* Now make Subtitle objects to represent the raw XML nodes
70            in a sane way.
71         */
72
73         ParseState parse_state;
74         examine_font_nodes (xml, font_nodes, parse_state);
75 }
76
77 void
78 SubtitleAsset::examine_font_nodes (
79         shared_ptr<const cxml::Node> xml,
80         list<shared_ptr<FontNode> > const & font_nodes,
81         ParseState& parse_state
82         )
83 {
84         for (list<shared_ptr<FontNode> >::const_iterator i = font_nodes.begin(); i != font_nodes.end(); ++i) {
85
86                 parse_state.font_nodes.push_back (*i);
87                 maybe_add_subtitle ((*i)->text, parse_state);
88
89                 for (list<shared_ptr<SubtitleNode> >::iterator j = (*i)->subtitle_nodes.begin(); j != (*i)->subtitle_nodes.end(); ++j) {
90                         parse_state.subtitle_nodes.push_back (*j);
91                         examine_text_nodes (xml, (*j)->text_nodes, parse_state);
92                         examine_font_nodes (xml, (*j)->font_nodes, parse_state);
93                         parse_state.subtitle_nodes.pop_back ();
94                 }
95         
96                 examine_font_nodes (xml, (*i)->font_nodes, parse_state);
97                 examine_text_nodes (xml, (*i)->text_nodes, parse_state);
98                 
99                 parse_state.font_nodes.pop_back ();
100         }
101 }
102
103 void
104 SubtitleAsset::examine_text_nodes (
105         shared_ptr<const cxml::Node> xml,
106         list<shared_ptr<TextNode> > const & text_nodes,
107         ParseState& parse_state
108         )
109 {
110         for (list<shared_ptr<TextNode> >::const_iterator i = text_nodes.begin(); i != text_nodes.end(); ++i) {
111                 parse_state.text_nodes.push_back (*i);
112                 maybe_add_subtitle ((*i)->text, parse_state);
113                 examine_font_nodes (xml, (*i)->font_nodes, parse_state);
114                 parse_state.text_nodes.pop_back ();
115         }
116 }
117
118 void
119 SubtitleAsset::maybe_add_subtitle (string text, ParseState const & parse_state)
120 {
121         if (empty_or_white_space (text)) {
122                 return;
123         }
124         
125         if (parse_state.text_nodes.empty() || parse_state.subtitle_nodes.empty ()) {
126                 return;
127         }
128
129         assert (!parse_state.text_nodes.empty ());
130         assert (!parse_state.subtitle_nodes.empty ());
131         
132         FontNode effective_font (parse_state.font_nodes);
133         TextNode effective_text (*parse_state.text_nodes.back ());
134         SubtitleNode effective_subtitle (*parse_state.subtitle_nodes.back ());
135
136         _subtitles.push_back (
137                 shared_ptr<Subtitle> (
138                         new Subtitle (
139                                 font_id_to_name (effective_font.id),
140                                 effective_font.italic.get(),
141                                 effective_font.color.get(),
142                                 effective_font.size,
143                                 effective_subtitle.in,
144                                 effective_subtitle.out,
145                                 effective_text.v_position,
146                                 effective_text.v_align,
147                                 text,
148                                 effective_font.effect ? effective_font.effect.get() : NONE,
149                                 effective_font.effect_color.get(),
150                                 effective_subtitle.fade_up_time,
151                                 effective_subtitle.fade_down_time
152                                 )
153                         )
154                 );
155 }
156
157 FontNode::FontNode (shared_ptr<const cxml::Node> node)
158 {
159         text = node->content ();
160         
161         id = node->optional_string_attribute ("Id").get_value_or ("");
162         size = node->optional_number_attribute<int64_t> ("Size").get_value_or (0);
163         italic = node->optional_bool_attribute ("Italic").get_value_or (false);
164         optional<string> c = node->optional_string_attribute ("Color");
165         if (c) {
166                 color = Color (c.get ());
167         }
168         optional<string> const e = node->optional_string_attribute ("Effect");
169         if (e) {
170                 effect = string_to_effect (e.get ());
171         }
172         c = node->optional_string_attribute ( "EffectColor");
173         if (c) {
174                 effect_color = Color (c.get ());
175         }
176         subtitle_nodes = type_children<SubtitleNode> (node, "Subtitle");
177         font_nodes = type_children<FontNode> (node, "Font");
178         text_nodes = type_children<TextNode> (node, "Text");
179 }
180
181 FontNode::FontNode (list<shared_ptr<FontNode> > const & font_nodes)
182         : size (0)
183         , italic (false)
184         , color ("FFFFFFFF")
185         , effect_color ("FFFFFFFF")
186 {
187         for (list<shared_ptr<FontNode> >::const_iterator i = font_nodes.begin(); i != font_nodes.end(); ++i) {
188                 if (!(*i)->id.empty ()) {
189                         id = (*i)->id;
190                 }
191                 if ((*i)->size != 0) {
192                         size = (*i)->size;
193                 }
194                 if ((*i)->italic) {
195                         italic = (*i)->italic.get ();
196                 }
197                 if ((*i)->color) {
198                         color = (*i)->color.get ();
199                 }
200                 if ((*i)->effect) {
201                         effect = (*i)->effect.get ();
202                 }
203                 if ((*i)->effect_color) {
204                         effect_color = (*i)->effect_color.get ();
205                 }
206         }
207 }
208
209 LoadFontNode::LoadFontNode (shared_ptr<const cxml::Node> node)
210 {
211         id = node->string_attribute ("Id");
212         uri = node->string_attribute ("URI");
213 }
214         
215
216 SubtitleNode::SubtitleNode (shared_ptr<const cxml::Node> node)
217 {
218         in = Time (node->string_attribute ("TimeIn"));
219         out = Time (node->string_attribute ("TimeOut"));
220         font_nodes = type_children<FontNode> (node, "Font");
221         text_nodes = type_children<TextNode> (node, "Text");
222         fade_up_time = fade_time (node, "FadeUpTime");
223         fade_down_time = fade_time (node, "FadeDownTime");
224 }
225
226 Time
227 SubtitleNode::fade_time (shared_ptr<const cxml::Node> node, string name)
228 {
229         string const u = node->optional_string_attribute (name).get_value_or ("");
230         Time t;
231         
232         if (u.empty ()) {
233                 t = Time (0, 0, 0, 20);
234         } else if (u.find (":") != string::npos) {
235                 t = Time (u);
236         } else {
237                 t = Time (0, 0, 0, lexical_cast<int> (u));
238         }
239
240         if (t > Time (0, 0, 8, 0)) {
241                 t = Time (0, 0, 8, 0);
242         }
243
244         return t;
245 }
246
247 TextNode::TextNode (shared_ptr<const cxml::Node> node)
248         : v_align (CENTER)
249 {
250         text = node->content ();
251         v_position = node->number_attribute<float> ("VPosition");
252         optional<string> v = node->optional_string_attribute ("VAlign");
253         if (v) {
254                 v_align = string_to_valign (v.get ());
255         }
256
257         font_nodes = type_children<FontNode> (node, "Font");
258 }
259
260 list<shared_ptr<Subtitle> >
261 SubtitleAsset::subtitles_at (Time t) const
262 {
263         list<shared_ptr<Subtitle> > s;
264         for (list<shared_ptr<Subtitle> >::const_iterator i = _subtitles.begin(); i != _subtitles.end(); ++i) {
265                 if ((*i)->in() <= t && t <= (*i)->out ()) {
266                         s.push_back (*i);
267                 }
268         }
269
270         return s;
271 }
272
273 std::string
274 SubtitleAsset::font_id_to_name (string id) const
275 {
276         list<shared_ptr<LoadFontNode> >::const_iterator i = _load_font_nodes.begin();
277         while (i != _load_font_nodes.end() && (*i)->id != id) {
278                 ++i;
279         }
280
281         if (i == _load_font_nodes.end ()) {
282                 return "";
283         }
284
285         if ((*i)->uri == "arial.ttf") {
286                 return "Arial";
287         }
288
289         return "";
290 }
291
292 Subtitle::Subtitle (
293         string font,
294         bool italic,
295         Color color,
296         int size,
297         Time in,
298         Time out,
299         float v_position,
300         VAlign v_align,
301         string text,
302         Effect effect,
303         Color effect_color,
304         Time fade_up_time,
305         Time fade_down_time
306         )
307         : _font (font)
308         , _italic (italic)
309         , _color (color)
310         , _size (size)
311         , _in (in)
312         , _out (out)
313         , _v_position (v_position)
314         , _v_align (v_align)
315         , _text (text)
316         , _effect (effect)
317         , _effect_color (effect_color)
318         , _fade_up_time (fade_up_time)
319         , _fade_down_time (fade_down_time)
320 {
321
322 }
323
324 int
325 Subtitle::size_in_pixels (int screen_height) const
326 {
327         /* Size in the subtitle file is given in points as if the screen
328            height is 11 inches, so a 72pt font would be 1/11th of the screen
329            height.
330         */
331         
332         return _size * screen_height / (11 * 72);
333 }
334
335 bool
336 libdcp::operator== (Subtitle const & a, Subtitle const & b)
337 {
338         return (
339                 a.font() == b.font() &&
340                 a.italic() == b.italic() &&
341                 a.color() == b.color() &&
342                 a.size() == b.size() &&
343                 a.in() == b.in() &&
344                 a.out() == b.out() &&
345                 a.v_position() == b.v_position() &&
346                 a.v_align() == b.v_align() &&
347                 a.text() == b.text() &&
348                 a.effect() == b.effect() &&
349                 a.effect_color() == b.effect_color() &&
350                 a.fade_up_time() == b.fade_up_time() &&
351                 a.fade_down_time() == b.fade_down_time()
352                 );
353 }
354
355 ostream&
356 libdcp::operator<< (ostream& s, Subtitle const & sub)
357 {
358         s << "\n`" << sub.text() << "' from " << sub.in() << " to " << sub.out() << ";\n"
359           << "fade up " << sub.fade_up_time() << ", fade down " << sub.fade_down_time() << ";\n"
360           << "font " << sub.font() << ", ";
361
362         if (sub.italic()) {
363                 s << "italic";
364         } else {
365                 s << "non-italic";
366         }
367         
368         s << ", size " << sub.size() << ", color " << sub.color() << ", vpos " << sub.v_position() << ", valign " << ((int) sub.v_align()) << ";\n"
369           << "effect " << ((int) sub.effect()) << ", effect color " << sub.effect_color();
370
371         return s;
372 }
373
374 void
375 SubtitleAsset::add (shared_ptr<Subtitle> s)
376 {
377         _subtitles.push_back (s);
378         _need_sort = true;
379 }
380
381 void
382 SubtitleAsset::write_to_cpl (ostream& s) const
383 {
384         /* XXX: should EditRate, Duration and IntrinsicDuration be in here? */
385         
386         s << "        <MainSubtitle>\n"
387           << "          <Id>urn:uuid:" << _uuid << "</Id>\n"
388           << "          <AnnotationText>" << _file_name << "</AnnotationText>\n"
389           << "          <EntryPoint>0</EntryPoint>\n"
390           << "        </MainSubtitle>\n";
391 }
392
393 struct SubtitleSorter {
394         bool operator() (shared_ptr<Subtitle> a, shared_ptr<Subtitle> b) {
395                 if (a->in() != b->in()) {
396                         return a->in() < b->in();
397                 }
398                 return a->v_position() < b->v_position();
399         }
400 };
401
402 void
403 SubtitleAsset::write_xml () const
404 {
405         ofstream f (path().string().c_str());
406         write_xml (f);
407 }
408
409 void
410 SubtitleAsset::write_xml (ostream& s) const
411 {
412         s << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
413           << "<DCSubtitle Version=\"1.0\">\n"
414           << "  <SubtitleID>" << _uuid << "</SubtitleID>\n"
415           << "  <MovieTitle>" << _movie_title << "</MovieTitle>\n"
416           << "  <ReelNumber>" << _reel_number << "</ReelNumber>\n"
417           << "  <Language>" << _language << "</Language>\n";
418
419         if (_load_font_nodes.size() > 1) {
420                 boost::throw_exception (MiscError ("multiple LoadFont nodes not supported"));
421         }
422
423         if (!_load_font_nodes.empty ()) {
424                 s << "  <LoadFont Id=\"" << _load_font_nodes.front()->id << "\" URI=\"" << _load_font_nodes.front()->uri << "\"/>\n";
425         }
426
427         list<shared_ptr<Subtitle> > sorted = _subtitles;
428         if (_need_sort) {
429                 sorted.sort (SubtitleSorter ());
430         }
431
432         /* XXX: multiple fonts not supported */
433         /* XXX: script, underlined, weight not supported */
434
435         bool first = true;
436         bool italic = false;
437         Color color;
438         int size = 0;
439         Effect effect = NONE;
440         Color effect_color;
441         int spot_number = 1;
442         Time last_in;
443         Time last_out;
444         Time last_fade_up_time;
445         Time last_fade_down_time;
446
447         for (list<shared_ptr<Subtitle> >::iterator i = sorted.begin(); i != sorted.end(); ++i) {
448
449                 /* We will start a new <Font>...</Font> whenever some font property changes.
450                    I suppose should really make an optimal hierarchy of <Font> tags, but
451                    that seems hard.
452                 */
453
454                 bool const font_changed = first              ||
455                         italic       != (*i)->italic()       ||
456                         color        != (*i)->color()        ||
457                         size         != (*i)->size()         ||
458                         effect       != (*i)->effect()       ||
459                         effect_color != (*i)->effect_color();
460
461                 stringstream a;
462                 if (font_changed) {
463                         italic = (*i)->italic ();
464                         a << "Italic=\"" << (italic ? "yes" : "no") << "\" ";
465                         color = (*i)->color ();
466                         a << "Color=\"" << color.to_argb_string() << "\" ";
467                         size = (*i)->size ();
468                         a << "Size=\"" << size << "\" ";
469                         effect = (*i)->effect ();
470                         a << "Effect=\"" << effect_to_string(effect) << "\" ";
471                         effect_color = (*i)->effect_color ();
472                         a << "EffectColor=\"" << effect_color.to_argb_string() << "\" ";
473                         a << "Script=\"normal\" Underlined=\"no\" Weight=\"normal\"";
474                 }
475
476                 if (first || font_changed ||
477                     (last_in != (*i)->in() ||
478                      last_out != (*i)->out() ||
479                      last_fade_up_time != (*i)->fade_up_time() ||
480                      last_fade_down_time != (*i)->fade_down_time()
481                             )) {
482
483                         if (!first) {
484                                 s << "  </Subtitle>\n";
485                         }
486
487                         if (font_changed) {
488                                 if (!first) {
489                                         s << "  </Font>\n";
490                                 }
491
492                                 string id = "theFontId";
493                                 if (!_load_font_nodes.empty()) {
494                                         id = _load_font_nodes.front()->id;
495                                 }
496                                 
497                                 s << "  <Font Id=\"" << id << "\" " << a.str() << ">\n";
498                         }
499
500                         s << "  <Subtitle "
501                           << "SpotNumber=\"" << spot_number++ << "\" "
502                           << "TimeIn=\"" << (*i)->in().to_string() << "\" "
503                           << "TimeOut=\"" << (*i)->out().to_string() << "\" "
504                           << "FadeUpTime=\"" << (*i)->fade_up_time().to_ticks() << "\" "
505                           << "FadeDownTime=\"" << (*i)->fade_down_time().to_ticks() << "\""
506                           << ">\n";
507
508                         last_in = (*i)->in ();
509                         last_out = (*i)->out ();
510                         last_fade_up_time = (*i)->fade_up_time ();
511                         last_fade_down_time = (*i)->fade_down_time ();
512                 }
513
514                 s << "      <Text "
515                   << "VAlign=\"" << valign_to_string ((*i)->v_align()) << "\" "
516                   << "VPosition=\"" << (*i)->v_position() << "\""
517                   << ">" << escape ((*i)->text()) << "</Text>\n";
518
519                 first = false;
520         }
521
522         s << "  </Subtitle>\n";
523         s << "  </Font>\n";
524         s << "</DCSubtitle>\n";
525 }
526
527 /** XXX: Another reason why we should be writing with libxml++ */
528 string
529 SubtitleAsset::escape (string s) const
530 {
531         boost::replace_all (s, "&", "&amp;");
532         return s;
533 }