Refactor TmpFile into an abstract base class
[ardour.git] / libs / audiographer / audiographer / sndfile / tmp_file_sync.h
1 #ifndef AUDIOGRAPHER_TMP_FILE_SYNC_H
2 #define AUDIOGRAPHER_TMP_FILE_SYNC_H
3
4 #include <cstdio>
5 #include <string>
6
7 #include <glib.h>
8 #include "pbd/gstdio_compat.h"
9
10 #include "sndfile_writer.h"
11 #include "sndfile_reader.h"
12 #include "tmp_file.h"
13
14 namespace AudioGrapher
15 {
16
17 /// A temporary file deleted after this class is destructed
18 template<typename T = DefaultSampleType>
19 class TmpFileSync
20         : public TmpFile<T>
21 {
22   public:
23
24         /// \a filename_template must match the requirements for mkstemp, i.e. end in "XXXXXX"
25         TmpFileSync (char * filename_template, int format, ChannelCount channels, framecnt_t samplerate)
26                 : SndfileHandle (g_mkstemp(filename_template), true, SndfileBase::ReadWrite, format, channels, samplerate)
27                 , filename (filename_template)
28         {}
29
30         TmpFileSync (int format, ChannelCount channels, framecnt_t samplerate)
31           : SndfileHandle (fileno (tmpfile()), true, SndfileBase::ReadWrite, format, channels, samplerate)
32         {}
33
34         TmpFileSync (TmpFileSync const & other) : SndfileHandle (other) {}
35         using SndfileHandle::operator=;
36
37         ~TmpFileSync()
38         {
39                 /* explicitly close first, some OS (yes I'm looking at you windows)
40                  * cannot delete files that are still open
41                  */
42                 if (!filename.empty()) {
43                         SndfileBase::close();
44                         std::remove(filename.c_str());
45                 }
46         }
47
48         void process (ProcessContext<T> const & c)
49         {
50                 SndfileWriter<T>::process (c);
51
52                 if (c.has_flag(ProcessContext<T>::EndOfInput)) {
53                         TmpFile<T>::FileFlushed ();
54                 }
55         }
56
57         using Sink<T>::process;
58
59   private:
60         std::string filename;
61 };
62
63 } // namespace
64
65 #endif // AUDIOGRAPHER_TMP_FILE_SYNC_H