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