Add wrappers around boost::filesystem methods that handle the
[libdcp.git] / src / sound_asset.cc
1 /*
2     Copyright (C) 2012-2021 Carl Hetherington <cth@carlh.net>
3
4     This file is part of libdcp.
5
6     libdcp is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     libdcp is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with libdcp.  If not, see <http://www.gnu.org/licenses/>.
18
19     In addition, as a special exception, the copyright holders give
20     permission to link the code of portions of this program with the
21     OpenSSL library under certain conditions as described in each
22     individual source file, and distribute linked combinations
23     including the two.
24
25     You must obey the GNU General Public License in all respects
26     for all of the code used other than OpenSSL.  If you modify
27     file(s) with this exception, you may extend this exception to your
28     version of the file(s), but you are not obligated to do so.  If you
29     do not wish to do so, delete this exception statement from your
30     version.  If you delete this exception statement from all source
31     files in the program, then also delete it here.
32 */
33
34
35 /** @file  src/sound_asset.cc
36  *  @brief SoundAsset class
37  */
38
39
40 #include "compose.hpp"
41 #include "dcp_assert.h"
42 #include "equality_options.h"
43 #include "exceptions.h"
44 #include "filesystem.h"
45 #include "sound_asset.h"
46 #include "sound_asset_reader.h"
47 #include "sound_asset_writer.h"
48 #include "sound_frame.h"
49 #include "util.h"
50 #include "warnings.h"
51 LIBDCP_DISABLE_WARNINGS
52 #include <asdcp/AS_DCP.h>
53 #include <asdcp/KM_fileio.h>
54 #include <asdcp/Metadata.h>
55 LIBDCP_ENABLE_WARNINGS
56 #include <libxml++/nodes/element.h>
57 #include <boost/filesystem.hpp>
58 #include <stdexcept>
59
60
61 using std::dynamic_pointer_cast;
62 using std::list;
63 using std::shared_ptr;
64 using std::string;
65 using std::vector;
66 using boost::optional;
67 using namespace dcp;
68
69
70 SoundAsset::SoundAsset (boost::filesystem::path file)
71         : Asset (file)
72 {
73         ASDCP::PCM::MXFReader reader;
74         auto r = reader.OpenRead(dcp::filesystem::fix_long_path(file).string().c_str());
75         if (ASDCP_FAILURE(r)) {
76                 boost::throw_exception (MXFFileError("could not open MXF file for reading", file.string(), r));
77         }
78
79         ASDCP::PCM::AudioDescriptor desc;
80         if (ASDCP_FAILURE (reader.FillAudioDescriptor(desc))) {
81                 boost::throw_exception (ReadError("could not read audio MXF information"));
82         }
83
84         _sampling_rate = desc.AudioSamplingRate.Denominator ? (desc.AudioSamplingRate.Numerator / desc.AudioSamplingRate.Denominator) : 0;
85         _channels = desc.ChannelCount;
86         _edit_rate = Fraction (desc.EditRate.Numerator, desc.EditRate.Denominator);
87
88         _intrinsic_duration = desc.ContainerDuration;
89
90         ASDCP::WriterInfo info;
91         if (ASDCP_FAILURE (reader.FillWriterInfo(info))) {
92                 boost::throw_exception (ReadError("could not read audio MXF information"));
93         }
94
95         ASDCP::MXF::SoundfieldGroupLabelSubDescriptor* soundfield;
96         auto rr = reader.OP1aHeader().GetMDObjectByType(
97                 asdcp_smpte_dict->ul(ASDCP::MDD_SoundfieldGroupLabelSubDescriptor),
98                 reinterpret_cast<ASDCP::MXF::InterchangeObject**>(&soundfield)
99                 );
100
101         if (KM_SUCCESS(rr)) {
102                 if (!soundfield->RFC5646SpokenLanguage.empty()) {
103                         char buffer[64];
104                         soundfield->RFC5646SpokenLanguage.get().EncodeString(buffer, sizeof(buffer));
105                         _language = buffer;
106                 }
107         }
108
109         list<ASDCP::MXF::InterchangeObject*> channel_labels;
110         rr = reader.OP1aHeader().GetMDObjectsByType(
111                 asdcp_smpte_dict->ul(ASDCP::MDD_AudioChannelLabelSubDescriptor),
112                 channel_labels
113                 );
114
115         if (KM_SUCCESS(rr)) {
116                 _active_channels = channel_labels.size();
117         }
118
119         _id = read_writer_info (info);
120 }
121
122
123 SoundAsset::SoundAsset (Fraction edit_rate, int sampling_rate, int channels, LanguageTag language, Standard standard)
124         : MXF (standard)
125         , _edit_rate (edit_rate)
126         , _channels (channels)
127         , _sampling_rate (sampling_rate)
128         , _language (language.to_string())
129 {
130
131 }
132
133
134 bool
135 SoundAsset::equals(shared_ptr<const Asset> other, EqualityOptions const& opt, NoteHandler note) const
136 {
137         if (opt.sound_assets_can_differ) {
138                 return true;
139         }
140
141         ASDCP::PCM::MXFReader reader_A;
142         DCP_ASSERT (file());
143         auto r = reader_A.OpenRead(dcp::filesystem::fix_long_path(*file()).string().c_str());
144         if (ASDCP_FAILURE(r)) {
145                 boost::throw_exception (MXFFileError("could not open MXF file for reading", file()->string(), r));
146         }
147
148         ASDCP::PCM::MXFReader reader_B;
149         r = reader_B.OpenRead(dcp::filesystem::fix_long_path(*other->file()).string().c_str());
150         if (ASDCP_FAILURE (r)) {
151                 boost::throw_exception (MXFFileError("could not open MXF file for reading", other->file()->string(), r));
152         }
153
154         ASDCP::PCM::AudioDescriptor desc_A;
155         if (ASDCP_FAILURE (reader_A.FillAudioDescriptor(desc_A))) {
156                 boost::throw_exception (ReadError ("could not read audio MXF information"));
157         }
158         ASDCP::PCM::AudioDescriptor desc_B;
159         if (ASDCP_FAILURE (reader_B.FillAudioDescriptor(desc_B))) {
160                 boost::throw_exception (ReadError ("could not read audio MXF information"));
161         }
162
163         if (desc_A.EditRate != desc_B.EditRate) {
164                 note (
165                         NoteType::ERROR,
166                         String::compose (
167                                 "audio edit rates differ: %1/%2 cf %3/%4",
168                                 desc_A.EditRate.Numerator, desc_A.EditRate.Denominator, desc_B.EditRate.Numerator, desc_B.EditRate.Denominator
169                                 )
170                         );
171                 return false;
172         } else if (desc_A.AudioSamplingRate != desc_B.AudioSamplingRate) {
173                 note (
174                         NoteType::ERROR,
175                         String::compose (
176                                 "audio sampling rates differ: %1 cf %2",
177                                 desc_A.AudioSamplingRate.Numerator, desc_A.AudioSamplingRate.Denominator,
178                                 desc_B.AudioSamplingRate.Numerator, desc_B.AudioSamplingRate.Numerator
179                                 )
180                         );
181                 return false;
182         } else if (desc_A.Locked != desc_B.Locked) {
183                 note (NoteType::ERROR, String::compose ("audio locked flags differ: %1 cf %2", desc_A.Locked, desc_B.Locked));
184                 return false;
185         } else if (desc_A.ChannelCount != desc_B.ChannelCount) {
186                 note (NoteType::ERROR, String::compose ("audio channel counts differ: %1 cf %2", desc_A.ChannelCount, desc_B.ChannelCount));
187                 return false;
188         } else if (desc_A.QuantizationBits != desc_B.QuantizationBits) {
189                 note (NoteType::ERROR, String::compose ("audio bits per sample differ: %1 cf %2", desc_A.QuantizationBits, desc_B.QuantizationBits));
190                 return false;
191         } else if (desc_A.BlockAlign != desc_B.BlockAlign) {
192                 note (NoteType::ERROR, String::compose ("audio bytes per sample differ: %1 cf %2", desc_A.BlockAlign, desc_B.BlockAlign));
193                 return false;
194         } else if (desc_A.AvgBps != desc_B.AvgBps) {
195                 note (NoteType::ERROR, String::compose ("audio average bps differ: %1 cf %2", desc_A.AvgBps, desc_B.AvgBps));
196                 return false;
197         } else if (desc_A.LinkedTrackID != desc_B.LinkedTrackID) {
198                 note (NoteType::ERROR, String::compose ("audio linked track IDs differ: %1 cf %2", desc_A.LinkedTrackID, desc_B.LinkedTrackID));
199                 return false;
200         } else if (desc_A.ContainerDuration != desc_B.ContainerDuration) {
201                 note (NoteType::ERROR, String::compose ("audio container durations differ: %1 cf %2", desc_A.ContainerDuration, desc_B.ContainerDuration));
202                 return false;
203         } else if (desc_A.ChannelFormat != desc_B.ChannelFormat) {
204                 /* XXX */
205         }
206
207         auto other_sound = dynamic_pointer_cast<const SoundAsset> (other);
208
209         auto reader = start_read ();
210         auto other_reader = other_sound->start_read ();
211
212         for (int i = 0; i < _intrinsic_duration; ++i) {
213
214                 auto frame_A = reader->get_frame (i);
215                 auto frame_B = other_reader->get_frame (i);
216
217                 if (frame_A->size() != frame_B->size()) {
218                         note (NoteType::ERROR, String::compose ("sizes of audio data for frame %1 differ", i));
219                         return false;
220                 }
221
222                 if (memcmp (frame_A->data(), frame_B->data(), frame_A->size()) != 0) {
223                         for (int sample = 0; sample < frame_A->samples(); ++sample) {
224                                 for (int channel = 0; channel < frame_A->channels(); ++channel) {
225                                         int32_t const d = abs(frame_A->get(channel, sample) - frame_B->get(channel, sample));
226                                         if (d > opt.max_audio_sample_error) {
227                                                 note (NoteType::ERROR, String::compose("PCM data difference of %1 in frame %2, channel %3, sample %4", d, i, channel, sample));
228                                                 return false;
229                                         }
230                                 }
231                         }
232                 }
233         }
234
235         return true;
236 }
237
238
239 shared_ptr<SoundAssetWriter>
240 SoundAsset::start_write(
241         boost::filesystem::path file,
242         vector<dcp::Channel> extra_active_channels,
243         AtmosSync atmos_sync,
244         MCASubDescriptors include_mca_subdescriptors
245         )
246 {
247         if (atmos_sync == AtmosSync::ENABLED && _channels < 14) {
248                 throw MiscError ("Insufficient channels to write ATMOS sync (there must be at least 14)");
249         }
250
251         return shared_ptr<SoundAssetWriter>(
252                 new SoundAssetWriter(this, file, extra_active_channels, atmos_sync == AtmosSync::ENABLED, include_mca_subdescriptors == MCASubDescriptors::ENABLED)
253                 );
254 }
255
256
257 shared_ptr<SoundAssetReader>
258 SoundAsset::start_read () const
259 {
260         return shared_ptr<SoundAssetReader> (new SoundAssetReader(this, key(), standard()));
261 }
262
263
264 string
265 SoundAsset::static_pkl_type (Standard standard)
266 {
267         switch (standard) {
268         case Standard::INTEROP:
269                 return "application/x-smpte-mxf;asdcpKind=Sound";
270         case Standard::SMPTE:
271                 return "application/mxf";
272         default:
273                 DCP_ASSERT (false);
274         }
275 }
276
277
278 bool
279 SoundAsset::valid_mxf (boost::filesystem::path file)
280 {
281         ASDCP::PCM::MXFReader reader;
282         Kumu::Result_t r = reader.OpenRead(dcp::filesystem::fix_long_path(file).string().c_str());
283         return !ASDCP_FAILURE (r);
284 }
285
286
287 int
288 SoundAsset::active_channels() const
289 {
290         return _active_channels.get_value_or(_channels);
291 }
292