Try to fix application of namespace to MainStereoscopicPicture nodes.
[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 <libxml++/nodes/element.h>
24 #include "subtitle_asset.h"
25 #include "parse/subtitle.h"
26 #include "util.h"
27 #include "xml.h"
28
29 using std::string;
30 using std::list;
31 using std::ostream;
32 using std::ofstream;
33 using std::stringstream;
34 using boost::shared_ptr;
35 using boost::lexical_cast;
36 using boost::optional;
37 using namespace libdcp;
38
39 SubtitleAsset::SubtitleAsset (string directory, string xml_file)
40         : Asset (directory, xml_file)
41         , _need_sort (false)
42 {
43         read_xml (path().string());
44 }
45
46 SubtitleAsset::SubtitleAsset (string directory, string movie_title, string language)
47         : Asset (directory)
48         , _movie_title (movie_title)
49         , _reel_number ("1")
50         , _language (language)
51         , _need_sort (false)
52 {
53
54 }
55
56 void
57 SubtitleAsset::read_xml (string xml_file)
58 {
59         shared_ptr<cxml::File> xml (new cxml::File (xml_file, "DCSubtitle"));
60         
61         _uuid = xml->string_child ("SubtitleID");
62         _movie_title = xml->string_child ("MovieTitle");
63         _reel_number = xml->string_child ("ReelNumber");
64         _language = xml->string_child ("Language");
65
66         xml->ignore_child ("LoadFont");
67
68         list<shared_ptr<libdcp::parse::Font> > font_nodes = type_children<libdcp::parse::Font> (xml, "Font");
69         _load_font_nodes = type_children<libdcp::parse::LoadFont> (xml, "LoadFont");
70
71         /* Now make Subtitle objects to represent the raw XML nodes
72            in a sane way.
73         */
74
75         ParseState parse_state;
76         examine_font_nodes (xml, font_nodes, parse_state);
77 }
78
79 void
80 SubtitleAsset::examine_font_nodes (
81         shared_ptr<const cxml::Node> xml,
82         list<shared_ptr<libdcp::parse::Font> > const & font_nodes,
83         ParseState& parse_state
84         )
85 {
86         for (list<shared_ptr<libdcp::parse::Font> >::const_iterator i = font_nodes.begin(); i != font_nodes.end(); ++i) {
87
88                 parse_state.font_nodes.push_back (*i);
89                 maybe_add_subtitle ((*i)->text, parse_state);
90
91                 for (list<shared_ptr<libdcp::parse::Subtitle> >::iterator j = (*i)->subtitle_nodes.begin(); j != (*i)->subtitle_nodes.end(); ++j) {
92                         parse_state.subtitle_nodes.push_back (*j);
93                         examine_text_nodes (xml, (*j)->text_nodes, parse_state);
94                         examine_font_nodes (xml, (*j)->font_nodes, parse_state);
95                         parse_state.subtitle_nodes.pop_back ();
96                 }
97         
98                 examine_font_nodes (xml, (*i)->font_nodes, parse_state);
99                 examine_text_nodes (xml, (*i)->text_nodes, parse_state);
100                 
101                 parse_state.font_nodes.pop_back ();
102         }
103 }
104
105 void
106 SubtitleAsset::examine_text_nodes (
107         shared_ptr<const cxml::Node> xml,
108         list<shared_ptr<libdcp::parse::Text> > const & text_nodes,
109         ParseState& parse_state
110         )
111 {
112         for (list<shared_ptr<libdcp::parse::Text> >::const_iterator i = text_nodes.begin(); i != text_nodes.end(); ++i) {
113                 parse_state.text_nodes.push_back (*i);
114                 maybe_add_subtitle ((*i)->text, parse_state);
115                 examine_font_nodes (xml, (*i)->font_nodes, parse_state);
116                 parse_state.text_nodes.pop_back ();
117         }
118 }
119
120 void
121 SubtitleAsset::maybe_add_subtitle (string text, ParseState const & parse_state)
122 {
123         if (empty_or_white_space (text)) {
124                 return;
125         }
126         
127         if (parse_state.text_nodes.empty() || parse_state.subtitle_nodes.empty ()) {
128                 return;
129         }
130
131         assert (!parse_state.text_nodes.empty ());
132         assert (!parse_state.subtitle_nodes.empty ());
133         
134         libdcp::parse::Font effective_font (parse_state.font_nodes);
135         libdcp::parse::Text effective_text (*parse_state.text_nodes.back ());
136         libdcp::parse::Subtitle effective_subtitle (*parse_state.subtitle_nodes.back ());
137
138         _subtitles.push_back (
139                 shared_ptr<Subtitle> (
140                         new Subtitle (
141                                 font_id_to_name (effective_font.id),
142                                 effective_font.italic.get(),
143                                 effective_font.color.get(),
144                                 effective_font.size,
145                                 effective_subtitle.in,
146                                 effective_subtitle.out,
147                                 effective_text.v_position,
148                                 effective_text.v_align,
149                                 text,
150                                 effective_font.effect ? effective_font.effect.get() : NONE,
151                                 effective_font.effect_color.get(),
152                                 effective_subtitle.fade_up_time,
153                                 effective_subtitle.fade_down_time
154                                 )
155                         )
156                 );
157 }
158
159 list<shared_ptr<Subtitle> >
160 SubtitleAsset::subtitles_at (Time t) const
161 {
162         list<shared_ptr<Subtitle> > s;
163         for (list<shared_ptr<Subtitle> >::const_iterator i = _subtitles.begin(); i != _subtitles.end(); ++i) {
164                 if ((*i)->in() <= t && t <= (*i)->out ()) {
165                         s.push_back (*i);
166                 }
167         }
168
169         return s;
170 }
171
172 std::string
173 SubtitleAsset::font_id_to_name (string id) const
174 {
175         list<shared_ptr<libdcp::parse::LoadFont> >::const_iterator i = _load_font_nodes.begin();
176         while (i != _load_font_nodes.end() && (*i)->id != id) {
177                 ++i;
178         }
179
180         if (i == _load_font_nodes.end ()) {
181                 return "";
182         }
183
184         if ((*i)->uri == "arial.ttf") {
185                 return "Arial";
186         }
187
188         return "";
189 }
190
191 Subtitle::Subtitle (
192         string font,
193         bool italic,
194         Color color,
195         int size,
196         Time in,
197         Time out,
198         float v_position,
199         VAlign v_align,
200         string text,
201         Effect effect,
202         Color effect_color,
203         Time fade_up_time,
204         Time fade_down_time
205         )
206         : _font (font)
207         , _italic (italic)
208         , _color (color)
209         , _size (size)
210         , _in (in)
211         , _out (out)
212         , _v_position (v_position)
213         , _v_align (v_align)
214         , _text (text)
215         , _effect (effect)
216         , _effect_color (effect_color)
217         , _fade_up_time (fade_up_time)
218         , _fade_down_time (fade_down_time)
219 {
220
221 }
222
223 int
224 Subtitle::size_in_pixels (int screen_height) const
225 {
226         /* Size in the subtitle file is given in points as if the screen
227            height is 11 inches, so a 72pt font would be 1/11th of the screen
228            height.
229         */
230         
231         return _size * screen_height / (11 * 72);
232 }
233
234 bool
235 libdcp::operator== (Subtitle const & a, Subtitle const & b)
236 {
237         return (
238                 a.font() == b.font() &&
239                 a.italic() == b.italic() &&
240                 a.color() == b.color() &&
241                 a.size() == b.size() &&
242                 a.in() == b.in() &&
243                 a.out() == b.out() &&
244                 a.v_position() == b.v_position() &&
245                 a.v_align() == b.v_align() &&
246                 a.text() == b.text() &&
247                 a.effect() == b.effect() &&
248                 a.effect_color() == b.effect_color() &&
249                 a.fade_up_time() == b.fade_up_time() &&
250                 a.fade_down_time() == b.fade_down_time()
251                 );
252 }
253
254 ostream&
255 libdcp::operator<< (ostream& s, Subtitle const & sub)
256 {
257         s << "\n`" << sub.text() << "' from " << sub.in() << " to " << sub.out() << ";\n"
258           << "fade up " << sub.fade_up_time() << ", fade down " << sub.fade_down_time() << ";\n"
259           << "font " << sub.font() << ", ";
260
261         if (sub.italic()) {
262                 s << "italic";
263         } else {
264                 s << "non-italic";
265         }
266         
267         s << ", size " << sub.size() << ", color " << sub.color() << ", vpos " << sub.v_position() << ", valign " << ((int) sub.v_align()) << ";\n"
268           << "effect " << ((int) sub.effect()) << ", effect color " << sub.effect_color();
269
270         return s;
271 }
272
273 void
274 SubtitleAsset::add (shared_ptr<Subtitle> s)
275 {
276         _subtitles.push_back (s);
277         _need_sort = true;
278 }
279
280 void
281 SubtitleAsset::write_to_cpl (xmlpp::Element* node, bool) const
282 {
283         /* XXX: should EditRate, Duration and IntrinsicDuration be in here? */
284
285         xmlpp::Node* ms = node->add_child ("MainSubtitle");
286         ms->add_child("Id")->add_child_text("urn:uuid:" + _uuid);
287         ms->add_child("AnnotationText")->add_child_text (_file_name);
288         /* XXX */
289         ms->add_child("EntryPoint")->add_child_text ("0");
290 }
291
292 struct SubtitleSorter {
293         bool operator() (shared_ptr<Subtitle> a, shared_ptr<Subtitle> b) {
294                 if (a->in() != b->in()) {
295                         return a->in() < b->in();
296                 }
297                 return a->v_position() < b->v_position();
298         }
299 };
300
301 void
302 SubtitleAsset::write_xml () const
303 {
304         ofstream s (path().string().c_str());
305         write_xml (s);
306 }
307
308 void
309 SubtitleAsset::write_xml (ostream& s) const
310 {
311         xmlpp::Document doc;
312         xmlpp::Element* root = doc.create_root_node ("DCSubtitle");
313         root->set_attribute ("Version", "1.0");
314
315         root->add_child("SubtitleID")->add_child_text (_uuid);
316         root->add_child("MovieTitle")->add_child_text (_movie_title);
317         root->add_child("ReelNumber")->add_child_text (lexical_cast<string> (_reel_number));
318         root->add_child("Language")->add_child_text (_language);
319
320         if (_load_font_nodes.size() > 1) {
321                 boost::throw_exception (MiscError ("multiple LoadFont nodes not supported"));
322         }
323
324         if (!_load_font_nodes.empty ()) {
325                 xmlpp::Element* load_font = root->add_child("LoadFont");
326                 load_font->set_attribute("Id", _load_font_nodes.front()->id);
327                 load_font->set_attribute("URI",  _load_font_nodes.front()->uri);
328         }
329
330         list<shared_ptr<Subtitle> > sorted = _subtitles;
331         if (_need_sort) {
332                 sorted.sort (SubtitleSorter ());
333         }
334
335         /* XXX: multiple fonts not supported */
336         /* XXX: script, underlined, weight not supported */
337
338         bool italic = false;
339         Color color;
340         int size = 0;
341         Effect effect = NONE;
342         Color effect_color;
343         int spot_number = 1;
344         Time last_in;
345         Time last_out;
346         Time last_fade_up_time;
347         Time last_fade_down_time;
348
349         xmlpp::Element* font = 0;
350         xmlpp::Element* subtitle = 0;
351
352         for (list<shared_ptr<Subtitle> >::iterator i = sorted.begin(); i != sorted.end(); ++i) {
353
354                 /* We will start a new <Font>...</Font> whenever some font property changes.
355                    I suppose we should really make an optimal hierarchy of <Font> tags, but
356                    that seems hard.
357                 */
358
359                 bool const font_changed =
360                         italic       != (*i)->italic()       ||
361                         color        != (*i)->color()        ||
362                         size         != (*i)->size()         ||
363                         effect       != (*i)->effect()       ||
364                         effect_color != (*i)->effect_color();
365
366                 if (font_changed) {
367                         italic = (*i)->italic ();
368                         color = (*i)->color ();
369                         size = (*i)->size ();
370                         effect = (*i)->effect ();
371                         effect_color = (*i)->effect_color ();
372                 }
373
374                 if (!font || font_changed) {
375                         font = root->add_child ("Font");
376                         string id = "theFontId";
377                         if (!_load_font_nodes.empty()) {
378                                 id = _load_font_nodes.front()->id;
379                         }
380                         font->set_attribute ("Id", id);
381                         font->set_attribute ("Italic", italic ? "yes" : "no");
382                         font->set_attribute ("Color", color.to_argb_string());
383                         font->set_attribute ("Size", lexical_cast<string> (size));
384                         font->set_attribute ("Effect", effect_to_string (effect));
385                         font->set_attribute ("EffectColor", effect_color.to_argb_string());
386                         font->set_attribute ("Script", "normal");
387                         font->set_attribute ("Underlined", "no");
388                         font->set_attribute ("Weight", "normal");
389                 }
390
391                 if (!subtitle || font_changed ||
392                     (last_in != (*i)->in() ||
393                      last_out != (*i)->out() ||
394                      last_fade_up_time != (*i)->fade_up_time() ||
395                      last_fade_down_time != (*i)->fade_down_time()
396                             )) {
397
398                         subtitle = font->add_child ("Subtitle");
399                         subtitle->set_attribute ("SpotNumber", lexical_cast<string> (spot_number++));
400                         subtitle->set_attribute ("TimeIn", (*i)->in().to_string());
401                         subtitle->set_attribute ("TimeOut", (*i)->out().to_string());
402                         subtitle->set_attribute ("FadeUpTime", lexical_cast<string> ((*i)->fade_up_time().to_ticks()));
403                         subtitle->set_attribute ("FadeDownTime", lexical_cast<string> ((*i)->fade_down_time().to_ticks()));
404
405                         last_in = (*i)->in ();
406                         last_out = (*i)->out ();
407                         last_fade_up_time = (*i)->fade_up_time ();
408                         last_fade_down_time = (*i)->fade_down_time ();
409                 }
410
411                 xmlpp::Element* text = subtitle->add_child ("Text");
412                 text->set_attribute ("VAlign", valign_to_string ((*i)->v_align()));             
413                 text->set_attribute ("VPosition", lexical_cast<string> ((*i)->v_position()));
414                 text->add_child_text ((*i)->text());
415         }
416
417         doc.write_to_stream_formatted (s, "UTF-8");
418 }
419