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