Use libxml++ for writing XML.
[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<libdcp::parse::Font> > font_nodes = type_children<libdcp::parse::Font> (xml, "Font");
67         _load_font_nodes = type_children<libdcp::parse::LoadFont> (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<libdcp::parse::Font> > const & font_nodes,
81         ParseState& parse_state
82         )
83 {
84         for (list<shared_ptr<libdcp::parse::Font> >::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<libdcp::parse::Subtitle> >::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<libdcp::parse::Text> > const & text_nodes,
107         ParseState& parse_state
108         )
109 {
110         for (list<shared_ptr<libdcp::parse::Text> >::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         libdcp::parse::Font effective_font (parse_state.font_nodes);
133         libdcp::parse::Text effective_text (*parse_state.text_nodes.back ());
134         libdcp::parse::Subtitle 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 list<shared_ptr<Subtitle> >
158 SubtitleAsset::subtitles_at (Time t) const
159 {
160         list<shared_ptr<Subtitle> > s;
161         for (list<shared_ptr<Subtitle> >::const_iterator i = _subtitles.begin(); i != _subtitles.end(); ++i) {
162                 if ((*i)->in() <= t && t <= (*i)->out ()) {
163                         s.push_back (*i);
164                 }
165         }
166
167         return s;
168 }
169
170 std::string
171 SubtitleAsset::font_id_to_name (string id) const
172 {
173         list<shared_ptr<libdcp::parse::LoadFont> >::const_iterator i = _load_font_nodes.begin();
174         while (i != _load_font_nodes.end() && (*i)->id != id) {
175                 ++i;
176         }
177
178         if (i == _load_font_nodes.end ()) {
179                 return "";
180         }
181
182         if ((*i)->uri == "arial.ttf") {
183                 return "Arial";
184         }
185
186         return "";
187 }
188
189 Subtitle::Subtitle (
190         string font,
191         bool italic,
192         Color color,
193         int size,
194         Time in,
195         Time out,
196         float v_position,
197         VAlign v_align,
198         string text,
199         Effect effect,
200         Color effect_color,
201         Time fade_up_time,
202         Time fade_down_time
203         )
204         : _font (font)
205         , _italic (italic)
206         , _color (color)
207         , _size (size)
208         , _in (in)
209         , _out (out)
210         , _v_position (v_position)
211         , _v_align (v_align)
212         , _text (text)
213         , _effect (effect)
214         , _effect_color (effect_color)
215         , _fade_up_time (fade_up_time)
216         , _fade_down_time (fade_down_time)
217 {
218
219 }
220
221 int
222 Subtitle::size_in_pixels (int screen_height) const
223 {
224         /* Size in the subtitle file is given in points as if the screen
225            height is 11 inches, so a 72pt font would be 1/11th of the screen
226            height.
227         */
228         
229         return _size * screen_height / (11 * 72);
230 }
231
232 bool
233 libdcp::operator== (Subtitle const & a, Subtitle const & b)
234 {
235         return (
236                 a.font() == b.font() &&
237                 a.italic() == b.italic() &&
238                 a.color() == b.color() &&
239                 a.size() == b.size() &&
240                 a.in() == b.in() &&
241                 a.out() == b.out() &&
242                 a.v_position() == b.v_position() &&
243                 a.v_align() == b.v_align() &&
244                 a.text() == b.text() &&
245                 a.effect() == b.effect() &&
246                 a.effect_color() == b.effect_color() &&
247                 a.fade_up_time() == b.fade_up_time() &&
248                 a.fade_down_time() == b.fade_down_time()
249                 );
250 }
251
252 ostream&
253 libdcp::operator<< (ostream& s, Subtitle const & sub)
254 {
255         s << "\n`" << sub.text() << "' from " << sub.in() << " to " << sub.out() << ";\n"
256           << "fade up " << sub.fade_up_time() << ", fade down " << sub.fade_down_time() << ";\n"
257           << "font " << sub.font() << ", ";
258
259         if (sub.italic()) {
260                 s << "italic";
261         } else {
262                 s << "non-italic";
263         }
264         
265         s << ", size " << sub.size() << ", color " << sub.color() << ", vpos " << sub.v_position() << ", valign " << ((int) sub.v_align()) << ";\n"
266           << "effect " << ((int) sub.effect()) << ", effect color " << sub.effect_color();
267
268         return s;
269 }
270
271 void
272 SubtitleAsset::add (shared_ptr<Subtitle> s)
273 {
274         _subtitles.push_back (s);
275         _need_sort = true;
276 }
277
278 void
279 SubtitleAsset::write_to_cpl (xmlpp::Node* node) const
280 {
281         /* XXX: should EditRate, Duration and IntrinsicDuration be in here? */
282
283         xmlpp::Node* ms = node->add_child ("MainSubtitle");
284         ms->add_child("Id")->add_child_text("urn:uuid:" + _uuid);
285         ms->add_child("AnnotationText")->add_child_text (_file_name);
286         /* XXX */
287         ms->add_child("EntryPoint")->add_child_text ("0");
288 }
289
290 struct SubtitleSorter {
291         bool operator() (shared_ptr<Subtitle> a, shared_ptr<Subtitle> b) {
292                 if (a->in() != b->in()) {
293                         return a->in() < b->in();
294                 }
295                 return a->v_position() < b->v_position();
296         }
297 };
298
299 void
300 SubtitleAsset::write_xml () const
301 {
302         ofstream s (path().string().c_str());
303         write_xml (s);
304 }
305
306 void
307 SubtitleAsset::write_xml (ostream& s) const
308 {
309         xmlpp::Document doc;
310         xmlpp::Element* root = doc.create_root_node ("DCSubtitle");
311         root->set_attribute ("Version", "1.0");
312
313         root->add_child("SubtitleID")->add_child_text (_uuid);
314         root->add_child("MovieTitle")->add_child_text (_movie_title);
315         root->add_child("ReelNumber")->add_child_text (lexical_cast<string> (_reel_number));
316         root->add_child("Language")->add_child_text (_language);
317
318         if (_load_font_nodes.size() > 1) {
319                 boost::throw_exception (MiscError ("multiple LoadFont nodes not supported"));
320         }
321
322         if (!_load_font_nodes.empty ()) {
323                 xmlpp::Element* load_font = root->add_child("LoadFont");
324                 load_font->set_attribute("Id", _load_font_nodes.front()->id);
325                 load_font->set_attribute("URI",  _load_font_nodes.front()->uri);
326         }
327
328         list<shared_ptr<Subtitle> > sorted = _subtitles;
329         if (_need_sort) {
330                 sorted.sort (SubtitleSorter ());
331         }
332
333         /* XXX: multiple fonts not supported */
334         /* XXX: script, underlined, weight not supported */
335
336         bool italic = false;
337         Color color;
338         int size = 0;
339         Effect effect = NONE;
340         Color effect_color;
341         int spot_number = 1;
342         Time last_in;
343         Time last_out;
344         Time last_fade_up_time;
345         Time last_fade_down_time;
346
347         xmlpp::Element* font = 0;
348         xmlpp::Element* subtitle = 0;
349
350         for (list<shared_ptr<Subtitle> >::iterator i = sorted.begin(); i != sorted.end(); ++i) {
351
352                 /* We will start a new <Font>...</Font> whenever some font property changes.
353                    I suppose we should really make an optimal hierarchy of <Font> tags, but
354                    that seems hard.
355                 */
356
357                 bool const font_changed =
358                         italic       != (*i)->italic()       ||
359                         color        != (*i)->color()        ||
360                         size         != (*i)->size()         ||
361                         effect       != (*i)->effect()       ||
362                         effect_color != (*i)->effect_color();
363
364                 if (font_changed) {
365                         italic = (*i)->italic ();
366                         color = (*i)->color ();
367                         size = (*i)->size ();
368                         effect = (*i)->effect ();
369                         effect_color = (*i)->effect_color ();
370                 }
371
372                 if (!font || font_changed) {
373                         font = root->add_child ("Font");
374                         string id = "theFontId";
375                         if (!_load_font_nodes.empty()) {
376                                 id = _load_font_nodes.front()->id;
377                         }
378                         font->set_attribute ("Id", id);
379                         font->set_attribute ("Italic", italic ? "yes" : "no");
380                         font->set_attribute ("Color", color.to_argb_string());
381                         font->set_attribute ("Size", lexical_cast<string> (size));
382                         font->set_attribute ("Effect", effect_to_string (effect));
383                         font->set_attribute ("EffectColor", effect_color.to_argb_string());
384                         font->set_attribute ("Script", "normal");
385                         font->set_attribute ("Underlined", "no");
386                         font->set_attribute ("Weight", "normal");
387                 }
388
389                 if (!subtitle ||
390                     (last_in != (*i)->in() ||
391                      last_out != (*i)->out() ||
392                      last_fade_up_time != (*i)->fade_up_time() ||
393                      last_fade_down_time != (*i)->fade_down_time()
394                             )) {
395
396                         subtitle = font->add_child ("Subtitle");
397                         subtitle->set_attribute ("SpotNumber", lexical_cast<string> (spot_number++));
398                         subtitle->set_attribute ("TimeIn", (*i)->in().to_string());
399                         subtitle->set_attribute ("TimeOut", (*i)->out().to_string());
400                         subtitle->set_attribute ("FadeUpTime", lexical_cast<string> ((*i)->fade_up_time().to_ticks()));
401                         subtitle->set_attribute ("FadeDownTime", lexical_cast<string> ((*i)->fade_down_time().to_ticks()));
402
403                         last_in = (*i)->in ();
404                         last_out = (*i)->out ();
405                         last_fade_up_time = (*i)->fade_up_time ();
406                         last_fade_down_time = (*i)->fade_down_time ();
407                 }
408
409                 xmlpp::Element* text = subtitle->add_child ("Text");
410                 text->set_attribute ("VAlign", valign_to_string ((*i)->v_align()));             
411                 text->set_attribute ("VPosition", lexical_cast<string> ((*i)->v_position()));
412                 text->add_child_text ((*i)->text());
413         }
414
415         doc.write_to_stream_formatted (s);
416 }
417