Fix crashes on x-thread signal emission.
[dcpomatic.git] / src / lib / audio_analysis.cc
index 46477950c90b7617abecee43565d90716dccbf1d..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;
@@ -44,7 +46,10 @@ AudioPoint::AudioPoint ()
 AudioPoint::AudioPoint (FILE* f)
 {
        for (int i = 0; i < COUNT; ++i) {
-               fscanf (f, "%f", &_data[i]);
+               int n = fscanf (f, "%f", &_data[i]);
+               if (n != 1) {
+                       _data[i] = 0;
+               }
        }
 }
 
@@ -86,8 +91,11 @@ AudioAnalysis::AudioAnalysis (int channels)
 AudioAnalysis::AudioAnalysis (boost::filesystem::path filename)
 {
        FILE* f = fopen_boost (filename, "r");
+       if (!f) {
+               throw OpenFileError (filename);
+       }
 
-       int channels;
+       int channels = 0;
        fscanf (f, "%d", &channels);
        _data.resize (channels);
 
@@ -108,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];
 }
 
@@ -134,7 +153,7 @@ AudioAnalysis::channels () const
 int
 AudioAnalysis::points (int c) const
 {
-       assert (c < channels ());
+       DCPOMATIC_ASSERT (c < channels ());
        return _data[c].size ();
 }
 
@@ -145,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) {
@@ -154,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);
 }