Add support for reading non-MXF-wrapped SMPTE subtitle files.
[libdcp.git] / src / dcp.cc
1 /*
2     Copyright (C) 2012-2014 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 /** @file  src/dcp.cc
21  *  @brief DCP class.
22  */
23
24 #include "raw_convert.h"
25 #include "dcp.h"
26 #include "sound_mxf.h"
27 #include "picture_mxf.h"
28 #include "interop_subtitle_content.h"
29 #include "smpte_subtitle_content.h"
30 #include "mono_picture_mxf.h"
31 #include "stereo_picture_mxf.h"
32 #include "util.h"
33 #include "metadata.h"
34 #include "exceptions.h"
35 #include "cpl.h"
36 #include "signer.h"
37 #include "compose.hpp"
38 #include "AS_DCP.h"
39 #include "decrypted_kdm.h"
40 #include "decrypted_kdm_key.h"
41 #include "dcp_assert.h"
42 #include <xmlsec/xmldsig.h>
43 #include <xmlsec/app.h>
44 #include <libxml++/libxml++.h>
45 #include <boost/filesystem.hpp>
46 #include <boost/algorithm/string.hpp>
47 #include <iostream>
48
49 using std::string;
50 using std::list;
51 using std::cout;
52 using std::ostream;
53 using std::make_pair;
54 using std::map;
55 using std::cout;
56 using std::exception;
57 using boost::shared_ptr;
58 using boost::algorithm::starts_with;
59 using namespace dcp;
60
61 DCP::DCP (boost::filesystem::path directory)
62         : _directory (directory)
63 {
64         if (!boost::filesystem::exists (directory)) {
65                 boost::filesystem::create_directories (directory);
66         }
67         
68         _directory = boost::filesystem::canonical (_directory);
69 }
70
71 template<class T> void
72 survivable_error (bool keep_going, dcp::DCP::ReadErrors* errors, T const & e)
73 {
74         if (keep_going) {
75                 if (errors) {
76                         errors->push_back (shared_ptr<T> (new T (e)));
77                 }
78         } else {
79                 throw e;
80         }
81 }
82
83 void
84 DCP::read (bool keep_going, ReadErrors* errors)
85 {
86         /* Read the ASSETMAP */
87         
88         boost::filesystem::path asset_map_file;
89         if (boost::filesystem::exists (_directory / "ASSETMAP")) {
90                 asset_map_file = _directory / "ASSETMAP";
91         } else if (boost::filesystem::exists (_directory / "ASSETMAP.xml")) {
92                 asset_map_file = _directory / "ASSETMAP.xml";
93         } else {
94                 boost::throw_exception (DCPReadError (String::compose ("could not find AssetMap file in `%1'", _directory.string())));
95         }
96
97         cxml::Document asset_map ("AssetMap");
98         asset_map.read_file (asset_map_file);
99         list<shared_ptr<cxml::Node> > asset_nodes = asset_map.node_child("AssetList")->node_children ("Asset");
100         map<string, boost::filesystem::path> paths;
101         for (list<shared_ptr<cxml::Node> >::const_iterator i = asset_nodes.begin(); i != asset_nodes.end(); ++i) {
102                 if ((*i)->node_child("ChunkList")->node_children("Chunk").size() != 1) {
103                         boost::throw_exception (XMLError ("unsupported asset chunk count"));
104                 }
105                 string p = (*i)->node_child("ChunkList")->node_child("Chunk")->string_child ("Path");
106                 if (starts_with (p, "file://")) {
107                         p = p.substr (7);
108                 }
109                 paths.insert (make_pair ((*i)->string_child ("Id"), p));
110         }
111
112         /* Read all the assets from the asset map */
113         /* XXX: I think we should be looking at the PKL here to decide type, not
114            the extension of the file.
115         */
116         for (map<string, boost::filesystem::path>::const_iterator i = paths.begin(); i != paths.end(); ++i) {
117                 boost::filesystem::path path = _directory / i->second;
118
119                 if (!boost::filesystem::exists (path)) {
120                         survivable_error (keep_going, errors, MissingAssetError (path));
121                         continue;
122                 }
123                 
124                 if (boost::algorithm::ends_with (path.string(), ".xml")) {
125                         xmlpp::DomParser* p = new xmlpp::DomParser;
126                         try {
127                                 p->parse_file (path.string());
128                         } catch (std::exception& e) {
129                                 delete p;
130                                 continue;
131                         }
132                         
133                         string const root = p->get_document()->get_root_node()->get_name ();
134                         delete p;
135                         
136                         if (root == "CompositionPlaylist") {
137                                 _assets.push_back (shared_ptr<CPL> (new CPL (path)));
138                         } else if (root == "DCSubtitle") {
139                                 _assets.push_back (shared_ptr<InteropSubtitleContent> (new InteropSubtitleContent (path)));
140                         }
141                 } else if (boost::algorithm::ends_with (path.string(), ".mxf")) {
142                         ASDCP::EssenceType_t type;
143                         if (ASDCP::EssenceType (path.string().c_str(), type) != ASDCP::RESULT_OK) {
144                                 throw DCPReadError ("Could not find essence type");
145                         }
146                         switch (type) {
147                                 case ASDCP::ESS_UNKNOWN:
148                                 case ASDCP::ESS_MPEG2_VES:
149                                         throw DCPReadError ("MPEG2 video essences are not supported");
150                                 case ASDCP::ESS_JPEG_2000:
151                                         _assets.push_back (shared_ptr<MonoPictureMXF> (new MonoPictureMXF (path)));
152                                         break;
153                                 case ASDCP::ESS_PCM_24b_48k:
154                                 case ASDCP::ESS_PCM_24b_96k:
155                                         _assets.push_back (shared_ptr<SoundMXF> (new SoundMXF (path)));
156                                         break;
157                                 case ASDCP::ESS_JPEG_2000_S:
158                                         _assets.push_back (shared_ptr<StereoPictureMXF> (new StereoPictureMXF (path)));
159                                         break;
160                                 case ASDCP::ESS_TIMED_TEXT:
161                                         _assets.push_back (shared_ptr<SMPTESubtitleContent> (new SMPTESubtitleContent (path)));
162                                         break;
163                                 default:
164                                         throw DCPReadError ("Unknown MXF essence type");
165                                 }
166                 }
167         }
168
169         list<shared_ptr<CPL> > cpl = cpls ();
170         for (list<shared_ptr<CPL> >::const_iterator i = cpl.begin(); i != cpl.end(); ++i) {
171                 (*i)->resolve_refs (list_of_type<Asset, Object> (assets ()));
172         }
173 }
174
175 bool
176 DCP::equals (DCP const & other, EqualityOptions opt, boost::function<void (NoteType, string)> note) const
177 {
178         list<shared_ptr<CPL> > a = cpls ();
179         list<shared_ptr<CPL> > b = other.cpls ();
180         
181         if (a.size() != b.size()) {
182                 note (DCP_ERROR, String::compose ("CPL counts differ: %1 vs %2", a.size(), b.size()));
183                 return false;
184         }
185
186         bool r = true;
187
188         for (list<shared_ptr<CPL> >::const_iterator i = a.begin(); i != a.end(); ++i) {
189                 list<shared_ptr<CPL> >::const_iterator j = b.begin ();
190                 while (j != b.end() && !(*j)->equals (*i, opt, note)) {
191                         ++j;
192                 }
193
194                 if (j == b.end ()) {
195                         r = false;
196                 }
197         }
198
199         return r;
200 }
201
202 void
203 DCP::add (boost::shared_ptr<Asset> asset)
204 {
205         _assets.push_back (asset);
206 }
207
208 bool
209 DCP::encrypted () const
210 {
211         list<shared_ptr<CPL> > cpl = cpls ();
212         for (list<shared_ptr<CPL> >::const_iterator i = cpl.begin(); i != cpl.end(); ++i) {
213                 if ((*i)->encrypted ()) {
214                         return true;
215                 }
216         }
217
218         return false;
219 }
220
221 void
222 DCP::add (DecryptedKDM const & kdm)
223 {
224         list<DecryptedKDMKey> keys = kdm.keys ();
225         list<shared_ptr<CPL> > cpl = cpls ();
226         
227         for (list<shared_ptr<CPL> >::iterator i = cpl.begin(); i != cpl.end(); ++i) {
228                 for (list<DecryptedKDMKey>::iterator j = keys.begin(); j != keys.end(); ++j) {
229                         if (j->cpl_id() == (*i)->id()) {
230                                 (*i)->add (kdm);
231                         }                               
232                 }
233         }
234 }
235
236 boost::filesystem::path
237 DCP::write_pkl (Standard standard, string pkl_uuid, XMLMetadata metadata, shared_ptr<const Signer> signer) const
238 {
239         boost::filesystem::path p = _directory;
240         p /= String::compose ("%1_pkl.xml", pkl_uuid);
241
242         xmlpp::Document doc;
243         xmlpp::Element* pkl;
244         if (standard == INTEROP) {
245                 pkl = doc.create_root_node("PackingList", "http://www.digicine.com/PROTO-ASDCP-PKL-20040311#");
246         } else {
247                 pkl = doc.create_root_node("PackingList", "http://www.smpte-ra.org/schemas/429-8/2007/PKL");
248         }
249         
250         if (signer) {
251                 pkl->set_namespace_declaration ("http://www.w3.org/2000/09/xmldsig#", "dsig");
252         }
253
254         pkl->add_child("Id")->add_child_text ("urn:uuid:" + pkl_uuid);
255
256         /* XXX: this is a bit of a hack */
257         DCP_ASSERT (cpls().size() > 0);
258         pkl->add_child("AnnotationText")->add_child_text (cpls().front()->annotation_text ());
259         
260         pkl->add_child("IssueDate")->add_child_text (metadata.issue_date);
261         pkl->add_child("Issuer")->add_child_text (metadata.issuer);
262         pkl->add_child("Creator")->add_child_text (metadata.creator);
263
264         xmlpp::Element* asset_list = pkl->add_child("AssetList");
265         for (list<shared_ptr<Asset> >::const_iterator i = _assets.begin(); i != _assets.end(); ++i) {
266                 (*i)->write_to_pkl (asset_list, standard);
267         }
268
269         if (signer) {
270                 signer->sign (pkl, standard);
271         }
272                 
273         doc.write_to_file (p.string (), "UTF-8");
274         return p.string ();
275 }
276
277 /** Write the VOLINDEX file.
278  *  @param standard DCP standard to use (INTEROP or SMPTE)
279  */
280 void
281 DCP::write_volindex (Standard standard) const
282 {
283         boost::filesystem::path p = _directory;
284         switch (standard) {
285         case INTEROP:
286                 p /= "VOLINDEX";
287                 break;
288         case SMPTE:
289                 p /= "VOLINDEX.xml";
290                 break;
291         default:
292                 DCP_ASSERT (false);
293         }
294
295         xmlpp::Document doc;
296         xmlpp::Element* root;
297
298         switch (standard) {
299         case INTEROP:
300                 root = doc.create_root_node ("VolumeIndex", "http://www.digicine.com/PROTO-ASDCP-AM-20040311#");
301                 break;
302         case SMPTE:
303                 root = doc.create_root_node ("VolumeIndex", "http://www.smpte-ra.org/schemas/429-9/2007/AM");
304                 break;
305         default:
306                 DCP_ASSERT (false);
307         }
308         
309         root->add_child("Index")->add_child_text ("1");
310         doc.write_to_file (p.string (), "UTF-8");
311 }
312
313 void
314 DCP::write_assetmap (Standard standard, string pkl_uuid, int pkl_length, XMLMetadata metadata) const
315 {
316         boost::filesystem::path p = _directory;
317         
318         switch (standard) {
319         case INTEROP:
320                 p /= "ASSETMAP";
321                 break;
322         case SMPTE:
323                 p /= "ASSETMAP.xml";
324                 break;
325         default:
326                 DCP_ASSERT (false);
327         }
328
329         xmlpp::Document doc;
330         xmlpp::Element* root;
331
332         switch (standard) {
333         case INTEROP:
334                 root = doc.create_root_node ("AssetMap", "http://www.digicine.com/PROTO-ASDCP-AM-20040311#");
335                 break;
336         case SMPTE:
337                 root = doc.create_root_node ("AssetMap", "http://www.smpte-ra.org/schemas/429-9/2007/AM");
338                 break;
339         default:
340                 DCP_ASSERT (false);
341         }
342
343         root->add_child("Id")->add_child_text ("urn:uuid:" + make_uuid());
344         root->add_child("AnnotationText")->add_child_text ("Created by " + metadata.creator);
345
346         switch (standard) {
347         case INTEROP:
348                 root->add_child("VolumeCount")->add_child_text ("1");
349                 root->add_child("IssueDate")->add_child_text (metadata.issue_date);
350                 root->add_child("Issuer")->add_child_text (metadata.issuer);
351                 root->add_child("Creator")->add_child_text (metadata.creator);
352                 break;
353         case SMPTE:
354                 root->add_child("Creator")->add_child_text (metadata.creator);
355                 root->add_child("VolumeCount")->add_child_text ("1");
356                 root->add_child("IssueDate")->add_child_text (metadata.issue_date);
357                 root->add_child("Issuer")->add_child_text (metadata.issuer);
358                 break;
359         default:
360                 DCP_ASSERT (false);
361         }
362                 
363         xmlpp::Node* asset_list = root->add_child ("AssetList");
364
365         xmlpp::Node* asset = asset_list->add_child ("Asset");
366         asset->add_child("Id")->add_child_text ("urn:uuid:" + pkl_uuid);
367         asset->add_child("PackingList")->add_child_text ("true");
368         xmlpp::Node* chunk_list = asset->add_child ("ChunkList");
369         xmlpp::Node* chunk = chunk_list->add_child ("Chunk");
370         chunk->add_child("Path")->add_child_text (pkl_uuid + "_pkl.xml");
371         chunk->add_child("VolumeIndex")->add_child_text ("1");
372         chunk->add_child("Offset")->add_child_text ("0");
373         chunk->add_child("Length")->add_child_text (raw_convert<string> (pkl_length));
374         
375         for (list<shared_ptr<Asset> >::const_iterator i = _assets.begin(); i != _assets.end(); ++i) {
376                 (*i)->write_to_assetmap (asset_list, _directory);
377         }
378
379         /* This must not be the _formatted version otherwise signature digests will be wrong */
380         doc.write_to_file (p.string (), "UTF-8");
381 }
382
383 /** Write all the XML files for this DCP.
384  *  @param standand INTEROP or SMPTE.
385  *  @param metadata Metadata to use for PKL and asset map files.
386  *  @param signer Signer to use, or 0.
387  */
388 void
389 DCP::write_xml (
390         Standard standard,
391         XMLMetadata metadata,
392         shared_ptr<const Signer> signer
393         )
394 {
395         list<shared_ptr<CPL> > cpl = cpls ();
396         for (list<shared_ptr<CPL> >::const_iterator i = cpl.begin(); i != cpl.end(); ++i) {
397                 string const filename = (*i)->id() + "_cpl.xml";
398                 (*i)->write_xml (_directory / filename, standard, signer);
399         }
400
401         string const pkl_uuid = make_uuid ();
402         boost::filesystem::path const pkl_path = write_pkl (standard, pkl_uuid, metadata, signer);
403         
404         write_volindex (standard);
405         write_assetmap (standard, pkl_uuid, boost::filesystem::file_size (pkl_path), metadata);
406 }
407
408 list<shared_ptr<CPL> >
409 DCP::cpls () const
410 {
411         return list_of_type<Asset, CPL> (_assets);
412 }