streamtools: Refactor options parsing and RGB->I420 conversion
[jpcrr.git] / streamtools / output-drv-x264.cpp
blobf36d85eb41a32b545cd15c693ab61a00a8f50a49
1 #include <cstring>
2 #include "output-drv.hpp"
3 #include <cstdio>
4 #include <stdexcept>
5 #include <vector>
6 #include <string>
7 #include <sstream>
8 #include "rgbtorgb.hh"
10 namespace
12 std::string expand_options(const std::string& opts, uint32_t rn, uint32_t rd)
14 std::ostringstream ret;
15 if(rd)
16 ret << "--fps " << rn << "/" << rd << " ";
17 ret << expand_arguments_common(opts, "--", " ");
18 return ret.str();
21 class output_driver_x264 : public output_driver
23 public:
24 output_driver_x264(const std::string& _filename, const std::string& _options)
26 filename = _filename;
27 options = _options;
28 set_video_callback<output_driver_x264>(*this, &output_driver_x264::video_callback);
31 ~output_driver_x264()
33 pclose(out);
36 void ready()
38 const video_settings& v = get_video_settings();
39 framesize = 4 * v.get_width() * v.get_height();
40 width = v.get_width();
41 height = v.get_height();
43 std::stringstream commandline;
44 commandline << "x264 ";
45 commandline << expand_options(options, v.get_rate_num(), v.get_rate_denum());
46 commandline << " - -o " << filename << " " << v.get_width() << "x" << v.get_height();
47 std::string s = commandline.str();
48 out = popen(s.c_str(), "w");
49 if(!out) {
50 std::stringstream str;
51 str << "Can't run x264 (" << s << ")";
52 throw std::runtime_error(str.str());
56 void video_callback(uint64_t timestamp, const uint8_t* raw_rgbx_data)
58 I420_convert_common(raw_rgbx_data, width, height, out, true);
60 private:
61 FILE* out;
62 std::string filename;
63 std::string options;
64 size_t framesize;
65 uint32_t width;
66 uint32_t height;
69 class output_driver_x264_factory : output_driver_factory
71 public:
72 output_driver_x264_factory()
73 : output_driver_factory("x264")
77 output_driver& make(const std::string& type, const std::string& name, const std::string& parameters)
79 return *new output_driver_x264(name, parameters);
81 } factory;