Remove debugging code.
[libdcp.git] / src / subtitle_asset.cc
1 /*
2     Copyright (C) 2012-2015 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, true);
92 }
93
94 void
95 SubtitleAsset::read_xml (string xml_file)
96 {
97         try {
98                 shared_ptr<cxml::Document> xml (new cxml::Document ("DCSubtitle"));
99                 xml->read_file (xml_file);
100                 read_xml (xml, false);
101         } catch (cxml::Error& e) {
102                 shared_ptr<cxml::Document> xml (new cxml::Document ("SubtitleReel"));
103                 xml->read_file (xml_file);
104                 read_xml (xml, true);
105         }               
106 }
107
108 void
109 SubtitleAsset::read_xml (shared_ptr<cxml::Document> xml, bool smpte)
110 {
111         /* XXX: hacks aplenty in here; need separate parsers for DCSubtitle (Interop) and SubtitleReel (SMPTE) */
112         
113         /* DCSubtitle */
114         optional<string> x = xml->optional_string_child ("SubtitleID");
115         if (!x) {
116                 /* SubtitleReel */
117                 x = xml->optional_string_child ("Id");
118         }
119         _uuid = x.get_value_or ("");
120
121         _movie_title = xml->optional_string_child ("MovieTitle");
122         _reel_number = xml->string_child ("ReelNumber");
123         _language = xml->string_child ("Language");
124
125         optional<int> tcr;
126         if (smpte) {
127                 tcr = xml->optional_number_child<int> ("TimeCodeRate");
128         }
129
130         _load_font_nodes = type_children<libdcp::parse::LoadFont> (xml, "LoadFont");
131
132         /* Now make Subtitle objects to represent the raw XML nodes
133            in a sane way.
134         */
135
136         ParseState parse_state;
137         parse_node (xml->node(), parse_state, tcr);
138 }
139
140 void
141 SubtitleAsset::parse_node (xmlpp::Node* node, ParseState& parse_state, optional<int> tcr)
142 {
143         xmlpp::Node::NodeList children = node->get_children ();
144         for (xmlpp::Node::NodeList::const_iterator i = children.begin(); i != children.end(); ++i) {
145                 xmlpp::ContentNode* c = dynamic_cast<xmlpp::ContentNode *> (*i);
146                 if (c) {
147                         maybe_add_subtitle (c->get_content (), parse_state);
148                 }
149
150                 xmlpp::Element* e = dynamic_cast<xmlpp::Element *> (*i);
151                 if (e) {
152                         cxml::ConstNodePtr n (new cxml::Node (e));
153                         if (n->name() == "Font") {
154                                 parse_state.font_nodes.push_back (shared_ptr<parse::Font> (new parse::Font (n, tcr)));
155                                 parse_node (e, parse_state, tcr);
156                                 parse_state.font_nodes.pop_back ();
157                         } else if (n->name() == "Text") {
158                                 parse_state.text_nodes.push_back (shared_ptr<parse::Text> (new parse::Text (n, tcr)));
159                                 parse_node (e, parse_state, tcr);
160                                 parse_state.text_nodes.pop_back ();
161                         } else if (n->name() == "Subtitle") {
162                                 parse_state.subtitle_nodes.push_back (shared_ptr<parse::Subtitle> (new parse::Subtitle (n, tcr)));
163                                 parse_node (e, parse_state, tcr);
164                                 parse_state.subtitle_nodes.pop_back ();
165                         } else if (n->name() == "SubtitleList") {
166                                 parse_node (e, parse_state, tcr);
167                         }
168                 }
169         }
170 }
171
172 void
173 SubtitleAsset::maybe_add_subtitle (string text, ParseState& parse_state)
174 {
175         if (empty_or_white_space (text)) {
176                 return;
177         }
178         
179         if (parse_state.text_nodes.empty() || parse_state.subtitle_nodes.empty ()) {
180                 return;
181         }
182
183         assert (!parse_state.text_nodes.empty ());
184         assert (!parse_state.subtitle_nodes.empty ());
185         
186         libdcp::parse::Font effective_font (parse_state.font_nodes);
187         libdcp::parse::Text effective_text (*parse_state.text_nodes.back ());
188         libdcp::parse::Subtitle effective_subtitle (*parse_state.subtitle_nodes.back ());
189
190         shared_ptr<Subtitle> c = parse_state.current;
191         if (!c ||
192             effective_subtitle.in != c->in() ||
193             effective_subtitle.out != c->out() ||
194             effective_text.v_position != c->v_position() ||
195             effective_text.v_align != c->v_align()) {
196
197                 parse_state.current.reset (
198                         new Subtitle (
199                                 font_id_to_name (effective_font.id),
200                                 effective_font.italic.get(),
201                                 effective_font.color.get(),
202                                 effective_font.size,
203                                 effective_subtitle.in,
204                                 effective_subtitle.out,
205                                 effective_text.v_position,
206                                 effective_text.v_align,
207                                 "",
208                                 effective_font.effect ? effective_font.effect.get() : NONE,
209                                 effective_font.effect_color.get(),
210                                 effective_subtitle.fade_up_time,
211                                 effective_subtitle.fade_down_time
212                                 )
213                         );
214                 
215                 _subtitles.push_back (parse_state.current);
216         }
217         
218         if (effective_font.italic.get()) {
219                 parse_state.current->set_text (parse_state.current->text() + "<i>" + text + "</i>");
220         } else {
221                 parse_state.current->set_text (parse_state.current->text() + text);
222         }
223 }
224
225 list<shared_ptr<Subtitle> >
226 SubtitleAsset::subtitles_during (Time from, Time to) const
227 {
228         list<shared_ptr<Subtitle> > s;
229         for (list<shared_ptr<Subtitle> >::const_iterator i = _subtitles.begin(); i != _subtitles.end(); ++i) {
230                 if ((*i)->out() >= from && (*i)->in() <= to) {
231                         s.push_back (*i);
232                 }
233         }
234
235         return s;
236 }
237
238 std::string
239 SubtitleAsset::font_id_to_name (string id) const
240 {
241         list<shared_ptr<libdcp::parse::LoadFont> >::const_iterator i = _load_font_nodes.begin();
242         while (i != _load_font_nodes.end() && (*i)->id != id) {
243                 ++i;
244         }
245
246         if (i == _load_font_nodes.end ()) {
247                 return "";
248         }
249
250         if ((*i)->uri && (*i)->uri.get() == "arial.ttf") {
251                 return "Arial";
252         }
253
254         return "";
255 }
256
257 Subtitle::Subtitle (
258         string font,
259         bool italic,
260         Color color,
261         int size,
262         Time in,
263         Time out,
264         float v_position,
265         VAlign v_align,
266         string text,
267         Effect effect,
268         Color effect_color,
269         Time fade_up_time,
270         Time fade_down_time
271         )
272         : _font (font)
273         , _italic (italic)
274         , _color (color)
275         , _size (size)
276         , _in (in)
277         , _out (out)
278         , _v_position (v_position)
279         , _v_align (v_align)
280         , _text (text)
281         , _effect (effect)
282         , _effect_color (effect_color)
283         , _fade_up_time (fade_up_time)
284         , _fade_down_time (fade_down_time)
285 {
286
287 }
288
289 int
290 Subtitle::size_in_pixels (int screen_height) const
291 {
292         /* Size in the subtitle file is given in points as if the screen
293            height is 11 inches, so a 72pt font would be 1/11th of the screen
294            height.
295         */
296         
297         return _size * screen_height / (11 * 72);
298 }
299
300 bool
301 libdcp::operator== (Subtitle const & a, Subtitle const & b)
302 {
303         return (
304                 a.font() == b.font() &&
305                 a.italic() == b.italic() &&
306                 a.color() == b.color() &&
307                 a.size() == b.size() &&
308                 a.in() == b.in() &&
309                 a.out() == b.out() &&
310                 a.v_position() == b.v_position() &&
311                 a.v_align() == b.v_align() &&
312                 a.text() == b.text() &&
313                 a.effect() == b.effect() &&
314                 a.effect_color() == b.effect_color() &&
315                 a.fade_up_time() == b.fade_up_time() &&
316                 a.fade_down_time() == b.fade_down_time()
317                 );
318 }
319
320 ostream&
321 libdcp::operator<< (ostream& s, Subtitle const & sub)
322 {
323         s << "\n`" << sub.text() << "' from " << sub.in() << " to " << sub.out() << ";\n"
324           << "fade up " << sub.fade_up_time() << ", fade down " << sub.fade_down_time() << ";\n"
325           << "font " << sub.font() << ", ";
326
327         if (sub.italic()) {
328                 s << "italic";
329         } else {
330                 s << "non-italic";
331         }
332         
333         s << ", size " << sub.size() << ", color " << sub.color() << ", vpos " << sub.v_position() << ", valign " << ((int) sub.v_align()) << ";\n"
334           << "effect " << ((int) sub.effect()) << ", effect color " << sub.effect_color();
335
336         return s;
337 }
338
339 void
340 SubtitleAsset::add (shared_ptr<Subtitle> s)
341 {
342         _subtitles.push_back (s);
343         _need_sort = true;
344 }
345
346 void
347 SubtitleAsset::write_to_cpl (xmlpp::Element* node) const
348 {
349         /* XXX: should EditRate, Duration and IntrinsicDuration be in here? */
350
351         xmlpp::Node* ms = node->add_child ("MainSubtitle");
352         ms->add_child("Id")->add_child_text("urn:uuid:" + _uuid);
353         ms->add_child("AnnotationText")->add_child_text (_file_name.string ());
354         /* XXX */
355         ms->add_child("EntryPoint")->add_child_text ("0");
356 }
357
358 struct SubtitleSorter {
359         bool operator() (shared_ptr<Subtitle> a, shared_ptr<Subtitle> b) {
360                 if (a->in() != b->in()) {
361                         return a->in() < b->in();
362                 }
363                 return a->v_position() < b->v_position();
364         }
365 };
366
367 void
368 SubtitleAsset::write_xml () const
369 {
370         FILE* f = fopen_boost (path (), "r");
371         Glib::ustring const s = xml_as_string ();
372         fwrite (s.c_str(), 1, s.length(), f);
373         fclose (f);
374 }
375
376 Glib::ustring
377 SubtitleAsset::xml_as_string () const
378 {
379         xmlpp::Document doc;
380         xmlpp::Element* root = doc.create_root_node ("DCSubtitle");
381         root->set_attribute ("Version", "1.0");
382
383         root->add_child("SubtitleID")->add_child_text (_uuid);
384         if (_movie_title) {
385                 root->add_child("MovieTitle")->add_child_text (_movie_title.get ());
386         }
387         root->add_child("ReelNumber")->add_child_text (raw_convert<string> (_reel_number));
388         root->add_child("Language")->add_child_text (_language);
389
390         if (_load_font_nodes.size() > 1) {
391                 boost::throw_exception (MiscError ("multiple LoadFont nodes not supported"));
392         }
393
394         if (!_load_font_nodes.empty ()) {
395                 xmlpp::Element* load_font = root->add_child("LoadFont");
396                 load_font->set_attribute("Id", _load_font_nodes.front()->id);
397                 if (_load_font_nodes.front()->uri) {
398                         load_font->set_attribute("URI",  _load_font_nodes.front()->uri.get ());
399                 }
400         }
401
402         list<shared_ptr<Subtitle> > sorted = _subtitles;
403         if (_need_sort) {
404                 sorted.sort (SubtitleSorter ());
405         }
406
407         /* XXX: multiple fonts not supported */
408         /* XXX: script, underlined, weight not supported */
409
410         bool italic = false;
411         Color color;
412         int size = 0;
413         Effect effect = NONE;
414         Color effect_color;
415         int spot_number = 1;
416         Time last_in;
417         Time last_out;
418         Time last_fade_up_time;
419         Time last_fade_down_time;
420
421         xmlpp::Element* font = 0;
422         xmlpp::Element* subtitle = 0;
423
424         for (list<shared_ptr<Subtitle> >::iterator i = sorted.begin(); i != sorted.end(); ++i) {
425
426                 /* We will start a new <Font>...</Font> whenever some font property changes.
427                    I suppose we should really make an optimal hierarchy of <Font> tags, but
428                    that seems hard.
429                 */
430
431                 bool const 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                 if (font_changed) {
439                         italic = (*i)->italic ();
440                         color = (*i)->color ();
441                         size = (*i)->size ();
442                         effect = (*i)->effect ();
443                         effect_color = (*i)->effect_color ();
444                 }
445
446                 if (!font || font_changed) {
447                         font = root->add_child ("Font");
448                         string id = "theFontId";
449                         if (!_load_font_nodes.empty()) {
450                                 id = _load_font_nodes.front()->id;
451                         }
452                         font->set_attribute ("Id", id);
453                         font->set_attribute ("Italic", italic ? "yes" : "no");
454                         font->set_attribute ("Color", color.to_argb_string());
455                         font->set_attribute ("Size", raw_convert<string> (size));
456                         font->set_attribute ("Effect", effect_to_string (effect));
457                         font->set_attribute ("EffectColor", effect_color.to_argb_string());
458                         font->set_attribute ("Script", "normal");
459                         font->set_attribute ("Underlined", "no");
460                         font->set_attribute ("Weight", "normal");
461                 }
462
463                 if (!subtitle || font_changed ||
464                     (last_in != (*i)->in() ||
465                      last_out != (*i)->out() ||
466                      last_fade_up_time != (*i)->fade_up_time() ||
467                      last_fade_down_time != (*i)->fade_down_time()
468                             )) {
469
470                         subtitle = font->add_child ("Subtitle");
471                         subtitle->set_attribute ("SpotNumber", raw_convert<string> (spot_number++));
472                         subtitle->set_attribute ("TimeIn", (*i)->in().to_string());
473                         subtitle->set_attribute ("TimeOut", (*i)->out().to_string());
474                         subtitle->set_attribute ("FadeUpTime", raw_convert<string> ((*i)->fade_up_time().to_editable_units(250)));
475                         subtitle->set_attribute ("FadeDownTime", raw_convert<string> ((*i)->fade_down_time().to_editable_units(250)));
476
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                 xmlpp::Element* text = subtitle->add_child ("Text");
484                 text->set_attribute ("VAlign", valign_to_string ((*i)->v_align()));             
485                 text->set_attribute ("VPosition", raw_convert<string> ((*i)->v_position()));
486                 text->add_child_text ((*i)->text());
487         }
488
489         return doc.write_to_string_formatted ("UTF-8");
490 }
491