Fix crashes on x-thread signal emission.
[dcpomatic.git] / src / lib / audio_analysis.cc
index 9f92bdb503be802bcdee6aa400d0a1738b0defc3..ee34b0d80b7fc2d3168f557e3947c68f85c995c9 100644 (file)
 
 */
 
+#include "audio_analysis.h"
+#include "dcpomatic_assert.h"
+#include "cross.h"
+#include <boost/filesystem.hpp>
 #include <stdint.h>
+#include <inttypes.h>
 #include <cmath>
 #include <cassert>
 #include <cstdio>
 #include <iostream>
-#include <boost/filesystem.hpp>
-#include "audio_analysis.h"
-#include "cross.h"
 
 using std::ostream;
 using std::istream;
@@ -89,6 +91,9 @@ AudioAnalysis::AudioAnalysis (int channels)
 AudioAnalysis::AudioAnalysis (boost::filesystem::path filename)
 {
        FILE* f = fopen_boost (filename, "r");
+       if (!f) {
+               throw OpenFileError (filename);
+       }
 
        int channels = 0;
        fscanf (f, "%d", &channels);
@@ -111,20 +116,31 @@ AudioAnalysis::AudioAnalysis (boost::filesystem::path filename)
                }
        }
 
+       /* These may not exist in old analysis files, so be careful
+          about reading them.
+       */
+       
+       float peak;
+       DCPTime::Type peak_time;
+       if (fscanf (f, "%f%" SCNd64, &peak, &peak_time) == 2) {
+               _peak = peak;
+               _peak_time = DCPTime (peak_time);
+       }
+       
        fclose (f);
 }
 
 void
 AudioAnalysis::add_point (int c, AudioPoint const & p)
 {
-       assert (c < channels ());
+       DCPOMATIC_ASSERT (c < channels ());
        _data[c].push_back (p);
 }
 
 AudioPoint
 AudioAnalysis::get_point (int c, int p) const
 {
-       assert (p < points (c));
+       DCPOMATIC_ASSERT (p < points (c));
        return _data[c][p];
 }
 
@@ -137,7 +153,7 @@ AudioAnalysis::channels () const
 int
 AudioAnalysis::points (int c) const
 {
-       assert (c < channels ());
+       DCPOMATIC_ASSERT (c < channels ());
        return _data[c].size ();
 }
 
@@ -148,6 +164,9 @@ AudioAnalysis::write (boost::filesystem::path filename)
        tmp.replace_extension (".tmp");
 
        FILE* f = fopen_boost (tmp, "w");
+       if (!f) {
+               throw OpenFileError (tmp);
+       }
 
        fprintf (f, "%ld\n", _data.size ());
        for (vector<vector<AudioPoint> >::iterator i = _data.begin(); i != _data.end(); ++i) {
@@ -157,6 +176,10 @@ AudioAnalysis::write (boost::filesystem::path filename)
                }
        }
 
+       if (_peak) {
+               fprintf (f, "%f%" PRId64, _peak.get (), _peak_time.get().get ());
+       }
+
        fclose (f);
        boost::filesystem::rename (tmp, filename);
 }