+ _sndfile = sf_open_fd (fd, SFM_WRITE, &_info, true);
+
+ if (_sndfile == 0) {
+ throw failed_constructor();
+ }
+
+#if 0
+ /* setting flac compression quality above the default does not produce a significant size
+ * improvement (not for large raw recordings anyway, the_CLA tests 2017-10-02, >> 250MB files,
+ * ~1% smaller), but does have a significant encoding speed penalty.
+ *
+ * We still may expose this as option someday though, perhaps for opposite reason: "fast encoding"
+ */
+ double flac_quality = 1; // libsndfile uses range 0..1 (mapped to flac 0..8), default is (5/8)
+ if (sf_command (_sndfile, SFC_SET_COMPRESSION_LEVEL, &flac_quality, sizeof (double)) != SF_TRUE) {
+ char errbuf[256];
+ sf_error_str (_sndfile, errbuf, sizeof (errbuf) - 1);
+ error << string_compose (_("Cannot set flac compression level: %1"), errbuf) << endmsg;
+ }
+#endif
+
+ Sample buf[8192];
+ samplecnt_t off = 0;
+ float peak = 0;
+ float norm = 1.f;
+
+ /* normalize before converting to fixed point, calc gain factor */
+ samplecnt_t len = other.read (buf, off, 8192, other.channel ());
+ while (len > 0) {
+ peak = compute_peak (buf, len, peak);
+ off += len;
+ len = other.read (buf, off, 8192, other.channel ());
+ if (progress) {
+ progress->set_progress (0.5f * (float) off / other.readable_length ());
+ }
+ }
+
+ if (peak > 0) {
+ _gain *= peak;
+ norm = 1.f / peak;
+ }
+
+ /* copy file */
+ off = 0;
+ len = other.read (buf, off, 8192, other.channel ());
+ while (len > 0) {
+ if (norm != 1.f) {
+ for (samplecnt_t i = 0; i < len; ++i) {
+ buf[i] *= norm;
+ }
+ }
+ write (buf, len);
+ off += len;
+ len = other.read (buf, off, 8192, other.channel ());
+ if (progress) {
+ progress->set_progress (0.5f + 0.5f * (float) off / other.readable_length ());
+ }
+ }
+}
+
+void
+SndFileSource::init_sndfile ()
+{