| 1 | #include <functional> |
| 2 | #include <iostream> |
| 3 | #include <memory> |
| 4 | #include <ostream> |
| 5 | #include <sstream> |
| 6 | #include <vector> |
| 7 | |
| 8 | #include "assert.h" |
| 9 | |
| 10 | #ifndef USE_GI_MODULE |
| 11 | // no inline as the implementation is provided by other TUs |
| 12 | // #define GI_INLINE 1 |
| 13 | #include <gst/gst.hpp> |
| 14 | #else |
| 15 | // optional, but recommended if gi macros are used |
| 16 | #include <gi/gi_inc.hpp> |
| 17 | // we also use some gst macros and api |
| 18 | #include <gst/gst.h> |
| 19 | // import used modules |
| 20 | import gi.repo.gobject; |
| 21 | import gi.repo.gst; |
| 22 | #endif |
| 23 | |
| 24 | namespace GLib = gi::repository::GLib; |
| 25 | namespace Gst = gi::repository::Gst; |
| 26 | namespace GObject_ = gi::repository::GObject; |
| 27 | |
| 28 | void |
| 29 | say(const std::string &msg) |
| 30 | { |
| 31 | std::cout << msg << std::endl; |
| 32 | } |
| 33 | |
| 34 | void |
| 35 | die(const std::string &why) |
| 36 | { |
| 37 | std::cerr << why << std::endl; |
| 38 | exit(2); |
| 39 | } |
| 40 | |
| 41 | class Player |
| 42 | { |
| 43 | typedef Player self; |
| 44 | |
| 45 | GLib::MainLoop loop_; |
| 46 | std::string url_; |
| 47 | |
| 48 | Gst::Element playbin_; |
| 49 | bool live_ = false; |
| 50 | Gst::Element vfilter_; |
| 51 | Gst::Element afilter_; |
| 52 | std::map<std::string, Gst::Element> filter_; |
| 53 | GLib::SourceScopedConnection monitor_; |
| 54 | GObject_::SignalConnection busconn_; |
| 55 | |
| 56 | public: |
| 57 | Player(GLib::MainLoop loop, const std::string &url) : loop_(loop), url_(url) |
| 58 | { |
| 59 | playbin_ = Gst::ElementFactory::make("playbin"); |
| 60 | assert(playbin_); |
| 61 | // get a property |
| 62 | // this one is known at introspection time |
| 63 | // (so type is known and suitable checked) |
| 64 | auto name = playbin_.property_name().get(); |
| 65 | std::cout << "created playbin " << name << std::endl; |
| 66 | } |
| 67 | |
| 68 | void start() |
| 69 | { |
| 70 | // set some property |
| 71 | playbin_.set_property("uri", url_); |
| 72 | // ... or several ones |
| 73 | playbin_.set_properties("volume", 0.5, "mute", false); |
| 74 | // ... non-primitive also possible |
| 75 | vfilter_ = Gst::ElementFactory::make("identity", "vfilter"); |
| 76 | afilter_ = Gst::ElementFactory::make("identity", "afilter"); |
| 77 | playbin_.set_properties("video-filter", vfilter_, "audio-filter", afilter_); |
| 78 | |
| 79 | // connect some; find out what the source element is |
| 80 | // signal not known to introspection, so have to provide signature here |
| 81 | playbin_.connect<void(Gst::Element, Gst::Element)>( |
| 82 | "source-setup", gi::mem_fun(&self::on_source_setup, this)); |
| 83 | // for a known signal, it is a bit easier to connect |
| 84 | auto bus = playbin_.get_bus(); |
| 85 | bus.add_signal_watch(); |
| 86 | // signal connect; using introspected (hence checked) signal definition |
| 87 | // could do without the slot step here and directly pass the lambda, |
| 88 | // but wrapping it this way allows combining this with the returned |
| 89 | // (plain) id into a scoped connection guard |
| 90 | auto slot = bus.signal_message().slot(gi::mem_fun(&self::on_message, this)); |
| 91 | busconn_ = |
| 92 | gi::make_connection(bus.signal_message().connect(slot), slot, bus); |
| 93 | // again, if the guard is not desired; the following simply suffices |
| 94 | if (false) |
| 95 | bus.signal_message().connect(gi::mem_fun(&self::on_message, this)); |
| 96 | // if the signal signature is somehow not supported |
| 97 | // then the following is a fallback manual method |
| 98 | // which still allows to use lambda (and such) |
| 99 | // and also provides some ownership management |
| 100 | if (false) { |
| 101 | auto h = [](GstBus *, GstMessage *) { |
| 102 | // dummy no-op |
| 103 | }; |
| 104 | bus.connect_unchecked<void(GstBus *, GstMessage *)>("message", h); |
| 105 | } |
| 106 | // likewise, if a callback is to be used whose arguments are not supported |
| 107 | // or in a function that is not supported, then the following is a fallback |
| 108 | // which still allows to use lambda (and such) |
| 109 | // and also provides some ownership management |
| 110 | if (false) { |
| 111 | auto h = []() { return false; }; |
| 112 | auto cb = new gi::callback_wrapper<gboolean(), false>(h); |
| 113 | // now the above pointer is managed as user data |
| 114 | // and will be suitable destroyed when needed |
| 115 | g_idle_add_full(0, &cb->wrapper, cb, &cb->destroy); |
| 116 | // in case of a typical single-use async callback (with no GDestroyNotify) |
| 117 | // use true as AUTODESTROY template parameter |
| 118 | // (then it will auto-clean up after invoking callback) |
| 119 | } |
| 120 | // alternatively, maybe there is some API that accepts a Closure |
| 121 | // the following are some convenient ways to get a closure |
| 122 | if (false) { |
| 123 | GLib::LogFunc h = [](gi::cstring_v log_domain, |
| 124 | GLib::LogLevelFlags log_level, |
| 125 | gi::cstring_v message) { |
| 126 | (void)log_domain; |
| 127 | (void)log_level; |
| 128 | (void)message; |
| 129 | }; |
| 130 | GObject_::Closure::from_callback(h); |
| 131 | } |
| 132 | // likewise, but with a bit more manual (C++) signature specification |
| 133 | if (false) { |
| 134 | auto h = [](GObject_::Object, int) {}; |
| 135 | GObject_::Closure::from_functor<void(GObject_::Object, int)>(h); |
| 136 | } |
| 137 | |
| 138 | say("Setting pipeline to PAUSED ..."); |
| 139 | auto ret = playbin_.set_state(Gst::State::PAUSED_); |
| 140 | if (ret == Gst::StateChangeReturn::FAILURE_) { |
| 141 | die("Pipeline does not want to pause"); |
| 142 | } else if (ret == Gst::StateChangeReturn::NO_PREROLL_) { |
| 143 | say("Pipeline is live and does not need PREROLL ..."); |
| 144 | live_ = true; |
| 145 | } else if (ret == Gst::StateChangeReturn::ASYNC_) { |
| 146 | say("Pipeline is PREROLLING ..."); |
| 147 | } |
| 148 | |
| 149 | // inspect after a while |
| 150 | GLib::timeout_add_seconds(2, [this]() { |
| 151 | inspect(); |
| 152 | return GLib::SOURCE_REMOVE_; |
| 153 | }); |
| 154 | |
| 155 | // some regular progress reporting ... |
| 156 | GLib::SourceFunc func = [this]() { |
| 157 | progress(); |
| 158 | return GLib::SOURCE_CONTINUE_; |
| 159 | }; |
| 160 | // the introspected function returns a plain id, |
| 161 | // which can be used in the usual way to disconnect |
| 162 | // e.g. at destructor time of owning object |
| 163 | // alternatively, a helper scoped object can take care of that |
| 164 | monitor_ = gi::make_connection(GLib::timeout_add_seconds(1, func), func); |
| 165 | // other such make_connection variations exist; |
| 166 | // e.g. for a signal connection, a probe callback |
| 167 | // (and can easily be custom added) |
| 168 | |
| 169 | // add a pad probe; use a casual lambda |
| 170 | // but not too casual, mind (dangling) references/pointers though |
| 171 | filter_["video"] = vfilter_; |
| 172 | filter_["audio"] = afilter_; |
| 173 | for (auto &&p : filter_) { |
| 174 | if (p.second) { |
| 175 | Gst::Pad pad = p.second.get_static_pad("sink"); |
| 176 | auto name = p.first; |
| 177 | auto handler = [name](Gst::Pad p, Gst::PadProbeInfo_Ref info) { |
| 178 | auto s = p.get_path_string(); |
| 179 | s += "received " + name + " buffer"; |
| 180 | auto buffer = info.get_buffer(); |
| 181 | if (buffer) { |
| 182 | s += " of size "; |
| 183 | s += std::to_string(buffer.get_size()); |
| 184 | } |
| 185 | return Gst::PadProbeReturn::REMOVE_; |
| 186 | }; |
| 187 | pad.add_probe(Gst::PadProbeType::BUFFER_, handler); |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | // shamelessly demo some helpers that aid in caps/value handling |
| 192 | auto caps = Gst::Caps::new_empty_simple("video/x-raw"); |
| 193 | caps.set_value("width", GObject_::Value(Gst::IntRange(240, 320))); |
| 194 | caps.set_value("pixel-aspect-ratio", GObject_::Value(Gst::Fraction(4, 3))); |
| 195 | caps.set_value( |
| 196 | "framerate", GObject_::Value(Gst::FractionRange({25, 1}, 30))); |
| 197 | // retrieving pretty much the same way |
| 198 | auto s = caps.get_structure(0); |
| 199 | auto par = s.get_value("pixel-aspect-ratio").get_value<Gst::Fraction>(); |
| 200 | // helpers also stream to string properly |
| 201 | std::ostringstream oss; |
| 202 | oss << par; |
| 203 | oss << (Gst::FlagSet(1, 1) == Gst::FlagSet(2, 1)); |
| 204 | // silly test code to exercise some operators |
| 205 | // Rank override allows for succinct numeric conversion |
| 206 | if (+Gst::Rank::PRIMARY_ + 0) { |
| 207 | // flags support various typical operations |
| 208 | (void)(Gst::PadProbeType::BUFFER_ | Gst::PadProbeType::BUFFER_LIST_); |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | void stop() |
| 213 | { |
| 214 | if (playbin_) |
| 215 | playbin_.set_state(Gst::State::NULL_); |
| 216 | loop_.quit(); |
| 217 | } |
| 218 | |
| 219 | void on_message(Gst::Bus /*bus*/, Gst::Message_Ref msg) |
| 220 | { |
| 221 | auto &&src = msg.src_(); |
| 222 | switch (msg.type_()) { |
| 223 | case Gst::MessageType::EOS_: |
| 224 | say("Got EOS from " + src.get_path_string()); |
| 225 | stop(); |
| 226 | break; |
| 227 | case Gst::MessageType::ERROR_: { |
| 228 | GLib::Error err; |
| 229 | gi::cstring debug; |
| 230 | msg.parse_error(&err, &debug); |
| 231 | say("Got error from " + src.get_path_string()); |
| 232 | if (debug.size()) |
| 233 | say("debug info:\n" + debug); |
| 234 | break; |
| 235 | } |
| 236 | case Gst::MessageType::STATE_CHANGED_: |
| 237 | /* only handle top-level case */ |
| 238 | if (src != playbin_) |
| 239 | break; |
| 240 | Gst::State old, new_, pending; |
| 241 | msg.parse_state_changed(&old, &new_, &pending); |
| 242 | if (new_ == Gst::State::PAUSED_ && old == Gst::State::READY_) |
| 243 | playbin_.set_state(Gst::State::PLAYING_); |
| 244 | break; |
| 245 | default: |
| 246 | // never mind |
| 247 | break; |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | void on_source_setup(Gst::Element /*pb*/, Gst::Element src) |
| 252 | { |
| 253 | say("source is " + src.get_path_string()); |
| 254 | } |
| 255 | |
| 256 | void inspect() |
| 257 | { |
| 258 | std::ostringstream oss; |
| 259 | // this should work |
| 260 | auto bin = gi::object_cast<Gst::Bin>(playbin_); |
| 261 | assert(bin); |
| 262 | // a dynamically loaded element may implement a number of interfaces |
| 263 | // which is not known at compile-time |
| 264 | // the cast above can also cast to interface, which can be obtained as |
| 265 | // follows if known at introspection/compile time |
| 266 | auto cp = bin.interface_(gi::interface_tag<Gst::ChildProxy>()); |
| 267 | oss << "player bin has " << cp.get_children_count() << " children" |
| 268 | << std::endl; |
| 269 | // get some properties (dynamically, i.e. not known at introspection |
| 270 | // time) type will have to match (i.e. transformable) at runtime |
| 271 | auto n_v = playbin_.get_property<int>("n-video"); |
| 272 | auto n_a = playbin_.get_property<int>("n-audio"); |
| 273 | // minimal stuff |
| 274 | oss << "sample streams: video=" << n_v << ", audio=" << n_a << std::endl; |
| 275 | // show some tag info |
| 276 | for (auto &&p : |
| 277 | std::map<std::string, int>{{"video", n_v}, {"audio", n_a}}) { |
| 278 | for (int i = 0; i < p.second; ++i) { |
| 279 | // the argument's type should match the signal definition |
| 280 | // (cast if needed to make it so) |
| 281 | auto action = std::string("get-"); |
| 282 | action += p.first + "-tags"; |
| 283 | auto taglist = playbin_.emit<Gst::TagList>(action, i); |
| 284 | if (!taglist) |
| 285 | continue; |
| 286 | auto ntags = taglist.n_tags(); |
| 287 | oss << p.first << " stream " << i << std::endl; |
| 288 | for (int j = 0; j < ntags; ++j) { |
| 289 | auto tname = taglist.nth_tag_name(j); |
| 290 | auto value = taglist.get_value_index(tname, 0); |
| 291 | #if GI_CONFIG_EXCEPTIONS |
| 292 | try { |
| 293 | #endif |
| 294 | auto sval = value.transform_value<std::string>(); |
| 295 | oss << " " << tname << ": " << sval << std::endl; |
| 296 | #if GI_CONFIG_EXCEPTIONS |
| 297 | } catch (...) { |
| 298 | // could be object or otherwise, never mind |
| 299 | } |
| 300 | #endif |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | // should also have caps here by now |
| 306 | // there are other ways to obtain this, but let's go this way here |
| 307 | for (auto &&p : filter_) { |
| 308 | if (p.second) { |
| 309 | Gst::Pad pad = p.second.get_static_pad("sink"); |
| 310 | auto caps = pad.get_current_caps(); |
| 311 | oss << p.first << " caps: " << caps.to_string() << std::endl; |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | say(oss.str()); |
| 316 | |
| 317 | say("Playbin elements:"); |
| 318 | // Gst::Iterator could be used with native interface |
| 319 | // but a helper wrapper has been provided that supports ease-of-use as |
| 320 | // in ... |
| 321 | for (auto &&el : Gst::IteratorAdapter<Gst::Element>(bin.iterate_recurse())) |
| 322 | say(el.get_path_string()); |
| 323 | say(""); |
| 324 | } |
| 325 | |
| 326 | static std::string time_to_str(Gst::ClockTime time) |
| 327 | { |
| 328 | // could be done otherwise |
| 329 | // but we have native C access at hand, so let's use that |
| 330 | auto s = g_strdup_printf("%" GST_TIME_FORMAT, GST_TIME_ARGS(time)); |
| 331 | std::string ret(s); |
| 332 | g_free(s); |
| 333 | return ret; |
| 334 | } |
| 335 | |
| 336 | void progress() |
| 337 | { |
| 338 | bool ok = true; |
| 339 | gint64 duration = -1, position = -1; |
| 340 | ok &= playbin_.query_duration(Gst::Format::TIME_, &duration); |
| 341 | ok &= playbin_.query_position(Gst::Format::TIME_, &position); |
| 342 | std::ostringstream oss; |
| 343 | if (ok) { |
| 344 | oss << "Duration: " << time_to_str(duration) |
| 345 | << ", Position: " << time_to_str(position); |
| 346 | } else { |
| 347 | oss << "No progress info available"; |
| 348 | } |
| 349 | say(oss.str()); |
| 350 | } |
| 351 | }; |
| 352 | |
| 353 | #ifdef GI_CLASS_IMPL |
| 354 | // not used in the above, but serves as a subclass example |
| 355 | class ChattyBin : public Gst::impl::BinImpl |
| 356 | { |
| 357 | public: |
| 358 | #if 0 |
| 359 | // this part is only needed if there is some conflict |
| 360 | // (among members of class and/or interfaces) |
| 361 | // otherwise it should be auto-detected |
| 362 | struct DefinitionData |
| 363 | { |
| 364 | GI_DEFINES_MEMBER(BinClassDef, add_element, true) |
| 365 | }; |
| 366 | #endif |
| 367 | |
| 368 | ChattyBin() : Gst::impl::BinImpl(this) {} |
| 369 | |
| 370 | bool add_element_(Gst::Element element) noexcept override |
| 371 | { |
| 372 | say("adding element " + element.name_() + '\n'); |
| 373 | return Gst::impl::BinImpl::add_element_(element); |
| 374 | } |
| 375 | }; |
| 376 | #endif |
| 377 | |
| 378 | int |
| 379 | main(int argc, char **argv) |
| 380 | { |
| 381 | if (argc < 2) |
| 382 | die("missing argument"); |
| 383 | |
| 384 | // C signature fits C main best anyway |
| 385 | gst_init(&argc, &argv); |
| 386 | |
| 387 | std::string url = argv[1]; |
| 388 | // make it URL if not so |
| 389 | if (!Gst::Uri::is_valid(url)) { |
| 390 | #if GI_CONFIG_EXCEPTIONS |
| 391 | try { |
| 392 | #endif |
| 393 | url = gi::expect(Gst::filename_to_uri(url)); |
| 394 | #if GI_CONFIG_EXCEPTIONS |
| 395 | } catch (const GLib::Error &ex) { |
| 396 | die(ex.what()); |
| 397 | } |
| 398 | #endif |
| 399 | } |
| 400 | |
| 401 | say("Playing " + url); |
| 402 | |
| 403 | // simply local var will do here |
| 404 | auto loop = GLib::MainLoop::new_(); |
| 405 | Player player(loop, url); |
| 406 | |
| 407 | // schedule start |
| 408 | GLib::idle_add([&] { |
| 409 | player.start(); |
| 410 | return GLib::SOURCE_REMOVE_; |
| 411 | }); |
| 412 | // ... and auto end after a while |
| 413 | GLib::timeout_add_seconds(10, [&] { |
| 414 | player.stop(); |
| 415 | return GLib::SOURCE_REMOVE_; |
| 416 | }); |
| 417 | |
| 418 | loop.run(); |
| 419 | } |