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