repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
axispod/vmpl
include/vmpl/split.h
<reponame>axispod/vmpl<filename>include/vmpl/split.h #pragma once #include "holder.h" namespace vmpl { namespace { template<unsigned int Position, typename ... Args> struct split_helper; template<unsigned int Position, typename T, typename ... Args> struct split_helper<Position, T, Args...> { typedef typename split_helper<Position - 1, Args...> recursive_type; typedef typename make_holder<T, typename recursive_type::head_type>::type head_type; typedef typename recursive_type::tail_type tail_type; }; template<typename ... Args> struct split_helper<0, Args...> { typedef holder<> head_type; typedef holder<Args...> tail_type; }; template<unsigned int Position> struct split_helper<Position>; template<> struct split_helper<0> { typedef holder<> head_type; typedef holder<> tail_type; }; } template<unsigned int Position, typename ... Args> struct split : public split_helper<Position, Args...>{}; template<unsigned int Position, typename ... Args> struct split<Position, holder<Args...>> : public split_helper<Position, Args...>{}; }
gamestake/frames-ios
iOS Example Frame Carthage/Frames/Frames.h
// // Frames.h // Frames // // Created by Harry.Brown on 01/04/2021. // Copyright © 2021 Checkout. All rights reserved. // #import <Foundation/Foundation.h> //! Project version number for Frames. FOUNDATION_EXPORT double FramesVersionNumber; //! Project version string for Frames. FOUNDATION_EXPORT const unsigned char FramesVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <Frames/PublicHeader.h>
pyshx/serenity
Userland/Libraries/LibIPC/Encoder.h
/* * Copyright (c) 2018-2021, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/Concepts.h> #include <AK/StdLibExtras.h> #include <LibIPC/Forward.h> #include <LibIPC/Message.h> namespace IPC { template<typename T> bool encode(Encoder&, T&) { static_assert(DependentFalse<T>, "Base IPC::encode() was instantiated"); VERIFY_NOT_REACHED(); } class Encoder { public: explicit Encoder(MessageBuffer& buffer) : m_buffer(buffer) { } Encoder& operator<<(bool); Encoder& operator<<(u8); Encoder& operator<<(u16); Encoder& operator<<(u32); Encoder& operator<<(u64); Encoder& operator<<(i8); Encoder& operator<<(i16); Encoder& operator<<(i32); Encoder& operator<<(i64); Encoder& operator<<(float); Encoder& operator<<(char const*); Encoder& operator<<(StringView const&); Encoder& operator<<(String const&); Encoder& operator<<(ByteBuffer const&); Encoder& operator<<(URL const&); Encoder& operator<<(Dictionary const&); Encoder& operator<<(File const&); template<typename K, typename V> Encoder& operator<<(HashMap<K, V> const& hashmap) { *this << (u32)hashmap.size(); for (auto it : hashmap) { *this << it.key; *this << it.value; } return *this; } template<typename T> Encoder& operator<<(Vector<T> const& vector) { *this << (u64)vector.size(); for (auto& value : vector) *this << value; return *this; } template<Enum T> Encoder& operator<<(T const& enum_value) { *this << AK::to_underlying(enum_value); return *this; } template<typename T> Encoder& operator<<(T const& value) { encode(value); return *this; } template<typename T> Encoder& operator<<(Optional<T> const& optional) { *this << optional.has_value(); if (optional.has_value()) *this << optional.value(); return *this; } template<typename T> void encode(T const& value) { IPC::encode(*this, value); } private: MessageBuffer& m_buffer; }; }
pyshx/serenity
Kernel/Module.h
/* * Copyright (c) 2018-2020, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/String.h> #include <AK/Vector.h> #include <Kernel/KBuffer.h> namespace Kernel { typedef void* (*ModuleInitPtr)(); typedef void* (*ModuleFiniPtr)(); struct Module { String name; NonnullOwnPtrVector<KBuffer> sections; ModuleInitPtr module_init { nullptr }; ModuleFiniPtr module_fini { nullptr }; }; }
pyshx/serenity
Userland/Applications/Magnifier/MagnifierWidget.h
<filename>Userland/Applications/Magnifier/MagnifierWidget.h /* * Copyright (c) 2021, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <LibGUI/Frame.h> class MagnifierWidget final : public GUI::Frame { C_OBJECT(MagnifierWidget); public: virtual ~MagnifierWidget(); void set_scale_factor(int scale_factor); private: MagnifierWidget(); virtual void paint_event(GUI::PaintEvent&) override; void sync(); int m_scale_factor { 2 }; RefPtr<Gfx::Bitmap> m_grabbed_bitmap; };
pyshx/serenity
Kernel/Net/LocalSocket.h
<reponame>pyshx/serenity /* * Copyright (c) 2018-2020, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/IntrusiveList.h> #include <Kernel/DoubleBuffer.h> #include <Kernel/Net/Socket.h> namespace Kernel { class OpenFileDescription; struct SocketPair { NonnullRefPtr<OpenFileDescription> description0; NonnullRefPtr<OpenFileDescription> description1; }; class LocalSocket final : public Socket { public: static KResultOr<NonnullRefPtr<LocalSocket>> try_create(int type); static KResultOr<SocketPair> try_create_connected_pair(int type); virtual ~LocalSocket() override; KResult sendfd(const OpenFileDescription& socket_description, OpenFileDescription& passing_description); KResultOr<NonnullRefPtr<OpenFileDescription>> recvfd(const OpenFileDescription& socket_description); static void for_each(Function<void(const LocalSocket&)>); StringView socket_path() const; String absolute_path(const OpenFileDescription& description) const override; // ^Socket virtual KResult bind(Userspace<const sockaddr*>, socklen_t) override; virtual KResult connect(OpenFileDescription&, Userspace<const sockaddr*>, socklen_t, ShouldBlock = ShouldBlock::Yes) override; virtual KResult listen(size_t) override; virtual void get_local_address(sockaddr*, socklen_t*) override; virtual void get_peer_address(sockaddr*, socklen_t*) override; virtual KResult attach(OpenFileDescription&) override; virtual void detach(OpenFileDescription&) override; virtual bool can_read(const OpenFileDescription&, size_t) const override; virtual bool can_write(const OpenFileDescription&, size_t) const override; virtual KResultOr<size_t> sendto(OpenFileDescription&, const UserOrKernelBuffer&, size_t, int, Userspace<const sockaddr*>, socklen_t) override; virtual KResultOr<size_t> recvfrom(OpenFileDescription&, UserOrKernelBuffer&, size_t, int flags, Userspace<sockaddr*>, Userspace<socklen_t*>, Time&) override; virtual KResult getsockopt(OpenFileDescription&, int level, int option, Userspace<void*>, Userspace<socklen_t*>) override; virtual KResult ioctl(OpenFileDescription&, unsigned request, Userspace<void*> arg) override; virtual KResult chown(OpenFileDescription&, UserID, GroupID) override; virtual KResult chmod(OpenFileDescription&, mode_t) override; private: explicit LocalSocket(int type, NonnullOwnPtr<DoubleBuffer> client_buffer, NonnullOwnPtr<DoubleBuffer> server_buffer); virtual StringView class_name() const override { return "LocalSocket"; } virtual bool is_local() const override { return true; } bool has_attached_peer(const OpenFileDescription&) const; DoubleBuffer* receive_buffer_for(OpenFileDescription&); DoubleBuffer* send_buffer_for(OpenFileDescription&); NonnullRefPtrVector<OpenFileDescription>& sendfd_queue_for(const OpenFileDescription&); NonnullRefPtrVector<OpenFileDescription>& recvfd_queue_for(const OpenFileDescription&); void set_connect_side_role(Role connect_side_role, bool force_evaluate_block_conditions = false) { auto previous = m_connect_side_role; m_connect_side_role = connect_side_role; if (previous != m_connect_side_role || force_evaluate_block_conditions) evaluate_block_conditions(); } KResult try_set_path(StringView); // An open socket file on the filesystem. RefPtr<OpenFileDescription> m_file; UserID m_prebind_uid { 0 }; GroupID m_prebind_gid { 0 }; mode_t m_prebind_mode { 0 }; // A single LocalSocket is shared between two file descriptions // on the connect side and the accept side; so we need to store // an additional role for the connect side and differentiate // between them. Role m_connect_side_role { Role::None }; OpenFileDescription* m_connect_side_fd { nullptr }; virtual Role role(const OpenFileDescription& description) const override { if (m_connect_side_fd == &description) return m_connect_side_role; return m_role; } bool m_bound { false }; bool m_accept_side_fd_open { false }; OwnPtr<KString> m_path; NonnullOwnPtr<DoubleBuffer> m_for_client; NonnullOwnPtr<DoubleBuffer> m_for_server; NonnullRefPtrVector<OpenFileDescription> m_fds_for_client; NonnullRefPtrVector<OpenFileDescription> m_fds_for_server; IntrusiveListNode<LocalSocket> m_list_node; public: using List = IntrusiveList<LocalSocket, RawPtr<LocalSocket>, &LocalSocket::m_list_node>; }; }
pyshx/serenity
Userland/Applications/PixelPaint/RectangleTool.h
/* * Copyright (c) 2018-2020, <NAME> <<EMAIL>> * Copyright (c) 2021, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include "Tool.h" #include <LibGUI/Forward.h> #include <LibGfx/Point.h> namespace PixelPaint { class RectangleTool final : public Tool { public: RectangleTool(); virtual ~RectangleTool() override; virtual void on_mousedown(Layer*, MouseEvent&) override; virtual void on_mousemove(Layer*, MouseEvent&) override; virtual void on_mouseup(Layer*, MouseEvent&) override; virtual void on_second_paint(Layer const*, GUI::PaintEvent&) override; virtual void on_keydown(GUI::KeyEvent&) override; virtual GUI::Widget* get_properties_widget() override; virtual Gfx::StandardCursor cursor() override { return Gfx::StandardCursor::Crosshair; } private: enum class FillMode { Outline, Fill, Gradient, }; enum class DrawMode { FromCenter, FromCorner, }; void draw_using(GUI::Painter&, Gfx::IntPoint const& start_position, Gfx::IntPoint const& end_position, int thickness); RefPtr<GUI::Widget> m_properties_widget; GUI::MouseButton m_drawing_button { GUI::MouseButton::None }; Gfx::IntPoint m_rectangle_start_position; Gfx::IntPoint m_rectangle_end_position; FillMode m_fill_mode { FillMode::Outline }; DrawMode m_draw_mode { DrawMode::FromCorner }; int m_thickness { 1 }; }; }
pyshx/serenity
Userland/Applications/Piano/Music.h
/* * Copyright (c) 2018-2020, <NAME> <<EMAIL>> * Copyright (c) 2019-2020, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/Types.h> #include <LibGfx/Color.h> namespace Music { // CD quality // - Stereo // - 16 bit // - 44,100 samples/sec // - 1,411.2 kbps struct Sample { i16 left; i16 right; }; // HACK: needs to increase with device sample rate, but all of the sample_count stuff is static for now constexpr int sample_count = 1 << 12; constexpr int buffer_size = sample_count * sizeof(Sample); constexpr double sample_rate = 44100; constexpr double volume_factor = 1800; enum Switch { Off, On, }; struct RollNote { u32 length() const { return (off_sample - on_sample) + 1; } u32 on_sample; u32 off_sample; u8 pitch; i8 velocity; }; enum Direction { Down, Up, }; enum Wave { Sine, Triangle, Square, Saw, Noise, RecordedSample, }; constexpr const char* wave_strings[] = { "Sine", "Triangle", "Square", "Saw", "Noise", "Frame", }; constexpr int first_wave = Sine; constexpr int last_wave = RecordedSample; enum Envelope { Done, Attack, Decay, Release, }; enum KeyColor { White, Black, }; constexpr KeyColor key_pattern[] = { White, Black, White, Black, White, White, Black, White, Black, White, Black, White, }; const Color note_pressed_color(64, 64, 255); const Color column_playing_color(128, 128, 255); const Color left_wave_colors[] = { // Sine { 255, 192, 0, }, // Triangle { 35, 171, 35, }, // Square { 128, 160, 255, }, // Saw { 240, 100, 128, }, // Noise { 197, 214, 225, }, // RecordedSample { 227, 39, 39, }, }; const Color right_wave_colors[] = { // Sine { 255, 223, 0, }, // Triangle { 35, 171, 90, }, // Square { 139, 128, 255, }, // Saw { 240, 100, 220, }, // Noise { 197, 223, 225, }, // RecordedSample { 227, 105, 39, }, }; constexpr int notes_per_octave = 12; constexpr int white_keys_per_octave = 7; constexpr int black_keys_per_octave = 5; constexpr int octave_min = 1; constexpr int octave_max = 7; // These values represent the user-side bounds, the application may use a different scale. constexpr int attack_max = 1000; constexpr int decay_max = 1000; constexpr int sustain_max = 1000; constexpr int release_max = 1000; constexpr int volume_max = 1000; constexpr int delay_max = 8; constexpr double beats_per_minute = 60; constexpr int beats_per_bar = 4; constexpr int notes_per_beat = 4; constexpr int roll_length = (sample_rate / (beats_per_minute / 60)) * beats_per_bar; constexpr const char* note_names[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B", }; // Equal temperament, A = 440Hz // We calculate note frequencies relative to A4: // 440.0 * pow(pow(2.0, 1.0 / 12.0), N) // Where N is the note distance from A. constexpr double note_frequencies[] = { // Octave 1 32.703195662574764, 34.647828872108946, 36.708095989675876, 38.890872965260044, 41.203444614108669, 43.653528929125407, 46.249302838954222, 48.99942949771858, 51.913087197493056, 54.999999999999915, 58.270470189761156, 61.735412657015416, // Octave 2 65.406391325149571, 69.295657744217934, 73.416191979351794, 77.781745930520117, 82.406889228217381, 87.307057858250872, 92.4986056779085, 97.998858995437217, 103.82617439498618, 109.99999999999989, 116.54094037952237, 123.4708253140309, // Octave 3 130.8127826502992, 138.59131548843592, 146.83238395870364, 155.56349186104035, 164.81377845643485, 174.61411571650183, 184.99721135581709, 195.99771799087452, 207.65234878997245, 219.99999999999989, 233.08188075904488, 246.94165062806198, // Octave 4 261.62556530059851, 277.18263097687202, 293.66476791740746, 311.12698372208081, 329.62755691286986, 349.22823143300383, 369.99442271163434, 391.99543598174927, 415.30469757994513, 440, 466.16376151808993, 493.88330125612413, // Octave 5 523.25113060119736, 554.36526195374427, 587.32953583481526, 622.25396744416196, 659.25511382574007, 698.456462866008, 739.98884542326903, 783.99087196349899, 830.60939515989071, 880.00000000000034, 932.32752303618031, 987.76660251224882, // Octave 6 1046.5022612023952, 1108.7305239074892, 1174.659071669631, 1244.5079348883246, 1318.5102276514808, 1396.9129257320169, 1479.977690846539, 1567.9817439269987, 1661.2187903197821, 1760.000000000002, 1864.6550460723618, 1975.5332050244986, // Octave 7 2093.0045224047913, 2217.4610478149793, 2349.3181433392633, 2489.0158697766506, 2637.020455302963, 2793.8258514640347, 2959.9553816930793, 3135.9634878539991, 3322.437580639566, 3520.0000000000055, 3729.3100921447249, 3951.0664100489994, }; constexpr int note_count = sizeof(note_frequencies) / sizeof(double); constexpr double middle_c = note_frequencies[36]; } using namespace Music;
pyshx/serenity
Kernel/Devices/SerialDevice.h
<reponame>pyshx/serenity /* * Copyright (c) 2018-2020, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <Kernel/Devices/CharacterDevice.h> #include <Kernel/IO.h> namespace Kernel { class SerialDevice final : public CharacterDevice { AK_MAKE_ETERNAL public: static NonnullRefPtr<SerialDevice> must_create(size_t com_number); virtual ~SerialDevice() override; // ^CharacterDevice virtual bool can_read(const OpenFileDescription&, size_t) const override; virtual KResultOr<size_t> read(OpenFileDescription&, u64, UserOrKernelBuffer&, size_t) override; virtual bool can_write(const OpenFileDescription&, size_t) const override; virtual KResultOr<size_t> write(OpenFileDescription&, u64, const UserOrKernelBuffer&, size_t) override; void put_char(char); enum InterruptEnable { LowPowerMode = 0x01 << 5, SleepMode = 0x01 << 4, ModemStatusInterrupt = 0x01 << 3, ReceiverLineStatusInterrupt = 0x01 << 2, TransmitterHoldingRegisterEmptyInterrupt = 0x01 << 1, ReceivedDataAvailableInterrupt = 0x01 << 0 }; enum Baud { Baud50 = 2304, Baud110 = 1047, Baud220 = 524, Baud300 = 384, Baud600 = 192, Baud1200 = 96, Baud2400 = 48, Baud4800 = 24, Baud9600 = 12, Baud19200 = 6, Baud38400 = 3, Baud57600 = 2, Baud115200 = 1 }; enum ParitySelect { None = 0x00 << 3, Odd = 0x01 << 3, Even = 0x03 << 3, Mark = 0x05 << 3, Space = 0x07 << 3 }; enum StopBits { One = 0x00 << 2, Two = 0x01 << 2 }; enum WordLength { FiveBits = 0x00, SixBits = 0x01, SevenBits = 0x02, EightBits = 0x03 }; enum FIFOControl { EnableFIFO = 0x01 << 0, ClearReceiveFIFO = 0x01 << 1, ClearTransmitFIFO = 0x01 << 2, Enable64ByteFIFO = 0x01 << 5, TriggerLevel1 = 0x00 << 6, TriggerLevel2 = 0x01 << 6, TriggerLevel3 = 0x02 << 6, TriggerLevel4 = 0x03 << 6 }; enum ModemControl { AutoflowControlEnabled = 0x01 << 5, LoopbackMode = 0x01 << 4, AuxiliaryOutput2 = 0x01 << 3, AuxiliaryOutput1 = 0x01 << 2, RequestToSend = 0x01 << 1, DataTerminalReady = 0x01 << 0 }; enum LineStatus { ErrorInReceivedFIFO = 0x01 << 7, EmptyDataHoldingRegisters = 0x01 << 6, EmptyTransmitterHoldingRegister = 0x01 << 5, BreakInterrupt = 0x01 << 4, FramingError = 0x01 << 3, ParityError = 0x01 << 2, OverrunError = 0x01 << 1, DataReady = 0x01 << 0 }; private: friend class PCISerialDevice; SerialDevice(IOAddress base_addr, unsigned minor); // ^CharacterDevice virtual StringView class_name() const override { return "SerialDevice"; } void initialize(); void set_interrupts(bool interrupt_enable); void set_baud(Baud); void set_fifo_control(u8 fifo_control); void set_line_control(ParitySelect, StopBits, WordLength); void set_break_enable(bool break_enable); void set_modem_control(u8 modem_control); u8 get_line_status() const; IOAddress m_base_addr; bool m_interrupt_enable { false }; u8 m_fifo_control { 0 }; Baud m_baud { Baud38400 }; ParitySelect m_parity_select { None }; StopBits m_stop_bits { One }; WordLength m_word_length { EightBits }; bool m_break_enable { false }; u8 m_modem_control { 0 }; bool m_last_put_char_was_carriage_return { false }; Spinlock m_serial_lock; }; }
pyshx/serenity
Userland/Libraries/LibCrypto/Cipher/Mode/GCM.h
/* * Copyright (c) 2020, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/OwnPtr.h> #include <AK/String.h> #include <AK/StringBuilder.h> #include <AK/StringView.h> #include <LibCrypto/Authentication/GHash.h> #include <LibCrypto/Cipher/Mode/CTR.h> #include <LibCrypto/Verification.h> namespace Crypto { namespace Cipher { using IncrementFunction = IncrementInplace; template<typename T> class GCM : public CTR<T, IncrementFunction> { public: constexpr static size_t IVSizeInBits = 128; virtual ~GCM() { } template<typename... Args> explicit constexpr GCM<T>(Args... args) : CTR<T>(args...) { static_assert(T::BlockSizeInBits == 128u, "GCM Mode is only available for 128-bit Ciphers"); __builtin_memset(m_auth_key_storage, 0, block_size); typename T::BlockType key_block(m_auth_key_storage, block_size); this->cipher().encrypt_block(key_block, key_block); key_block.bytes().copy_to(m_auth_key); m_ghash = Authentication::GHash(m_auth_key); } virtual String class_name() const override { StringBuilder builder; builder.append(this->cipher().class_name()); builder.append("_GCM"); return builder.build(); } virtual size_t IV_length() const override { return IVSizeInBits / 8; } // FIXME: This overload throws away the auth stuff, think up a better way to return more than a single bytebuffer. virtual void encrypt(ReadonlyBytes in, Bytes& out, ReadonlyBytes ivec = {}, Bytes* = nullptr) override { VERIFY(!ivec.is_empty()); static ByteBuffer dummy; encrypt(in, out, ivec, dummy, dummy); } virtual void decrypt(ReadonlyBytes in, Bytes& out, ReadonlyBytes ivec = {}) override { encrypt(in, out, ivec); } void encrypt(const ReadonlyBytes& in, Bytes out, const ReadonlyBytes& iv_in, const ReadonlyBytes& aad, Bytes tag) { auto iv_buf_result = ByteBuffer::copy(iv_in); // Not enough memory to figure out :shrug: if (!iv_buf_result.has_value()) { dbgln("GCM::encrypt: Not enough memory to allocate {} bytes for IV", iv_in.size()); return; } auto iv = iv_buf_result->bytes(); // Increment the IV for block 0 CTR<T>::increment(iv); typename T::BlockType block0; block0.overwrite(iv); this->cipher().encrypt_block(block0, block0); // Skip past block 0 CTR<T>::increment(iv); if (in.is_empty()) CTR<T>::key_stream(out, iv); else CTR<T>::encrypt(in, out, iv); auto auth_tag = m_ghash->process(aad, out); block0.apply_initialization_vector({ auth_tag.data, array_size(auth_tag.data) }); block0.bytes().copy_to(tag); } VerificationConsistency decrypt(ReadonlyBytes in, Bytes out, ReadonlyBytes iv_in, ReadonlyBytes aad, ReadonlyBytes tag) { auto iv_buf_result = ByteBuffer::copy(iv_in); // Not enough memory to figure out :shrug: if (!iv_buf_result.has_value()) return VerificationConsistency::Inconsistent; auto iv = iv_buf_result->bytes(); // Increment the IV for block 0 CTR<T>::increment(iv); typename T::BlockType block0; block0.overwrite(iv); this->cipher().encrypt_block(block0, block0); // Skip past block 0 CTR<T>::increment(iv); auto auth_tag = m_ghash->process(aad, in); block0.apply_initialization_vector({ auth_tag.data, array_size(auth_tag.data) }); auto test_consistency = [&] { if (block0.block_size() != tag.size() || __builtin_memcmp(block0.bytes().data(), tag.data(), tag.size()) != 0) return VerificationConsistency::Inconsistent; return VerificationConsistency::Consistent; }; // FIXME: This block needs constant-time comparisons. if (in.is_empty()) { out = {}; return test_consistency(); } CTR<T>::encrypt(in, out, iv); return test_consistency(); } private: static constexpr auto block_size = T::BlockType::BlockSizeInBits / 8; u8 m_auth_key_storage[block_size]; Bytes m_auth_key { m_auth_key_storage, block_size }; Optional<Authentication::GHash> m_ghash; }; } }
pyshx/serenity
Userland/Services/AudioServer/ClientConnection.h
<gh_stars>1-10 /* * Copyright (c) 2018-2020, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/HashMap.h> #include <AudioServer/AudioClientEndpoint.h> #include <AudioServer/AudioServerEndpoint.h> #include <LibIPC/ClientConnection.h> namespace Audio { class Buffer; } namespace AudioServer { class BufferQueue; class Mixer; class ClientConnection final : public IPC::ClientConnection<AudioClientEndpoint, AudioServerEndpoint> { C_OBJECT(ClientConnection) public: explicit ClientConnection(NonnullRefPtr<Core::LocalSocket>, int client_id, Mixer& mixer); ~ClientConnection() override; void did_finish_playing_buffer(Badge<BufferQueue>, int buffer_id); void did_change_muted_state(Badge<Mixer>, bool muted); void did_change_main_mix_volume(Badge<Mixer>, int volume); virtual void die() override; static void for_each(Function<void(ClientConnection&)>); private: virtual Messages::AudioServer::GetMainMixVolumeResponse get_main_mix_volume() override; virtual void set_main_mix_volume(i32) override; virtual Messages::AudioServer::EnqueueBufferResponse enqueue_buffer(Core::AnonymousBuffer const&, i32, int) override; virtual Messages::AudioServer::GetRemainingSamplesResponse get_remaining_samples() override; virtual Messages::AudioServer::GetPlayedSamplesResponse get_played_samples() override; virtual void set_paused(bool) override; virtual void clear_buffer(bool) override; virtual Messages::AudioServer::GetPlayingBufferResponse get_playing_buffer() override; virtual Messages::AudioServer::GetMutedResponse get_muted() override; virtual void set_muted(bool) override; virtual void set_sample_rate(u16 sample_rate) override; virtual Messages::AudioServer::GetSampleRateResponse get_sample_rate() override; Mixer& m_mixer; RefPtr<BufferQueue> m_queue; }; }
pyshx/serenity
Userland/Libraries/LibCore/GetPassword.h
/* * Copyright (c) 2020, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/OSError.h> #include <AK/Result.h> #include <AK/String.h> namespace Core { Result<String, OSError> get_password(const StringView& prompt = "Password: "); }
pyshx/serenity
Userland/Libraries/LibWeb/HTML/HTMLScriptElement.h
<reponame>pyshx/serenity<gh_stars>0 /* * Copyright (c) 2018-2020, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/Function.h> #include <LibWeb/HTML/HTMLElement.h> namespace Web::HTML { class HTMLScriptElement final : public HTMLElement { public: using WrapperType = Bindings::HTMLScriptElementWrapper; HTMLScriptElement(DOM::Document&, QualifiedName); virtual ~HTMLScriptElement() override; bool is_non_blocking() const { return m_non_blocking; } bool is_ready_to_be_parser_executed() const { return m_ready_to_be_parser_executed; } bool failed_to_load() const { return m_failed_to_load; } void set_parser_document(Badge<HTMLDocumentParser>, DOM::Document&); void set_non_blocking(Badge<HTMLDocumentParser>, bool); void set_already_started(Badge<HTMLDocumentParser>, bool b) { m_already_started = b; } void prepare_script(Badge<HTMLDocumentParser>) { prepare_script(); } void execute_script(); bool is_parser_inserted() const { return !!m_parser_document; } virtual void inserted() override; // https://html.spec.whatwg.org/multipage/scripting.html#dom-script-supports static bool supports(String const& type) { return type.is_one_of("classic", "module"); } private: void prepare_script(); void script_became_ready(); void when_the_script_is_ready(Function<void()>); WeakPtr<DOM::Document> m_parser_document; WeakPtr<DOM::Document> m_preparation_time_document; bool m_non_blocking { false }; bool m_already_started { false }; bool m_from_an_external_file { false }; bool m_script_ready { false }; bool m_ready_to_be_parser_executed { false }; bool m_failed_to_load { false }; enum class ScriptType { Classic, Module }; ScriptType m_script_type { ScriptType::Classic }; Function<void()> m_script_ready_callback; String m_script_source; String m_script_filename; }; }
pyshx/serenity
Userland/Libraries/LibWeb/WebContentClient.h
<reponame>pyshx/serenity /* * Copyright (c) 2020-2021, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/HashMap.h> #include <LibIPC/ServerConnection.h> #include <LibWeb/Cookie/ParsedCookie.h> #include <WebContent/WebContentClientEndpoint.h> #include <WebContent/WebContentServerEndpoint.h> namespace Web { class OutOfProcessWebView; class WebContentClient final : public IPC::ServerConnection<WebContentClientEndpoint, WebContentServerEndpoint> , public WebContentClientEndpoint { C_OBJECT(WebContentClient); public: Function<void()> on_web_content_process_crash; private: WebContentClient(OutOfProcessWebView&); virtual void die() override; virtual void did_paint(Gfx::IntRect const&, i32) override; virtual void did_finish_loading(URL const&) override; virtual void did_invalidate_content_rect(Gfx::IntRect const&) override; virtual void did_change_selection() override; virtual void did_request_cursor_change(i32) override; virtual void did_layout(Gfx::IntSize const&) override; virtual void did_change_title(String const&) override; virtual void did_request_scroll(int) override; virtual void did_request_scroll_into_view(Gfx::IntRect const&) override; virtual void did_enter_tooltip_area(Gfx::IntPoint const&, String const&) override; virtual void did_leave_tooltip_area() override; virtual void did_hover_link(URL const&) override; virtual void did_unhover_link() override; virtual void did_click_link(URL const&, String const&, unsigned) override; virtual void did_middle_click_link(URL const&, String const&, unsigned) override; virtual void did_start_loading(URL const&) override; virtual void did_request_context_menu(Gfx::IntPoint const&) override; virtual void did_request_link_context_menu(Gfx::IntPoint const&, URL const&, String const&, unsigned) override; virtual void did_request_image_context_menu(Gfx::IntPoint const&, URL const&, String const&, unsigned, Gfx::ShareableBitmap const&) override; virtual void did_get_source(URL const&, String const&) override; virtual void did_get_dom_tree(String const&) override; virtual void did_get_dom_node_properties(i32 node_id, String const& specified_style, String const& computed_style) override; virtual void did_output_js_console_message(i32 message_index) override; virtual void did_get_js_console_messages(i32 start_index, Vector<String> const& message_types, Vector<String> const& messages) override; virtual void did_change_favicon(Gfx::ShareableBitmap const&) override; virtual void did_request_alert(String const&) override; virtual Messages::WebContentClient::DidRequestConfirmResponse did_request_confirm(String const&) override; virtual Messages::WebContentClient::DidRequestPromptResponse did_request_prompt(String const&, String const&) override; virtual Messages::WebContentClient::DidRequestCookieResponse did_request_cookie(URL const&, u8) override; virtual void did_set_cookie(URL const&, Web::Cookie::ParsedCookie const&, u8) override; OutOfProcessWebView& m_view; }; }
pyshx/serenity
Kernel/ACPI/Parser.h
<reponame>pyshx/serenity /* * Copyright (c) 2020, <NAME>. <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/Types.h> #include <Kernel/ACPI/Definitions.h> #include <Kernel/ACPI/Initialize.h> #include <Kernel/FileSystem/SysFSComponent.h> #include <Kernel/Memory/Region.h> #include <Kernel/PhysicalAddress.h> #include <Kernel/VirtualAddress.h> namespace Kernel::ACPI { class ACPISysFSDirectory : public SysFSDirectory { public: static void initialize(); private: ACPISysFSDirectory(); }; class ACPISysFSComponent : public SysFSComponent { public: static NonnullRefPtr<ACPISysFSComponent> create(String name, PhysicalAddress, size_t table_size); virtual KResultOr<size_t> read_bytes(off_t, size_t, UserOrKernelBuffer&, OpenFileDescription*) const override; protected: KResultOr<NonnullOwnPtr<KBuffer>> try_to_generate_buffer() const; ACPISysFSComponent(String name, PhysicalAddress, size_t table_size); PhysicalAddress m_paddr; size_t m_length; }; class Parser { public: static Parser* the(); template<typename ParserType> static void initialize(PhysicalAddress rsdp) { set_the(*new ParserType(rsdp)); } virtual Optional<PhysicalAddress> find_table(const StringView& signature); virtual void try_acpi_reboot(); virtual bool can_reboot(); virtual void try_acpi_shutdown(); virtual bool can_shutdown() { return false; } PhysicalAddress rsdp() const { return m_rsdp; } PhysicalAddress main_system_description_table() const { return m_main_system_description_table; } bool is_xsdt_supported() const { return m_xsdt_supported; } void enumerate_static_tables(Function<void(const StringView&, PhysicalAddress, size_t)>); virtual bool have_8042() const { return m_x86_specific_flags.keyboard_8042; } const FADTFlags::HardwareFeatures& hardware_features() const { return m_hardware_flags; } const FADTFlags::x86_Specific_Flags& x86_specific_flags() const { return m_x86_specific_flags; } virtual void enable_aml_interpretation(); virtual void enable_aml_interpretation(File&); virtual void enable_aml_interpretation(u8*, u32); virtual void disable_aml_interpretation(); protected: explicit Parser(PhysicalAddress rsdp); virtual ~Parser() = default; private: static void set_the(Parser&); void locate_static_data(); void locate_main_system_description_table(); void initialize_main_system_description_table(); size_t get_table_size(PhysicalAddress); u8 get_table_revision(PhysicalAddress); void init_fadt(); void init_facs(); bool validate_reset_register(); void access_generic_address(const Structures::GenericAddressStructure&, u32 value); PhysicalAddress m_rsdp; PhysicalAddress m_main_system_description_table; Vector<PhysicalAddress> m_sdt_pointers; PhysicalAddress m_fadt; PhysicalAddress m_facs; bool m_xsdt_supported { false }; FADTFlags::HardwareFeatures m_hardware_flags; FADTFlags::x86_Specific_Flags m_x86_specific_flags; }; }
pyshx/serenity
Kernel/TimerQueue.h
/* * Copyright (c) 2018-2020, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/Function.h> #include <AK/IntrusiveList.h> #include <AK/NonnullRefPtr.h> #include <AK/OwnPtr.h> #include <AK/RefCounted.h> #include <AK/Time.h> #include <Kernel/Time/TimeManagement.h> namespace Kernel { TYPEDEF_DISTINCT_ORDERED_ID(u64, TimerId); class Timer : public RefCounted<Timer> { friend class TimerQueue; public: void setup(clockid_t clock_id, Time expires, Function<void()>&& callback) { VERIFY(!is_queued()); m_clock_id = clock_id; m_expires = expires; m_callback = move(callback); } ~Timer() { VERIFY(!is_queued()); } Time remaining() const; private: TimerId m_id; clockid_t m_clock_id; Time m_expires; Time m_remaining {}; Function<void()> m_callback; Atomic<bool> m_cancelled { false }; Atomic<bool> m_callback_finished { false }; Atomic<bool> m_in_use { false }; bool operator<(const Timer& rhs) const { return m_expires < rhs.m_expires; } bool operator>(const Timer& rhs) const { return m_expires > rhs.m_expires; } bool operator==(const Timer& rhs) const { return m_id == rhs.m_id; } void clear_cancelled() { return m_cancelled.store(false, AK::memory_order_release); } bool set_cancelled() { return m_cancelled.exchange(true, AK::memory_order_acq_rel); } bool is_in_use() { return m_in_use.load(AK::memory_order_acquire); }; void set_in_use() { m_in_use.store(true, AK::memory_order_release); } void clear_in_use() { return m_in_use.store(false, AK::memory_order_release); } bool is_callback_finished() const { return m_callback_finished.load(AK::memory_order_acquire); } void clear_callback_finished() { m_callback_finished.store(false, AK::memory_order_release); } void set_callback_finished() { m_callback_finished.store(true, AK::memory_order_release); } Time now(bool) const; bool is_queued() const { return m_list_node.is_in_list(); } public: IntrusiveListNode<Timer> m_list_node; using List = IntrusiveList<Timer, RawPtr<Timer>, &Timer::m_list_node>; }; class TimerQueue { friend class Timer; public: TimerQueue(); static TimerQueue& the(); TimerId add_timer(NonnullRefPtr<Timer>&&); bool add_timer_without_id(NonnullRefPtr<Timer>, clockid_t, const Time&, Function<void()>&&); bool cancel_timer(Timer& timer, bool* was_in_use = nullptr); void fire(); private: struct Queue { Timer::List list; Time next_timer_due {}; }; void remove_timer_locked(Queue&, Timer&); void update_next_timer_due(Queue&); void add_timer_locked(NonnullRefPtr<Timer>); Queue& queue_for_timer(Timer& timer) { switch (timer.m_clock_id) { case CLOCK_MONOTONIC: case CLOCK_MONOTONIC_COARSE: case CLOCK_MONOTONIC_RAW: return m_timer_queue_monotonic; case CLOCK_REALTIME: case CLOCK_REALTIME_COARSE: return m_timer_queue_realtime; default: VERIFY_NOT_REACHED(); } } u64 m_timer_id_count { 0 }; u64 m_ticks_per_second { 0 }; Queue m_timer_queue_monotonic; Queue m_timer_queue_realtime; Timer::List m_timers_executing; }; }
pyshx/serenity
Userland/Services/WebContent/PageHost.h
/* * Copyright (c) 2020-2021, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <LibGfx/Rect.h> #include <LibWeb/Page/Page.h> namespace WebContent { class ClientConnection; class PageHost final : public Web::PageClient { AK_MAKE_NONCOPYABLE(PageHost); AK_MAKE_NONMOVABLE(PageHost); public: static NonnullOwnPtr<PageHost> create(ClientConnection& client) { return adopt_own(*new PageHost(client)); } virtual ~PageHost(); Web::Page& page() { return *m_page; } const Web::Page& page() const { return *m_page; } void paint(const Gfx::IntRect& content_rect, Gfx::Bitmap&); void set_palette_impl(const Gfx::PaletteImpl&); void set_viewport_rect(const Gfx::IntRect&); void set_screen_rects(const Vector<Gfx::IntRect, 4>& rects, size_t main_screen_index) { m_screen_rect = rects[main_screen_index]; }; void set_should_show_line_box_borders(bool b) { m_should_show_line_box_borders = b; } private: // ^PageClient virtual Gfx::Palette palette() const override; virtual Gfx::IntRect screen_rect() const override { return m_screen_rect; } virtual void page_did_invalidate(const Gfx::IntRect&) override; virtual void page_did_change_selection() override; virtual void page_did_request_cursor_change(Gfx::StandardCursor) override; virtual void page_did_layout() override; virtual void page_did_change_title(const String&) override; virtual void page_did_request_scroll(int) override; virtual void page_did_request_scroll_into_view(const Gfx::IntRect&) override; virtual void page_did_enter_tooltip_area(const Gfx::IntPoint&, const String&) override; virtual void page_did_leave_tooltip_area() override; virtual void page_did_hover_link(const URL&) override; virtual void page_did_unhover_link() override; virtual void page_did_click_link(const URL&, const String& target, unsigned modifiers) override; virtual void page_did_middle_click_link(const URL&, const String& target, unsigned modifiers) override; virtual void page_did_request_context_menu(const Gfx::IntPoint&) override; virtual void page_did_request_link_context_menu(const Gfx::IntPoint&, const URL&, const String& target, unsigned modifiers) override; virtual void page_did_start_loading(const URL&) override; virtual void page_did_finish_loading(const URL&) override; virtual void page_did_request_alert(const String&) override; virtual bool page_did_request_confirm(const String&) override; virtual String page_did_request_prompt(const String&, const String&) override; virtual void page_did_change_favicon(const Gfx::Bitmap&) override; virtual void page_did_request_image_context_menu(const Gfx::IntPoint&, const URL&, const String& target, unsigned modifiers, const Gfx::Bitmap*) override; virtual String page_did_request_cookie(const URL&, Web::Cookie::Source) override; virtual void page_did_set_cookie(const URL&, const Web::Cookie::ParsedCookie&, Web::Cookie::Source) override; explicit PageHost(ClientConnection&); Web::Layout::InitialContainingBlock* layout_root(); void setup_palette(); ClientConnection& m_client; NonnullOwnPtr<Web::Page> m_page; RefPtr<Gfx::PaletteImpl> m_palette_impl; Gfx::IntRect m_screen_rect; bool m_should_show_line_box_borders { false }; }; }
pyshx/serenity
Userland/Applications/PixelPaint/ProjectLoader.h
/* * Copyright (c) 2021, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include "Image.h" #include <AK/JsonArray.h> #include <AK/Result.h> #include <AK/StringView.h> namespace PixelPaint { class ProjectLoader { public: ProjectLoader() = default; ~ProjectLoader() = default; Result<void, String> try_load_from_fd_and_close(int fd, StringView path); Result<void, String> try_load_from_path(StringView path); bool is_raw_image() const { return m_is_raw_image; } bool has_image() const { return !m_image.is_null(); } RefPtr<Image> release_image() const { return move(m_image); } JsonArray const& json_metadata() const { return m_json_metadata; } private: RefPtr<Image> m_image { nullptr }; bool m_is_raw_image { false }; JsonArray m_json_metadata {}; }; }
pyshx/serenity
Kernel/Arch/x86/Processor.h
<reponame>pyshx/serenity<gh_stars>0 /* * Copyright (c) 2018-2021, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/Array.h> #include <AK/Concepts.h> #include <AK/Function.h> #include <AK/Types.h> #include <Kernel/Arch/x86/ASM_wrapper.h> #include <Kernel/Arch/x86/CPUID.h> #include <Kernel/Arch/x86/DescriptorTable.h> #include <Kernel/Arch/x86/PageDirectory.h> #include <Kernel/Arch/x86/TSS.h> #include <Kernel/Forward.h> namespace Kernel { class ProcessorInfo; struct ProcessorMessageEntry; enum class ProcessorSpecificDataID { MemoryManager, __Count, }; #if ARCH(X86_64) # define MSR_FS_BASE 0xc0000100 # define MSR_GS_BASE 0xc0000101 #endif // FIXME: Find a better place for these extern "C" void thread_context_first_enter(void); extern "C" void exit_kernel_thread(void); extern "C" void do_assume_context(Thread* thread, u32 flags); struct [[gnu::aligned(16)]] FPUState { u8 buffer[512]; }; struct ProcessorMessage { using CallbackFunction = Function<void()>; enum Type { FlushTlb, Callback, }; Type type; Atomic<u32> refs; union { ProcessorMessage* next; // only valid while in the pool alignas(CallbackFunction) u8 callback_storage[sizeof(CallbackFunction)]; struct { Memory::PageDirectory const* page_directory; u8* ptr; size_t page_count; } flush_tlb; }; volatile bool async; ProcessorMessageEntry* per_proc_entries; CallbackFunction& callback_value() { return *bit_cast<CallbackFunction*>(&callback_storage); } void invoke_callback() { VERIFY(type == Type::Callback); callback_value()(); } }; struct ProcessorMessageEntry { ProcessorMessageEntry* next; ProcessorMessage* msg; }; struct DeferredCallEntry { using HandlerFunction = Function<void()>; DeferredCallEntry* next; alignas(HandlerFunction) u8 handler_storage[sizeof(HandlerFunction)]; bool was_allocated; HandlerFunction& handler_value() { return *bit_cast<HandlerFunction*>(&handler_storage); } void invoke_handler() { handler_value()(); } }; class Processor; // Note: We only support 64 processors at most at the moment, // so allocate 64 slots of inline capacity in the container. using ProcessorContainer = Array<Processor*, 64>; class Processor { friend class ProcessorInfo; AK_MAKE_NONCOPYABLE(Processor); AK_MAKE_NONMOVABLE(Processor); Processor* m_self; DescriptorTablePointer m_gdtr; Descriptor m_gdt[256]; u32 m_gdt_length; u32 m_cpu; FlatPtr m_in_irq; volatile u32 m_in_critical; static Atomic<u32> s_idle_cpu_mask; TSS m_tss; static FPUState s_clean_fpu_state; CPUFeature m_features; static Atomic<u32> g_total_processors; u8 m_physical_address_bit_width; ProcessorInfo* m_info; Thread* m_current_thread; Thread* m_idle_thread; Atomic<ProcessorMessageEntry*> m_message_queue; bool m_invoke_scheduler_async; bool m_scheduler_initialized; bool m_in_scheduler; Atomic<bool> m_halt_requested; DeferredCallEntry* m_pending_deferred_calls; // in reverse order DeferredCallEntry* m_free_deferred_call_pool_entry; DeferredCallEntry m_deferred_call_pool[5]; void* m_processor_specific_data[(size_t)ProcessorSpecificDataID::__Count]; void gdt_init(); void write_raw_gdt_entry(u16 selector, u32 low, u32 high); void write_gdt_entry(u16 selector, Descriptor& descriptor); static ProcessorContainer& processors(); static void smp_return_to_pool(ProcessorMessage& msg); static ProcessorMessage& smp_get_from_pool(); static void smp_cleanup_message(ProcessorMessage& msg); bool smp_enqueue_message(ProcessorMessage&); static void smp_unicast_message(u32 cpu, ProcessorMessage& msg, bool async); static void smp_broadcast_message(ProcessorMessage& msg); static void smp_broadcast_wait_sync(ProcessorMessage& msg); static void smp_broadcast_halt(); void deferred_call_pool_init(); void deferred_call_execute_pending(); DeferredCallEntry* deferred_call_get_free(); void deferred_call_return_to_pool(DeferredCallEntry*); void deferred_call_queue_entry(DeferredCallEntry*); void cpu_detect(); void cpu_setup(); String features_string() const; public: Processor() = default; void early_initialize(u32 cpu); void initialize(u32 cpu); void detect_hypervisor(); void detect_hypervisor_hyperv(CPUID const& hypervisor_leaf_range); void idle_begin() { s_idle_cpu_mask.fetch_or(1u << m_cpu, AK::MemoryOrder::memory_order_relaxed); } void idle_end() { s_idle_cpu_mask.fetch_and(~(1u << m_cpu), AK::MemoryOrder::memory_order_relaxed); } static Processor& by_id(u32); static u32 count() { // NOTE: because this value never changes once all APs are booted, // we can safely bypass loading it atomically. return *g_total_processors.ptr(); } ALWAYS_INLINE static void pause() { asm volatile("pause"); } ALWAYS_INLINE static void wait_check() { Processor::pause(); if (Processor::is_smp_enabled()) Processor::current().smp_process_pending_messages(); } [[noreturn]] static void halt(); static void flush_entire_tlb_local() { write_cr3(read_cr3()); } static void flush_tlb_local(VirtualAddress vaddr, size_t page_count); static void flush_tlb(Memory::PageDirectory const*, VirtualAddress, size_t); Descriptor& get_gdt_entry(u16 selector); void flush_gdt(); const DescriptorTablePointer& get_gdtr(); static size_t processor_count() { return processors().size(); } template<IteratorFunction<Processor&> Callback> static inline IterationDecision for_each(Callback callback) { auto& procs = processors(); size_t count = procs.size(); for (size_t i = 0; i < count; i++) { if (callback(*procs[i]) == IterationDecision::Break) return IterationDecision::Break; } return IterationDecision::Continue; } template<VoidFunction<Processor&> Callback> static inline IterationDecision for_each(Callback callback) { auto& procs = processors(); size_t count = procs.size(); for (size_t i = 0; i < count; i++) { if (procs[i] != nullptr) callback(*procs[i]); } return IterationDecision::Continue; } ALWAYS_INLINE u8 physical_address_bit_width() const { return m_physical_address_bit_width; } ALWAYS_INLINE ProcessorInfo& info() { return *m_info; } static bool is_smp_enabled(); ALWAYS_INLINE static Processor& current() { return *(Processor*)read_gs_ptr(__builtin_offsetof(Processor, m_self)); } ALWAYS_INLINE static bool is_initialized() { return #if ARCH(I386) get_gs() == GDT_SELECTOR_PROC && #endif read_gs_ptr(__builtin_offsetof(Processor, m_self)) != 0; } template<typename T> T* get_specific() { return static_cast<T*>(m_processor_specific_data[static_cast<size_t>(T::processor_specific_data_id())]); } void set_specific(ProcessorSpecificDataID specific_id, void* ptr) { m_processor_specific_data[static_cast<size_t>(specific_id)] = ptr; } ALWAYS_INLINE void set_idle_thread(Thread& idle_thread) { m_idle_thread = &idle_thread; } ALWAYS_INLINE static Thread* current_thread() { // If we were to use Processor::current here, we'd have to // disable interrupts to prevent a race where we may get pre-empted // right after getting the Processor structure and then get moved // to another processor, which would lead us to get the wrong thread. // To avoid having to disable interrupts, we can just read the field // directly in an atomic fashion, similar to Processor::current. return (Thread*)read_gs_ptr(__builtin_offsetof(Processor, m_current_thread)); } ALWAYS_INLINE static void set_current_thread(Thread& current_thread) { // See comment in Processor::current_thread write_gs_ptr(__builtin_offsetof(Processor, m_current_thread), FlatPtr(&current_thread)); } ALWAYS_INLINE static Thread* idle_thread() { // See comment in Processor::current_thread return (Thread*)read_gs_ptr(__builtin_offsetof(Processor, m_idle_thread)); } ALWAYS_INLINE u32 id() const { // NOTE: This variant should only be used when iterating over all // Processor instances, or when it's guaranteed that the thread // cannot move to another processor in between calling Processor::current // and Processor::get_id, or if this fact is not important. // All other cases should use Processor::id instead! return m_cpu; } ALWAYS_INLINE static u32 current_id() { // See comment in Processor::current_thread return read_gs_ptr(__builtin_offsetof(Processor, m_cpu)); } ALWAYS_INLINE static bool is_bootstrap_processor() { return Processor::current_id() == 0; } ALWAYS_INLINE static FlatPtr current_in_irq() { return read_gs_ptr(__builtin_offsetof(Processor, m_in_irq)); } ALWAYS_INLINE static void restore_in_critical(u32 critical) { write_gs_ptr(__builtin_offsetof(Processor, m_in_critical), critical); } ALWAYS_INLINE static void enter_critical() { write_gs_ptr(__builtin_offsetof(Processor, m_in_critical), in_critical() + 1); } ALWAYS_INLINE static bool current_in_scheduler() { return read_gs_value<decltype(m_in_scheduler)>(__builtin_offsetof(Processor, m_in_scheduler)); } ALWAYS_INLINE static void set_current_in_scheduler(bool value) { write_gs_value<decltype(m_in_scheduler)>(__builtin_offsetof(Processor, m_in_scheduler), value); } private: ALWAYS_INLINE void do_leave_critical() { VERIFY(m_in_critical > 0); if (m_in_critical == 1) { if (!m_in_irq) { deferred_call_execute_pending(); VERIFY(m_in_critical == 1); } m_in_critical = 0; if (!m_in_irq) check_invoke_scheduler(); } else { m_in_critical = m_in_critical - 1; } } public: ALWAYS_INLINE static void leave_critical() { current().do_leave_critical(); } ALWAYS_INLINE static u32 clear_critical() { auto prev_critical = in_critical(); write_gs_ptr(__builtin_offsetof(Processor, m_in_critical), 0); auto& proc = current(); if (!proc.m_in_irq) proc.check_invoke_scheduler(); return prev_critical; } ALWAYS_INLINE static void restore_critical(u32 prev_critical) { // NOTE: This doesn't have to be atomic, and it's also fine if we // get preempted in between these steps. If we move to another // processors m_in_critical will move along with us. And if we // are preempted, we would resume with the same flags. write_gs_ptr(__builtin_offsetof(Processor, m_in_critical), prev_critical); } ALWAYS_INLINE static u32 in_critical() { // See comment in Processor::current_thread return read_gs_ptr(__builtin_offsetof(Processor, m_in_critical)); } ALWAYS_INLINE static FPUState const& clean_fpu_state() { return s_clean_fpu_state; } static void smp_enable(); bool smp_process_pending_messages(); static void smp_unicast(u32 cpu, Function<void()>, bool async); static void smp_broadcast_flush_tlb(Memory::PageDirectory const*, VirtualAddress, size_t); static u32 smp_wake_n_idle_processors(u32 wake_count); static void deferred_call_queue(Function<void()> callback); ALWAYS_INLINE bool has_feature(CPUFeature f) const { return (static_cast<u32>(m_features) & static_cast<u32>(f)) != 0; } void check_invoke_scheduler(); void invoke_scheduler_async() { m_invoke_scheduler_async = true; } void enter_trap(TrapFrame& trap, bool raise_irq); void exit_trap(TrapFrame& trap); [[noreturn]] void initialize_context_switching(Thread& initial_thread); NEVER_INLINE void switch_context(Thread*& from_thread, Thread*& to_thread); [[noreturn]] static void assume_context(Thread& thread, FlatPtr flags); FlatPtr init_context(Thread& thread, bool leave_crit); static Vector<FlatPtr> capture_stack_trace(Thread& thread, size_t max_frames = 0); static StringView platform_string(); }; template<typename T> class ProcessorSpecific { public: static void initialize() { Processor::current().set_specific(T::processor_specific_data_id(), new T); } static T& get() { return *Processor::current().get_specific<T>(); } }; }
pyshx/serenity
Userland/Libraries/LibJS/Runtime/Intl/LocalePrototype.h
/* * Copyright (c) 2021, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <LibJS/Runtime/Object.h> namespace JS::Intl { class LocalePrototype final : public Object { JS_OBJECT(LocalePrototype, Object); public: explicit LocalePrototype(GlobalObject&); virtual void initialize(GlobalObject&) override; virtual ~LocalePrototype() override = default; private: JS_DECLARE_NATIVE_FUNCTION(maximize); JS_DECLARE_NATIVE_FUNCTION(minimize); JS_DECLARE_NATIVE_FUNCTION(to_string); JS_DECLARE_NATIVE_GETTER(base_name); JS_DECLARE_NATIVE_GETTER(calendar); JS_DECLARE_NATIVE_GETTER(case_first); JS_DECLARE_NATIVE_GETTER(collation); JS_DECLARE_NATIVE_GETTER(hour_cycle); JS_DECLARE_NATIVE_GETTER(numbering_system); JS_DECLARE_NATIVE_GETTER(numeric); JS_DECLARE_NATIVE_GETTER(language); JS_DECLARE_NATIVE_GETTER(script); JS_DECLARE_NATIVE_GETTER(region); }; }
Ric92/frustum_clipping
include/ConvexPolyhedron.h
#ifndef CONVEXPOLYHEDRON_H_ #define CONVEXPOLYHEDRON_H_ #include <Eigen/Eigen> #include "Facet.h" #include <pcl/point_types.h> #include <pcl/surface/convex_hull.h> class ConvexPolyhedron { public: ConvexPolyhedron(); std::unordered_map<std::string, std::shared_ptr<Facet>> getFacets(); void setFacets(std::unordered_map<std::string, std::shared_ptr<Facet>> _facets); std::vector<Eigen::Vector3f> getVertices(); void setVertices(std::vector<Eigen::Vector3f> _vertices); float getVolume(); void setVolume(float _volume); void clipConvexPolyhedron(std::shared_ptr<ConvexPolyhedron> _convexPolyhedron, std::vector<Eigen::Vector3f> &_intersectionPoints); float computeVolumeFromPoints(std::vector<Eigen::Vector3f> _points); private: bool clipSegmentFacets(std::unordered_map<std::string, std::shared_ptr<Facet>> _polyhedronFacets, std::pair<Eigen::Vector3f, Eigen::Vector3f> _segment, std::vector<Eigen::Vector3f> &_output); bool isInsidePolyhedron(std::unordered_map<std::string, std::shared_ptr<Facet>> _polyhedron, Eigen::Vector3f _point); float distanceToPlane(Eigen::Vector4f _plane, Eigen::Vector3f _point); // Facets std::unordered_map<std::string, std::shared_ptr<Facet>> mFacets; //Vertex std::vector<Eigen::Vector3f> mVertices; //Volume float mVolume; }; #include <ConvexPolyhedron.inl> #endif // CONVEXPOLYHEDRON_H_
Ric92/frustum_clipping
include/Frustum.h
#ifndef FRUSTUM_H_ #define FRUSTUM_H_ #include <Eigen/Eigen> #include <utility> #include "Facet.h" #include <unordered_map> #include "ConvexPolyhedron.h" class Frustum : public ConvexPolyhedron { public: // _pose: Pose of Frustum // _hfov,_vfov: Vertical and horizontal FOV in degrees // _npDistance,fpDistance: Distance between pose and nearest and farest plane Frustum(int _id, Eigen::Matrix4f _pose, float _hfov, float _vfov, float _npDistance, float _fpDistance) { id = _id; mPose = _pose; mHFov = float(_vfov * M_PI / 180); // degrees to radians mVFov = float(_hfov * M_PI / 180); // degrees to radians mNpDistance = _npDistance; mFpDistance = _fpDistance; std::vector<Eigen::Vector3f> frustumVertices; Eigen::Vector3f view = mPose.block(0, 0, 3, 1); // view vector Eigen::Vector3f up = mPose.block(0, 1, 3, 1); // up vector Eigen::Vector3f right = mPose.block(0, 2, 3, 1); // right vector mPosition = mPose.block(0, 3, 3, 1); // Frustum position mNp_height = float(2 * tan(mVFov / 2) * mNpDistance); mNp_width = float(2 * tan(mHFov / 2) * mNpDistance); mFp_height = float(2 * tan(mVFov / 2) * mFpDistance); mFp_width = float(2 * tan(mHFov / 2) * mFpDistance); // far plane mFpCenter = mPosition + view * mFpDistance; mFpTopLeft = mFpCenter + (up * mFp_height / 2) - (right * mFp_width / 2); mFpTopRight = mFpCenter + (up * mFp_height / 2) + (right * mFp_width / 2); mFpBotLeft = mFpCenter - (up * mFp_height / 2) - (right * mFp_width / 2); mFpBotRight = mFpCenter - (up * mFp_height / 2) + (right * mFp_width / 2); // near plane mNpCenter = mPosition + view * mNpDistance; mNpTopLeft = mNpCenter + (up * mNp_height / 2) - (right * mNp_width / 2); mNpTopRight = mNpCenter + (up * mNp_height / 2) + (right * mNp_width / 2); mNpBotLeft = mNpCenter - (up * mNp_height / 2) - (right * mNp_width / 2); mNpBotRight = mNpCenter - (up * mNp_height / 2) + (right * mNp_width / 2); frustumVertices = {mFpTopLeft, mFpTopRight, mFpBotLeft, mFpBotRight, mNpTopLeft, mNpTopRight, mNpBotLeft, mNpBotRight}; std::unordered_map<std::string, std::shared_ptr<Facet>> frustumFacets; // Plane eq: Ax + By + Cz + D = 0 // Far plane mFplaneNormal = (mFpTopRight - mFpTopLeft).cross(mFpBotRight - mFpTopLeft); mFplaneNormal.normalize(); mFplane.head(3) = mFplaneNormal; mFplane[3] = -mFpTopRight.dot(mFplaneNormal); std::vector<Eigen::Vector3f> farVertex = {mFpTopRight, mFpTopLeft, mFpBotLeft, mFpBotRight}; std::shared_ptr<Facet> farFacet(new Facet(mFplane, farVertex)); frustumFacets["far"] = farFacet; // Near plane mNplaneNormal = mNpCenter - mFpCenter; mNplaneNormal.normalize(); mNplane.head(3) = mNplaneNormal; mNplane[3] = -mNpBotRight.dot(mNplaneNormal); std::vector<Eigen::Vector3f> nearVertex = {mNpTopRight, mNpTopLeft, mNpBotLeft, mNpBotRight}; std::shared_ptr<Facet> nearFacet(new Facet(mNplane, nearVertex)); frustumFacets["near"] = nearFacet; // Up plane mUpPlaneNormal = (mNpTopLeft - mFpTopLeft).cross(mNpTopRight - mFpTopLeft); mUpPlaneNormal.normalize(); mUpPlane.head(3) = mUpPlaneNormal; mUpPlane[3] = -mNpTopLeft.dot(mUpPlaneNormal); std::vector<Eigen::Vector3f> upVertex = {mNpTopRight, mNpTopLeft, mFpTopLeft, mFpTopRight}; std::shared_ptr<Facet> upFacet(new Facet(mUpPlane, upVertex)); frustumFacets["up"] = upFacet; // Down plane mDownPlaneNormal = -(mNpBotLeft - mFpBotLeft).cross(mNpBotRight - mFpBotLeft); mDownPlaneNormal.normalize(); mDownPlane.head(3) = mDownPlaneNormal; mDownPlane[3] = -mNpBotLeft.dot(mDownPlaneNormal); std::vector<Eigen::Vector3f> downVertex = {mNpBotRight, mNpBotLeft, mFpBotLeft, mFpBotRight}; std::shared_ptr<Facet> downFacet(new Facet(mDownPlane, downVertex)); frustumFacets["down"] = downFacet; // Right plane mRightPlaneNormal = -(mNpBotRight - mFpBotRight).cross(mNpTopRight - mFpBotRight); mRightPlaneNormal.normalize(); mRightPlane.head(3) = mRightPlaneNormal; mRightPlane[3] = -mNpBotRight.dot(mRightPlaneNormal); std::vector<Eigen::Vector3f> rightVertex = {mNpBotRight, mNpTopRight, mFpTopRight, mFpBotRight}; std::shared_ptr<Facet> rightFacet(new Facet(mRightPlane, rightVertex)); frustumFacets["right"] = rightFacet; // Left plane mLeftPlaneNormal = (mNpBotLeft - mFpBotLeft).cross(mNpTopLeft - mFpBotLeft); mLeftPlaneNormal.normalize(); mLeftPlane.head(3) = mLeftPlaneNormal; mLeftPlane[3] = -mNpBotLeft.dot(mLeftPlaneNormal); std::vector<Eigen::Vector3f> leftVertex = {mNpBotLeft, mNpTopLeft, mFpTopLeft, mFpBotLeft}; std::shared_ptr<Facet> leftFacet(new Facet(mLeftPlane, leftVertex)); frustumFacets["left"] = leftFacet; setFacets(frustumFacets); setVertices(frustumVertices); // Volume = (h/3) * (B1+B2+sqrt(B1+B2)) float nearArea = mNp_height * mNp_width; float farArea = mFp_height * mFp_width; setVolume(((mFpDistance - mNpDistance) / 3) * (nearArea + farArea + sqrt(nearArea + farArea))); } int id; // Frustum pose Eigen::Matrix4f mPose; Eigen::Vector3f mPosition; // FOV rad float mHFov; float mVFov; // Plane distance float mNpDistance; float mFpDistance; // Far plane float mFp_height; float mFp_width; Eigen::Vector3f mFpCenter; Eigen::Vector3f mFpTopLeft; Eigen::Vector3f mFpTopRight; Eigen::Vector3f mFpBotLeft; Eigen::Vector3f mFpBotRight; Eigen::Vector4f mFplane; Eigen::Vector3f mFplaneNormal; // Near plane float mNp_height; float mNp_width; Eigen::Vector3f mNpCenter; Eigen::Vector3f mNpTopLeft; Eigen::Vector3f mNpTopRight; Eigen::Vector3f mNpBotLeft; Eigen::Vector3f mNpBotRight; Eigen::Vector4f mNplane; Eigen::Vector3f mNplaneNormal; // Up plane Eigen::Vector4f mUpPlane; Eigen::Vector3f mUpPlaneNormal; // Down plane Eigen::Vector4f mDownPlane; Eigen::Vector3f mDownPlaneNormal; // Right plane Eigen::Vector4f mRightPlane; Eigen::Vector3f mRightPlaneNormal; // Left plane Eigen::Vector4f mLeftPlane; Eigen::Vector3f mLeftPlaneNormal; public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; #endif
Ric92/frustum_clipping
include/Cube.h
#ifndef CUBE_H_ #define CUBE_H_ #include <Eigen/Eigen> #include <utility> #include "Facet.h" #include <unordered_map> #include "ConvexPolyhedron.h" class Cube : public ConvexPolyhedron { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW // _pose: Pose of Frustum // _hfov,_vfov: Vertical and horizontal FOV in degrees // _npDistance,fpDistance: Distance between pose and nearest and farest // plane Cube(int _id, Eigen::Matrix4f _pose, float _width, float _heigth, float _deep) { id = _id; mPose = _pose; mWidth = _width; mHeigth = _heigth; mDeep = _deep; // back plane // heigth // ^ // | // |-->width // // v4----v1 // | | // v3----v2 Eigen::Vector3f v1(mWidth / 2, mDeep / 2, mHeigth / 2); Eigen::Vector3f v2(mWidth / 2, mDeep / 2, -mHeigth / 2); Eigen::Vector3f v3(-mWidth / 2, mDeep / 2, -mHeigth / 2); Eigen::Vector3f v4(-mWidth / 2, mDeep / 2, mHeigth / 2); // front plane // v8----v5 // | | // v7----v6 Eigen::Vector3f v5(mWidth / 2, -mDeep / 2, mHeigth / 2); Eigen::Vector3f v6(mWidth / 2, -mDeep / 2, -mHeigth / 2); Eigen::Vector3f v7(-mWidth / 2, -mDeep / 2, -mHeigth / 2); Eigen::Vector3f v8(-mWidth / 2, -mDeep / 2, mHeigth / 2); v1 = mPose.block(0, 0, 3, 3) * v1 + mPose.block(0, 3, 3, 1); v2 = mPose.block(0, 0, 3, 3) * v2 + mPose.block(0, 3, 3, 1); v3 = mPose.block(0, 0, 3, 3) * v3 + mPose.block(0, 3, 3, 1); v4 = mPose.block(0, 0, 3, 3) * v4 + mPose.block(0, 3, 3, 1); v5 = mPose.block(0, 0, 3, 3) * v5 + mPose.block(0, 3, 3, 1); v6 = mPose.block(0, 0, 3, 3) * v6 + mPose.block(0, 3, 3, 1); v7 = mPose.block(0, 0, 3, 3) * v7 + mPose.block(0, 3, 3, 1); v8 = mPose.block(0, 0, 3, 3) * v8 + mPose.block(0, 3, 3, 1); std::vector<Eigen::Vector3f> cubeVertices; cubeVertices = {v1, v2, v3, v4, v5, v6, v7, v8}; // TOP BACK // | / // v4----v1 / // / / // / / // LEFT<-- v8----v5 --> RIGHT // v3----v2 // / / // / / // v7----v6 // / // / // FRONT std::unordered_map<std::string, std::shared_ptr<Facet>> cubeFacets; // Plane eq: Ax + By + Cz + D = 0 // Back plane mBackplaneNormal = (v1 - v2).cross(v2 - v3); mBackplaneNormal.normalize(); mBackplane.head(3) = mBackplaneNormal; mBackplane[3] = -v1.dot(mBackplaneNormal); std::vector<Eigen::Vector3f> backVertex = {v1, v2, v3, v4}; std::shared_ptr<Facet> backFacet(new Facet(mBackplane, backVertex)); cubeFacets["back"] = backFacet; // Front plane mFrontplaneNormal = (v5 - v6).cross(v7 - v6); mFrontplaneNormal.normalize(); mFrontplane.head(3) = mFrontplaneNormal; mFrontplane[3] = -v5.dot(mFrontplaneNormal); std::vector<Eigen::Vector3f> nearVertex = {v5, v6, v7, v8}; std::shared_ptr<Facet> frontFacet(new Facet(mFrontplane, nearVertex)); cubeFacets["front"] = frontFacet; // Top plane mTopPlaneNormal = (v1 - v5).cross(v4 - v1); mTopPlane.head(3) = mTopPlaneNormal; mTopPlane[3] = -v1.dot(mTopPlaneNormal); std::vector<Eigen::Vector3f> topVertex = {v1, v5, v8, v4}; std::shared_ptr<Facet> topFacet(new Facet(mTopPlane, topVertex)); cubeFacets["top"] = topFacet; // Down plane mDownPlaneNormal = (v2 - v6).cross(v6 - v7); mDownPlaneNormal.normalize(); mDownPlane.head(3) = mDownPlaneNormal; mDownPlane[3] = -v2.dot(mDownPlaneNormal); std::vector<Eigen::Vector3f> downVertex = {v2, v6, v7, v3}; std::shared_ptr<Facet> downFacet(new Facet(mDownPlane, downVertex)); cubeFacets["down"] = downFacet; // Right plane mRightPlaneNormal = (v1 - v2).cross(v6 - v2); mRightPlaneNormal.normalize(); mRightPlane.head(3) = mRightPlaneNormal; mRightPlane[3] = -v1.dot(mRightPlaneNormal); std::vector<Eigen::Vector3f> rightVertex = {v1, v5, v6, v2}; std::shared_ptr<Facet> rightFacet(new Facet(mRightPlane, rightVertex)); cubeFacets["right"] = rightFacet; // Left plane mLeftPlaneNormal = (v8 - v7).cross(v3 - v7); mLeftPlaneNormal.normalize(); mLeftPlane.head(3) = mLeftPlaneNormal; mLeftPlane[3] = -v8.dot(mLeftPlaneNormal); std::vector<Eigen::Vector3f> leftVertex = {v4, v8, v7, v3}; std::shared_ptr<Facet> leftFacet(new Facet(mLeftPlane, leftVertex)); cubeFacets["left"] = leftFacet; setFacets(cubeFacets); setVertices(cubeVertices); setVolume(mWidth * mHeigth * mDeep); } int id; // Frustum pose Eigen::Matrix4f mPose; float mWidth, mHeigth, mDeep; // Back plane Eigen::Vector4f mBackplane; Eigen::Vector3f mBackplaneNormal; // Front plane Eigen::Vector4f mFrontplane; Eigen::Vector3f mFrontplaneNormal; // Top plane Eigen::Vector4f mTopPlane; Eigen::Vector3f mTopPlaneNormal; // Down plane Eigen::Vector4f mDownPlane; Eigen::Vector3f mDownPlaneNormal; // Right plane Eigen::Vector4f mRightPlane; Eigen::Vector3f mRightPlaneNormal; // Left plane Eigen::Vector4f mLeftPlane; Eigen::Vector3f mLeftPlaneNormal; }; #endif
Ric92/frustum_clipping
include/Facet.h
#ifndef FACET_H_ #define FACET_H_ #include <Eigen/Eigen> struct Facet { public: Facet(Eigen::Vector4f _plane, std::vector<Eigen::Vector3f> _vertex) : plane(_plane), vertex(_vertex){} Eigen::Vector4f plane; std::vector<Eigen::Vector3f> vertex; }; #endif
Ric92/frustum_clipping
include/Clipper.h
<reponame>Ric92/frustum_clipping #ifndef FRUSTUM_CLIPPING_CLIPPER_H_ #define FRUSTUM_CLIPPING_CLIPPER_H_ #include <Eigen/Eigen> #include "Frustum.h" #include "Facet.h" #include "Drawer.h" class Clipper { public: Clipper(); void clipFrustumFrustum(std::shared_ptr<Frustum> _frustum1, std::shared_ptr<Frustum> _frustum2, std::vector<Eigen::Vector3f> &_intersectionPoints); bool clipSegmentPlane(std::shared_ptr<Facet> _facet, std::pair<Eigen::Vector3f, Eigen::Vector3f> _segment, std::vector<Eigen::Vector3f> &_output); float distanceToPlane(Eigen::Vector4f _plane, Eigen::Vector3f _point); void clipSegmentFrustum(std::shared_ptr<Frustum> _frustum, std::pair<Eigen::Vector3f, Eigen::Vector3f> _segment, std::vector<Eigen::Vector3f> &_intersectionPoints); bool isInsidePolyhedron(std::unordered_map<std::string, std::shared_ptr<Facet>> _polyhedron, Eigen::Vector3f _point); private: Drawer<pcl::PointXYZRGB> *mDrawer = nullptr; }; #include <Clipper.inl> #endif // FRUSTUM_CLIPPING_CLIPPER_H_
Ric92/frustum_clipping
include/Drawer.h
#ifndef DRAWER_H_ #define DRAWER_H_ #include <opencv2/opencv.hpp> #include <pcl/io/pcd_io.h> #include <pcl/visualization/pcl_visualizer.h> #include <chrono> #include <thread> #include "Facet.h" template <typename PointType_> class Drawer { public: static bool init(); static Drawer *get() { return mSingleton; } void polyhedron(int _id, Eigen::Vector3f _position, std::unordered_map<std::string, std::shared_ptr<Facet>> _facets); void point(Eigen::Vector3f _point, std::string _id); void line(std::pair<Eigen::Vector3f, Eigen::Vector3f> _line, std::string _id); void plane(int id, Eigen::Vector4f _plane, std::vector<Eigen::Vector3f> _points); void spinOnce(); private: Drawer(); void keycallback(const pcl::visualization::KeyboardEvent &_event, void *_data); PointType_ eigenVector3fToPcl(Eigen::Vector3f _vec); private: boost::shared_ptr<pcl::visualization::PCLVisualizer> mViewer; bool mPause = false; static Drawer *mSingleton; }; #include "Drawer.inl" #endif
bjxagu/kms-core
src/gst-plugins/commons/sdpagent/kmssdpmidext.c
/* * (C) Copyright 2015 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <string.h> #include "kmsisdpmediaextension.h" #include "kmssdpmidext.h" #include "kmssdpagent.h" #include "kms-sdp-agent-marshal.h" #define OBJECT_NAME "sdpmidext" GST_DEBUG_CATEGORY_STATIC (kms_sdp_mid_ext_debug_category); #define GST_CAT_DEFAULT kms_sdp_mid_ext_debug_category #define parent_class kms_sdp_mid_ext_parent_class static void kms_i_sdp_media_extension_init (KmsISdpMediaExtensionInterface * iface); G_DEFINE_TYPE_WITH_CODE (KmsSdpMidExt, kms_sdp_mid_ext, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE (KMS_TYPE_I_SDP_MEDIA_EXTENSION, kms_i_sdp_media_extension_init) GST_DEBUG_CATEGORY_INIT (kms_sdp_mid_ext_debug_category, OBJECT_NAME, 0, "debug category for sdp mid_ext")); #define KMS_SDP_MID_EXT_GET_PRIVATE(obj) ( \ G_TYPE_INSTANCE_GET_PRIVATE ( \ (obj), \ KMS_TYPE_SDP_MID_EXT, \ KmsSdpMidExtPrivate \ ) \ ) #define MID_ATTR "mid" struct _KmsSdpMidExtPrivate { gchar *mid; }; /* Object properties */ enum { PROP_0, PROP_MID, N_PROPERTIES }; enum { SIGNAL_ON_OFFER_MID, SIGNAL_ON_ANSWER_MID, LAST_SIGNAL }; static guint obj_signals[LAST_SIGNAL] = { 0 }; static gboolean kms_sdp_mid_ext_add_offer_attributes (KmsISdpMediaExtension * ext, GstSDPMedia * offer, GError ** error) { gchar *mid; mid = (gchar *) gst_sdp_media_get_attribute_val (offer, MID_ATTR); if (mid != NULL) { GST_WARNING_OBJECT (ext, "Mid '%s' already added to the offer", mid); return TRUE; } g_signal_emit (G_OBJECT (ext), obj_signals[SIGNAL_ON_OFFER_MID], 0, &mid); gst_sdp_media_add_attribute (offer, MID_ATTR, mid); g_free (mid); return TRUE; } static gboolean kms_sdp_mid_ext_add_answer_attributes (KmsISdpMediaExtension * ext, const GstSDPMedia * offer, GstSDPMedia * answer, GError ** error) { const gchar *mid; gchar *str; gboolean ret = FALSE; mid = gst_sdp_media_get_attribute_val (answer, MID_ATTR); if (mid != NULL) { /* do not add more mid attributes */ GST_DEBUG_OBJECT (ext, "Mid has already set in answer"); return TRUE; } mid = gst_sdp_media_get_attribute_val (offer, MID_ATTR); if (mid == NULL) { GST_WARNING_OBJECT (ext, "Remote agent does not support groups"); return TRUE; } str = g_strdup (mid); g_signal_emit (G_OBJECT (ext), obj_signals[SIGNAL_ON_ANSWER_MID], 0, mid, &ret); g_free (str); if (!ret) { g_set_error_literal (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_UNEXPECTED_ERROR, "Media stream identifier error"); return FALSE; } gst_sdp_media_add_attribute (answer, MID_ATTR, mid); return TRUE; } static gboolean kms_sdp_mid_ext_can_insert_attribute (KmsISdpMediaExtension * ext, const GstSDPMedia * offer, const GstSDPAttribute * attr, GstSDPMedia * answer, SdpMessageContext * ctx) { GST_DEBUG_OBJECT (ext, "an insert %s:%s ?", attr->key, attr->value); return FALSE; } static void kms_sdp_mid_ext_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { KmsSdpMidExt *self = KMS_SDP_MID_EXT (object); switch (prop_id) { case PROP_MID: g_value_set_string (value, self->priv->mid); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void kms_sdp_mid_ext_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { KmsSdpMidExt *self = KMS_SDP_MID_EXT (object); switch (prop_id) { case PROP_MID: g_free (self->priv->mid); self->priv->mid = g_value_dup_string (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void kms_sdp_mid_ext_finalize (GObject * object) { KmsSdpMidExt *self = KMS_SDP_MID_EXT (object); GST_DEBUG_OBJECT (self, "finalize"); g_free (self->priv->mid); G_OBJECT_CLASS (parent_class)->finalize (object); } static void kms_sdp_mid_ext_class_init (KmsSdpMidExtClass * klass) { GObjectClass *gobject_class; gobject_class = G_OBJECT_CLASS (klass); gobject_class->get_property = kms_sdp_mid_ext_get_property; gobject_class->set_property = kms_sdp_mid_ext_set_property; gobject_class->finalize = kms_sdp_mid_ext_finalize; g_object_class_install_property (gobject_class, PROP_MID, g_param_spec_string ("mid", "Mid", "Media stream identification", NULL, G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS)); obj_signals[SIGNAL_ON_OFFER_MID] = g_signal_new ("on-offer-mid", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (KmsSdpMidExtClass, on_offer_mid), NULL, NULL, __kms_sdp_agent_marshal_STRING__VOID, G_TYPE_STRING, 0); obj_signals[SIGNAL_ON_ANSWER_MID] = g_signal_new ("on-answer-mid", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (KmsSdpMidExtClass, on_answer_mid), NULL, NULL, __kms_sdp_agent_marshal_BOOLEAN__STRING, G_TYPE_BOOLEAN, 1, G_TYPE_STRING); g_type_class_add_private (klass, sizeof (KmsSdpMidExtPrivate)); } static void kms_sdp_mid_ext_init (KmsSdpMidExt * self) { self->priv = KMS_SDP_MID_EXT_GET_PRIVATE (self); /* Nothing to do */ } static void kms_i_sdp_media_extension_init (KmsISdpMediaExtensionInterface * iface) { iface->add_offer_attributes = kms_sdp_mid_ext_add_offer_attributes; iface->add_answer_attributes = kms_sdp_mid_ext_add_answer_attributes; iface->can_insert_attribute = kms_sdp_mid_ext_can_insert_attribute; } KmsSdpMidExt * kms_sdp_mid_ext_new () { gpointer obj; obj = g_object_new (KMS_TYPE_SDP_MID_EXT, NULL); return KMS_SDP_MID_EXT (obj); }
bjxagu/kms-core
src/gst-plugins/commons/kmsbasertpsession.h
<reponame>bjxagu/kms-core /* * (C) Copyright 2015 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef __KMS_BASE_RTP_SESSION_H__ #define __KMS_BASE_RTP_SESSION_H__ #include <gst/gst.h> #include "kmssdpsession.h" #include "kmsirtpsessionmanager.h" #include "kmsirtpconnection.h" #include "kmsconnectionstate.h" G_BEGIN_DECLS typedef struct _KmsIRtpSessionManager KmsIRtpSessionManager; /* #defines don't like whitespacey bits */ #define KMS_TYPE_BASE_RTP_SESSION \ (kms_base_rtp_session_get_type()) #define KMS_BASE_RTP_SESSION(obj) \ (G_TYPE_CHECK_INSTANCE_CAST((obj),KMS_TYPE_BASE_RTP_SESSION,KmsBaseRtpSession)) #define KMS_BASE_RTP_SESSION_CLASS(klass) \ (G_TYPE_CHECK_CLASS_CAST((klass),KMS_TYPE_BASE_RTP_SESSION,KmsBaseRtpSessionClass)) #define KMS_IS_BASE_RTP_SESSION(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE((obj),KMS_TYPE_BASE_RTP_SESSION)) #define KMS_IS_BASE_RTP_SESSION_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE((klass),KMS_TYPE_BASE_RTP_SESSION)) #define KMS_BASE_RTP_SESSION_CAST(obj) ((KmsBaseRtpSession*)(obj)) typedef struct _KmsBaseRtpSession KmsBaseRtpSession; typedef struct _KmsBaseRtpSessionClass KmsBaseRtpSessionClass; typedef struct _KmsBaseRTPSessionStats KmsBaseRTPSessionStats; struct _KmsBaseRtpSession { KmsSdpSession parent; KmsIRtpSessionManager *manager; GHashTable *conns; KmsConnectionState conn_state; SdpMediaConfig *audio_neg_mconf; guint32 local_audio_ssrc; guint32 remote_audio_ssrc; SdpMediaConfig *video_neg_mconf; guint32 local_video_ssrc; guint32 remote_video_ssrc; gboolean stats_enabled; }; struct _KmsBaseRtpSessionClass { KmsSdpSessionClass parent_class; /* private */ /* virtual methods */ void (*post_constructor) (KmsBaseRtpSession * self, KmsBaseSdpEndpoint * ep, guint id, KmsIRtpSessionManager * manager); KmsIRtpConnection * (*create_connection) (KmsBaseRtpSession *self, SdpMediaConfig * mconf, const gchar *name, guint16 min_port, guint16 max_port); KmsIRtcpMuxConnection* (*create_rtcp_mux_connection) (KmsBaseRtpSession *self, const gchar *name, guint16 min_port, guint16 max_port); KmsIBundleConnection * (*create_bundle_connection) (KmsBaseRtpSession *self, const gchar *name, guint16 min_port, guint16 max_port); void (*connection_state_changed) (KmsBaseRtpSession * self, KmsConnectionState new_state); }; GType kms_base_rtp_session_get_type (void); KmsBaseRtpSession * kms_base_rtp_session_new (KmsBaseSdpEndpoint * ep, guint id, KmsIRtpSessionManager * manager); KmsIRtpConnection * kms_base_rtp_session_get_connection_by_name (KmsBaseRtpSession * self, const gchar * name); KmsIRtpConnection * kms_base_rtp_session_get_connection (KmsBaseRtpSession * self, SdpMediaConfig * mconf); KmsIRtpConnection * kms_base_rtp_session_create_connection (KmsBaseRtpSession * self, SdpMediaConfig * mconf, guint16 min_port, guint16 max_port); void kms_base_rtp_session_start_transport_send (KmsBaseRtpSession * self, gboolean offerer); void kms_base_rtp_session_enable_connections_stats (KmsBaseRtpSession * self); void kms_base_rtp_session_disable_connections_stats (KmsBaseRtpSession * self); G_END_DECLS #endif /* __KMS_BASE_RTP_SESSION_H__ */
bjxagu/kms-core
tests/check/element/agnosticbin.c
<filename>tests/check/element/agnosticbin.c /* * (C) Copyright 2013 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <gst/check/gstcheck.h> #include <gst/gst.h> #include <glib.h> #define AGNOSTIC_KEY "agnostic" G_DEFINE_QUARK (AGNOSTIC_KEY, agnostic_key); #define DECODER_KEY "decoder" G_DEFINE_QUARK (DECODER_KEY, decoder_key); #define FAKESINK_KEY "fakesink" G_DEFINE_QUARK (FAKESINK_KEY, fakesink_key); #define VALVE_KEY "valve" G_DEFINE_QUARK (VALVE_KEY, valve_key); #define COUNT_KEY "count" G_DEFINE_QUARK (COUNT_KEY, count_key); /* * By now we only enable one output, otherwise the test will probably fail * once the bug is solved this value should be incremented */ #define N_ITERS 200 typedef struct _ElementsData { GstElement *agnosticbin; GstElement *fakesink; } ElementsData; static GMainLoop *loop; static gboolean quit_main_loop_idle (gpointer data) { GMainLoop *loop = data; g_main_loop_quit (loop); return FALSE; } static void bus_msg (GstBus * bus, GstMessage * msg, gpointer pipe) { switch (GST_MESSAGE_TYPE (msg)) { case GST_MESSAGE_ERROR:{ gchar *error_file = g_strdup_printf ("error-%s", GST_OBJECT_NAME (pipe)); GST_ERROR ("Error: %" GST_PTR_FORMAT, msg); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipe), GST_DEBUG_GRAPH_SHOW_ALL, error_file); g_free (error_file); fail ("Error received on bus"); break; } case GST_MESSAGE_WARNING:{ gchar *warn_file = g_strdup_printf ("warning-%s", GST_OBJECT_NAME (pipe)); GST_WARNING ("Warning: %" GST_PTR_FORMAT, msg); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipe), GST_DEBUG_GRAPH_SHOW_ALL, warn_file); g_free (warn_file); break; } case GST_MESSAGE_EOS:{ quit_main_loop_idle (loop); break; } default: break; } } static void fakesink_hand_off (GstElement * fakesink, GstBuffer * buf, GstPad * pad, gpointer data) { static int count = 0; GMainLoop *loop = (GMainLoop *) data; if (count++ > 40) { g_object_set (G_OBJECT (fakesink), "signal-handoffs", FALSE, NULL); g_idle_add (quit_main_loop_idle, loop); } } static gboolean reconnect_elements (gpointer data) { ElementsData *elements = data; GstPad *pad = gst_element_get_request_pad (elements->agnosticbin, "src_%u"); gst_element_link_pads (elements->agnosticbin, GST_OBJECT_NAME (pad), elements->fakesink, NULL); g_object_unref (pad); return FALSE; } static void free_elements (gpointer data) { ElementsData *elements = data; g_object_unref (elements->agnosticbin); g_object_unref (elements->fakesink); g_slice_free (ElementsData, elements); } static void fakesink_hand_off_simple (GstElement * fakesink, GstBuffer * buf, GstPad * pad, gpointer data) { static int count = 0; GMainLoop *loop = (GMainLoop *) data; count++; if (count == 40) { GstPad *peer = gst_pad_get_peer (pad); ElementsData *elements = g_slice_new (ElementsData); elements->agnosticbin = gst_pad_get_parent_element (peer); elements->fakesink = g_object_ref (fakesink); gst_pad_unlink (peer, pad); g_object_unref (peer); g_idle_add_full (G_PRIORITY_DEFAULT, reconnect_elements, elements, free_elements); } else if (count > 100) { g_object_set (G_OBJECT (fakesink), "signal-handoffs", FALSE, NULL); g_idle_add (quit_main_loop_idle, loop); } } static gboolean link_again (gpointer data) { GstElement *decoder = (GstElement *) data; GstElement *agnostic = g_object_get_qdata (G_OBJECT (data), agnostic_key_quark ()); GstElement *fakesink = g_object_get_qdata (G_OBJECT (decoder), fakesink_key_quark ()); GST_DEBUG ("Linking again %" GST_PTR_FORMAT ", %" GST_PTR_FORMAT, agnostic, decoder); g_object_set (G_OBJECT (fakesink), "signal-handoffs", TRUE, NULL); gst_element_link (agnostic, decoder); return FALSE; } static gboolean idle_unlink (gpointer data) { GstPad *sink, *src; GstElement *decoder = (GstElement *) data; GstElement *agnostic = g_object_get_qdata (G_OBJECT (decoder), agnostic_key_quark ()); sink = gst_element_get_static_pad (decoder, "sink"); src = gst_pad_get_peer (sink); gst_pad_unlink (src, sink); gst_element_release_request_pad (agnostic, src); g_object_unref (src); g_object_unref (sink); g_timeout_add (200, link_again, decoder); return FALSE; } static void fakesink_hand_off2 (GstElement * fakesink, GstBuffer * buf, GstPad * pad, gpointer data) { static int count = 0; static int cycles = 0; GMainLoop *loop = (GMainLoop *) data; if (count++ > 10) { count = 0; if (cycles++ > 10) { g_object_set (G_OBJECT (fakesink), "signal-handoffs", FALSE, NULL); GST_DEBUG ("Quit loop"); g_idle_add (quit_main_loop_idle, loop); } else { GstElement *decoder = g_object_get_qdata (G_OBJECT (fakesink), decoder_key_quark ()); g_object_set (G_OBJECT (fakesink), "signal-handoffs", FALSE, NULL); mark_point (); g_idle_add (idle_unlink, decoder); } } } static gboolean timeout_check (gpointer pipeline) { if (GST_IS_BIN (pipeline)) { gchar *timeout_file = g_strdup_printf ("timeout-%s", GST_OBJECT_NAME (pipeline)); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline), GST_DEBUG_GRAPH_SHOW_ALL, timeout_file); g_free (timeout_file); } return FALSE; } static gpointer toggle_thread (gpointer data) { GstElement *pipeline = GST_ELEMENT (data); GstElement *valve = g_object_get_qdata (G_OBJECT (pipeline), valve_key_quark ()); GstPad *sink = gst_element_get_static_pad (valve, "sink"); gint i; g_usleep (800000); for (i = 0; i < 15; i++) { if (g_main_loop_is_running (loop)) { g_object_set (valve, "drop", i % 2, NULL); g_usleep (20000); } else { GST_DEBUG ("Main loop stopped"); break; } } g_usleep (100000); g_object_set (valve, "drop", FALSE, NULL); g_object_unref (sink); GST_DEBUG ("Toggle thread finished"); { GstElement *fakesink = gst_bin_get_by_name (GST_BIN (pipeline), "fakesink"); GST_DEBUG_OBJECT (fakesink, "Found"); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (fakesink_hand_off), loop); g_object_set (G_OBJECT (fakesink), "signal-handoffs", TRUE, NULL); g_object_unref (fakesink); } return NULL; } static gboolean link_source (gpointer data) { GstElement *pipeline = data; GstElement *agnosticbin = gst_bin_get_by_name (GST_BIN (pipeline), "agnosticbin"); GstElement *videosrc = gst_element_factory_make ("videotestsrc", NULL); g_object_set (G_OBJECT (videosrc), "is-live", TRUE, NULL); gst_bin_add_many (GST_BIN (pipeline), videosrc, NULL); gst_element_link (videosrc, agnosticbin); gst_element_sync_state_with_parent (videosrc); g_object_unref (agnosticbin); return FALSE; } static void type_found (GstElement * typefind, guint prob, GstCaps * caps, GstElement * pipeline) { GstElement *fakesink = gst_bin_get_by_name (GST_BIN (pipeline), "fakesink"); GstElement *agnosticbin = gst_element_factory_make ("agnosticbin", NULL); gst_bin_add (GST_BIN (pipeline), agnosticbin); gst_element_sync_state_with_parent (agnosticbin); gst_element_link (agnosticbin, fakesink); gst_element_link (typefind, agnosticbin); g_object_unref (fakesink); } static void change_input (gpointer pipeline) { GstBin *pipe = GST_BIN (pipeline); GstElement *agnosticbin; GstPad *peer, *sink; GstElement *agnosticbin2 = gst_bin_get_by_name (pipe, "agnosticbin_2"); GstElement *enc = gst_element_factory_make ("vp8enc", NULL); GstElement *fakesink = gst_bin_get_by_name (pipe, "fakesink"); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (fakesink_hand_off), loop); g_object_unref (fakesink); gst_bin_add (pipe, enc); gst_element_sync_state_with_parent (enc); sink = gst_element_get_static_pad (agnosticbin2, "sink"); peer = gst_pad_get_peer (sink); agnosticbin = gst_pad_get_parent_element (peer); gst_pad_unlink (peer, sink); GST_INFO ("Got peer: %" GST_PTR_FORMAT, peer); gst_element_release_request_pad (agnosticbin, peer); gst_element_link (enc, agnosticbin2); gst_element_link (agnosticbin, enc); g_object_unref (agnosticbin); g_object_unref (agnosticbin2); g_object_unref (sink); g_object_unref (peer); } static GstPadProbeReturn block_agnostic_sink (GstPad * pad, GstPadProbeInfo * info, gpointer data) { static gboolean configuring = FALSE; /* HACK: Ignore caps event and stream start event that causes negotiation * failures.This is a workaround that should be removed */ if (GST_PAD_PROBE_INFO_TYPE (info) & GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM) { GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info); if (GST_EVENT_TYPE (event) == GST_EVENT_STREAM_START || GST_EVENT_TYPE (event) == GST_EVENT_CAPS) { return GST_PAD_PROBE_PASS; } } /* HACK: Ignore query accept caps that causes negotiation errors. * This is a workaround that should be removed */ if (GST_PAD_PROBE_INFO_TYPE (info) & GST_PAD_PROBE_TYPE_QUERY_DOWNSTREAM) { GstQuery *query = GST_PAD_PROBE_INFO_QUERY (info); if (GST_QUERY_TYPE (query) == GST_QUERY_ACCEPT_CAPS) { return GST_PAD_PROBE_PASS; } } if (g_atomic_int_compare_and_exchange (&configuring, FALSE, TRUE)) { change_input (data); g_atomic_int_set (&configuring, FALSE); return GST_PAD_PROBE_REMOVE; } return GST_PAD_PROBE_PASS; } static gboolean change_input_cb (gpointer pipeline) { GstBin *pipe = GST_BIN (pipeline); GstPad *sink; GstElement *agnosticbin2 = gst_bin_get_by_name (pipe, "agnosticbin_2"); sink = gst_element_get_static_pad (agnosticbin2, "sink"); gst_pad_add_probe (sink, GST_PAD_PROBE_TYPE_BLOCK, block_agnostic_sink, pipeline, NULL); // HACK: Sending a dummy event to ensure the block probe is called gst_pad_send_event (sink, gst_event_new_custom (GST_EVENT_TYPE_DOWNSTREAM, gst_structure_new_from_string ("dummy"))); g_object_unref (agnosticbin2); g_object_unref (sink); return FALSE; } static gboolean check_pipeline_termination (gpointer data) { GstElement *pipeline = GST_ELEMENT (data); int *count = g_object_get_qdata (G_OBJECT (pipeline), count_key_quark ()); if (count != NULL && g_atomic_int_dec_and_test (count)) { GST_DEBUG ("Terminating main loop"); quit_main_loop_idle (loop); } return FALSE; } static GstFlowReturn appsink_handle_many (GstElement * appsink, gpointer data) { int *count = g_object_get_qdata (G_OBJECT (appsink), count_key_quark ()); GstSample *sample; if (count == NULL) { count = g_malloc0 (sizeof (int)); g_object_set_qdata_full (G_OBJECT (appsink), count_key_quark (), count, g_free); } g_signal_emit_by_name (appsink, "pull-sample", &sample); gst_sample_unref (sample); if (g_atomic_int_add (count, 1) == 40) { GST_DEBUG_OBJECT (appsink, "Terminatig"); g_idle_add (check_pipeline_termination, GST_OBJECT_PARENT (appsink)); } return GST_FLOW_OK; } static gboolean connect_output (gpointer pipeline) { GstElement *agnosticbin = gst_bin_get_by_name (GST_BIN (pipeline), "agnosticbin"); GstElement *appsink = gst_element_factory_make ("appsink", NULL); GstCaps *caps = gst_caps_from_string ("audio/x-vorbis"); g_object_set (G_OBJECT (appsink), "emit-signals", TRUE, "caps", caps, "sync", TRUE, "async", FALSE, NULL); gst_caps_unref (caps); g_signal_connect (G_OBJECT (appsink), "new-sample", G_CALLBACK (appsink_handle_many), NULL); gst_bin_add (GST_BIN (pipeline), appsink); gst_element_sync_state_with_parent (appsink); if (!gst_element_link (agnosticbin, appsink)) { GST_ERROR ("Error linking elements"); } g_object_unref (agnosticbin); return FALSE; } GST_START_TEST (input_reconfiguration) { GstElement *pipeline = gst_pipeline_new (__FUNCTION__); GstElement *videosrc = gst_element_factory_make ("videotestsrc", NULL); GstElement *agnosticbin = gst_element_factory_make ("agnosticbin", "agnosticbin_1"); GstElement *agnosticbin2 = gst_element_factory_make ("agnosticbin", "agnosticbin_2"); GstElement *fakesink = gst_element_factory_make ("fakesink", "fakesink"); GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); loop = g_main_loop_new (NULL, TRUE); g_object_set (G_OBJECT (videosrc), "is-live", TRUE, NULL); g_object_set (G_OBJECT (fakesink), "sync", TRUE, "signal-handoffs", TRUE, "async", FALSE, NULL); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); gst_bin_add_many (GST_BIN (pipeline), videosrc, agnosticbin, agnosticbin2, fakesink, NULL); gst_element_link_many (videosrc, agnosticbin, agnosticbin2, fakesink, NULL); gst_element_set_state (pipeline, GST_STATE_PLAYING); g_timeout_add_seconds (1, change_input_cb, pipeline); g_timeout_add_seconds (6, timeout_check, pipeline); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (pipeline); g_object_unref (bus); g_main_loop_unref (loop); } GST_END_TEST; static gboolean change_input_caps_cb (gpointer pipeline) { GstBin *pipe = GST_BIN (pipeline); GstElement *fakesink = gst_bin_get_by_name (pipe, "fakesink"); GstCaps *caps = gst_caps_from_string ("video/x-raw,width=321,height=241"); GstElement *capsfilter = gst_bin_get_by_name (pipe, "input_caps"); g_object_set (capsfilter, "caps", caps, NULL); gst_caps_unref (caps); g_object_unref (capsfilter); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (fakesink_hand_off), loop); g_object_unref (fakesink); return FALSE; } GST_START_TEST (input_caps_reconfiguration) { GstElement *pipeline = gst_parse_launch ("videotestsrc is-live=true ! capsfilter name=input_caps caps=video/x-raw,width=800,height=600 ! agnosticbin ! video/x-vp8 ! agnosticbin ! video/x-raw ! fakesink sync=false async=false signal-handoffs=true name=fakesink", NULL); GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); loop = g_main_loop_new (NULL, TRUE); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); gst_element_set_state (pipeline, GST_STATE_PLAYING); g_timeout_add_seconds (1, change_input_caps_cb, pipeline); g_timeout_add_seconds (6, timeout_check, pipeline); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (pipeline); g_object_unref (bus); g_main_loop_unref (loop); } GST_END_TEST GST_START_TEST (add_later) { GMainLoop *loop = g_main_loop_new (NULL, TRUE); GstElement *pipeline = gst_pipeline_new (__FUNCTION__); GstElement *videosrc = gst_element_factory_make ("videotestsrc", NULL); GstElement *typefind = gst_element_factory_make ("typefind", NULL); GstElement *fakesink = gst_element_factory_make ("fakesink", "fakesink"); GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); g_object_set (G_OBJECT (fakesink), "sync", TRUE, "signal-handoffs", TRUE, "async", FALSE, NULL); g_object_set (G_OBJECT (videosrc), "is-live", TRUE, NULL); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (fakesink_hand_off), loop); g_signal_connect (G_OBJECT (typefind), "have-type", G_CALLBACK (type_found), pipeline); gst_bin_add_many (GST_BIN (pipeline), videosrc, typefind, fakesink, NULL); gst_element_link (videosrc, typefind); gst_element_set_state (pipeline, GST_STATE_PLAYING); g_timeout_add_seconds (10, timeout_check, pipeline); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (pipeline); g_object_unref (bus); g_main_loop_unref (loop); } GST_END_TEST GST_START_TEST (delay_stream) { GMainLoop *loop = g_main_loop_new (NULL, TRUE); GstElement *pipeline = gst_pipeline_new (__FUNCTION__); GstElement *agnosticbin = gst_element_factory_make ("agnosticbin", "agnosticbin"); GstElement *fakesink = gst_element_factory_make ("fakesink", NULL); GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); g_object_set (G_OBJECT (fakesink), "async", FALSE, "sync", TRUE, "signal-handoffs", TRUE, NULL); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (fakesink_hand_off), loop); gst_bin_add_many (GST_BIN (pipeline), agnosticbin, fakesink, NULL); gst_element_link (agnosticbin, fakesink); gst_element_set_state (pipeline, GST_STATE_PLAYING); g_timeout_add_seconds (1, link_source, pipeline); g_timeout_add_seconds (11, timeout_check, pipeline); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (pipeline); g_object_unref (bus); g_main_loop_unref (loop); } GST_END_TEST GST_START_TEST (valve_test) { GstElement *pipeline = gst_pipeline_new (__FUNCTION__); GstElement *videotestsrc = gst_element_factory_make ("videotestsrc", NULL); GstElement *fakesink = gst_element_factory_make ("fakesink", NULL); GstElement *agnosticbin = gst_element_factory_make ("agnosticbin", NULL); GstElement *valve = gst_element_factory_make ("valve", NULL); GstElement *decoder = gst_element_factory_make ("vp8dec", NULL); GstElement *fakesink2 = gst_element_factory_make ("fakesink", "fakesink"); gboolean ret; GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); GThread *thread; g_object_set_qdata (G_OBJECT (pipeline), valve_key_quark (), valve); loop = g_main_loop_new (NULL, TRUE); g_object_set (G_OBJECT (videotestsrc), "is-live", TRUE, NULL); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); g_object_set_qdata (G_OBJECT (fakesink2), decoder_key_quark (), decoder); g_object_set_qdata (G_OBJECT (decoder), agnostic_key_quark (), agnosticbin); g_object_set (G_OBJECT (fakesink2), "sync", TRUE, "async", FALSE, NULL); g_object_set (G_OBJECT (fakesink), "sync", TRUE, "async", FALSE, NULL); mark_point (); gst_bin_add_many (GST_BIN (pipeline), videotestsrc, agnosticbin, fakesink, valve, decoder, fakesink2, NULL); mark_point (); ret = gst_element_link_many (videotestsrc, agnosticbin, fakesink, NULL); fail_unless (ret); mark_point (); ret = gst_element_link_many (agnosticbin, valve, decoder, fakesink2, NULL); fail_unless (ret); mark_point (); gst_element_set_state (pipeline, GST_STATE_PLAYING); thread = g_thread_new ("toggle", toggle_thread, pipeline); g_thread_unref (thread); g_timeout_add_seconds (10, timeout_check, pipeline); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (pipeline); g_object_unref (bus); g_main_loop_unref (loop); } GST_END_TEST GST_START_TEST (reconnect_test) { GMainLoop *loop = g_main_loop_new (NULL, TRUE); GstElement *pipeline = gst_pipeline_new (__FUNCTION__); GstElement *videotestsrc = gst_element_factory_make ("videotestsrc", NULL); GstElement *fakesink = gst_element_factory_make ("fakesink", NULL); GstElement *agnosticbin = gst_element_factory_make ("agnosticbin", NULL); GstElement *decoder = gst_element_factory_make ("vp8dec", NULL); GstElement *fakesink2 = gst_element_factory_make ("fakesink", NULL); gboolean ret; GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); g_object_set (G_OBJECT (videotestsrc), "is-live", TRUE, NULL); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); g_object_set (G_OBJECT (fakesink2), "sync", TRUE, "signal-handoffs", TRUE, "async", FALSE, NULL); g_signal_connect (G_OBJECT (fakesink2), "handoff", G_CALLBACK (fakesink_hand_off2), loop); g_object_set_qdata (G_OBJECT (fakesink2), decoder_key_quark (), decoder); g_object_set_qdata (G_OBJECT (decoder), agnostic_key_quark (), agnosticbin); g_object_set_qdata (G_OBJECT (decoder), fakesink_key_quark (), fakesink2); mark_point (); gst_bin_add_many (GST_BIN (pipeline), videotestsrc, agnosticbin, fakesink, decoder, fakesink2, NULL); mark_point (); ret = gst_element_link_many (videotestsrc, agnosticbin, fakesink, NULL); fail_unless (ret); mark_point (); ret = gst_element_link_many (agnosticbin, decoder, fakesink2, NULL); fail_unless (ret); mark_point (); gst_element_set_state (pipeline, GST_STATE_PLAYING); mark_point (); g_timeout_add_seconds (10, timeout_check, pipeline); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (bus); g_object_unref (pipeline); g_main_loop_unref (loop); } GST_END_TEST GST_START_TEST (static_link) { GMainLoop *loop = g_main_loop_new (NULL, TRUE); GstElement *pipeline = gst_pipeline_new (__FUNCTION__); GstElement *videotestsrc = gst_element_factory_make ("videotestsrc", NULL); GstElement *fakesink = gst_element_factory_make ("fakesink", NULL); GstElement *agnosticbin = gst_element_factory_make ("agnosticbin", NULL); GstElement *decoder = gst_element_factory_make ("vp8dec", NULL); GstElement *fakesink2 = gst_element_factory_make ("fakesink", NULL); gboolean ret; GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); g_object_set (G_OBJECT (videotestsrc), "is-live", TRUE, NULL); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); g_object_set (G_OBJECT (fakesink2), "sync", TRUE, "signal-handoffs", TRUE, "async", FALSE, NULL); g_signal_connect (G_OBJECT (fakesink2), "handoff", G_CALLBACK (fakesink_hand_off), loop); mark_point (); gst_bin_add_many (GST_BIN (pipeline), videotestsrc, agnosticbin, fakesink, decoder, fakesink2, NULL); mark_point (); ret = gst_element_link_many (videotestsrc, agnosticbin, fakesink, NULL); fail_unless (ret); mark_point (); ret = gst_element_link_many (agnosticbin, decoder, fakesink2, NULL); fail_unless (ret); mark_point (); gst_element_set_state (pipeline, GST_STATE_PLAYING); mark_point (); g_timeout_add_seconds (10, timeout_check, pipeline); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (bus); g_object_unref (pipeline); g_main_loop_unref (loop); } GST_END_TEST GST_START_TEST (encoded_input_n_encoded_output) { GstElement *pipeline = gst_pipeline_new (__FUNCTION__); GstElement *audiotestsrc = gst_element_factory_make ("audiotestsrc", NULL); GstElement *encoder = gst_element_factory_make ("alawenc", NULL); GstElement *agnosticbin = gst_element_factory_make ("agnosticbin", "agnosticbin"); gboolean ret; int *count, i; GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); loop = g_main_loop_new (NULL, TRUE); g_object_set (G_OBJECT (audiotestsrc), "is-live", TRUE, NULL); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); mark_point (); gst_bin_add_many (GST_BIN (pipeline), audiotestsrc, encoder, agnosticbin, NULL); mark_point (); ret = gst_element_link_many (audiotestsrc, encoder, agnosticbin, NULL); fail_unless (ret); mark_point (); gst_element_set_state (pipeline, GST_STATE_PLAYING); mark_point (); count = g_malloc0 (sizeof (int)); *count = N_ITERS; g_object_set_qdata_full (G_OBJECT (pipeline), count_key_quark (), count, g_free); GST_INFO ("Connecting %d outputs", N_ITERS); g_timeout_add_seconds (6, timeout_check, pipeline); for (i = 0; i < N_ITERS; i++) { g_timeout_add (700, connect_output, pipeline); } mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (bus); g_object_unref (pipeline); g_main_loop_unref (loop); } GST_END_TEST GST_START_TEST (encoded_input_link) { GMainLoop *loop = g_main_loop_new (NULL, TRUE); GstElement *pipeline = gst_pipeline_new (__FUNCTION__); GstElement *videotestsrc = gst_element_factory_make ("videotestsrc", NULL); GstElement *encoder = gst_element_factory_make ("vp8enc", NULL); GstElement *fakesink = gst_element_factory_make ("fakesink", NULL); GstElement *filter = gst_element_factory_make ("capsfilter", NULL); GstElement *agnosticbin = gst_element_factory_make ("agnosticbin", NULL); GstCaps *caps; gboolean ret; GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); g_object_set (G_OBJECT (videotestsrc), "is-live", TRUE, NULL); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); g_object_set (G_OBJECT (fakesink), "sync", TRUE, "signal-handoffs", TRUE, "async", FALSE, NULL); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (fakesink_hand_off), loop); caps = gst_caps_from_string ("video/x-raw"); g_object_set (G_OBJECT (filter), "caps", caps, NULL); gst_caps_unref (caps); mark_point (); gst_bin_add_many (GST_BIN (pipeline), videotestsrc, encoder, agnosticbin, filter, fakesink, NULL); mark_point (); ret = gst_element_link_many (videotestsrc, encoder, agnosticbin, filter, fakesink, NULL); fail_unless (ret); mark_point (); gst_element_set_state (pipeline, GST_STATE_PLAYING); mark_point (); g_timeout_add_seconds (10, timeout_check, pipeline); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (bus); g_object_unref (pipeline); g_main_loop_unref (loop); } GST_END_TEST GST_START_TEST (simple_link) { GMainLoop *loop = g_main_loop_new (NULL, TRUE); GstElement *pipeline = gst_pipeline_new (__FUNCTION__); GstElement *videotestsrc = gst_element_factory_make ("videotestsrc", NULL); GstElement *fakesink = gst_element_factory_make ("fakesink", NULL); GstElement *agnosticbin = gst_element_factory_make ("agnosticbin", NULL); gboolean ret; GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); g_object_set (G_OBJECT (videotestsrc), "is-live", TRUE, NULL); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); g_object_set (G_OBJECT (fakesink), "sync", TRUE, "signal-handoffs", TRUE, "async", FALSE, NULL); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (fakesink_hand_off_simple), loop); mark_point (); gst_bin_add_many (GST_BIN (pipeline), videotestsrc, agnosticbin, fakesink, NULL); mark_point (); ret = gst_element_link_many (videotestsrc, agnosticbin, fakesink, NULL); fail_unless (ret); mark_point (); gst_element_set_state (pipeline, GST_STATE_PLAYING); mark_point (); g_timeout_add_seconds (10, timeout_check, pipeline); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (bus); g_object_unref (pipeline); g_main_loop_unref (loop); } GST_END_TEST GST_START_TEST (create_test) { GstElement *agnosticbin = gst_element_factory_make ("agnosticbin", NULL); GstPad *pad; pad = gst_element_get_request_pad (agnosticbin, "src_%u"); GST_DEBUG_OBJECT (pad, "Pad created"); gst_element_release_request_pad (agnosticbin, pad); gst_object_unref (pad); g_object_unref (agnosticbin); } GST_END_TEST GST_START_TEST (h264_encoding_odd_dimension) { GstElement *pipeline = gst_parse_launch ("videotestsrc is-live=true num-buffers=30 ! video/x-raw, format=(string)I420, width=(int)319, height=(int)239, pixel-aspect-ratio=(fraction)1/1, interlace-mode=(string)progressive, colorimetry=(string)bt601, framerate=(fraction)14/1 ! agnosticbin ! video/x-h264 ! fakesink async=true", NULL); GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); loop = g_main_loop_new (NULL, TRUE); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); gst_element_set_state (pipeline, GST_STATE_PLAYING); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (bus); g_object_unref (pipeline); g_main_loop_unref (loop); } GST_END_TEST; static GstPadProbeReturn event_probe (GstPad * pad, GstPadProbeInfo * info, gpointer data) { GstEvent *event = gst_pad_probe_info_get_event (info); if (GST_EVENT_TYPE (event) == GST_EVENT_CUSTOM_UPSTREAM) { const GstStructure *st = gst_event_get_structure (event); gboolean key_frame_requested = g_strcmp0 (gst_structure_get_name (st), "GstForceKeyUnit") == 0; fail_if (key_frame_requested); } return GST_PAD_PROBE_OK; } static void change_dimension (gpointer pipeline) { GstCaps *caps = gst_caps_from_string ("video/x-raw,format=(string)I420,width=(int)640,height=(int)480"); GstElement *capsfilter = gst_bin_get_by_name (GST_BIN (pipeline), "capsfilter"); GstElement *vp8caps; GstPad *sink; vp8caps = gst_bin_get_by_name (GST_BIN (pipeline), "vp8caps"); if (vp8caps) { sink = gst_element_get_static_pad (vp8caps, "sink"); gst_pad_add_probe (sink, GST_PAD_PROBE_TYPE_EVENT_BOTH, event_probe, NULL, NULL); g_object_unref (sink); g_object_unref (vp8caps); } g_object_set (capsfilter, "caps", caps, NULL); g_object_unref (capsfilter); gst_caps_unref (caps); } static GstPadProbeReturn sink_probe (GstPad * pad, GstPadProbeInfo * info, gpointer pipeline) { GstEvent *event = gst_pad_probe_info_get_event (info); static gboolean first = TRUE; if (GST_EVENT_TYPE (event) == GST_EVENT_CAPS) { if (first) { first = FALSE; } else { g_idle_add (quit_main_loop_idle, loop); } } return GST_PAD_PROBE_OK; } static void start_on_handoff (GstElement * fakesink, GstBuffer * buf, GstPad * pad, gpointer data) { static guint count = 0; if (count > 20) { g_object_set (fakesink, "signal-handoffs", FALSE, NULL); change_dimension (GST_ELEMENT_PARENT (fakesink)); } count++; } GST_START_TEST (video_dimension_change) { GstElement *fakesink; GstPad *sink; GstElement *pipeline = gst_parse_launch ("videotestsrc is-live=true ! capsfilter name=capsfilter caps=video/x-raw,format=(string)I420,width=(int)320,height=(int)240 ! agnosticbin ! capsfilter name=vp8caps caps=video/x-vp8 ! agnosticbin ! fakesink async=true sync=true name=sink signal-handoffs=true", NULL); GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); loop = g_main_loop_new (NULL, TRUE); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); fakesink = gst_bin_get_by_name (GST_BIN (pipeline), "sink"); sink = gst_element_get_static_pad (fakesink, "sink"); gst_pad_add_probe (sink, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, sink_probe, pipeline, NULL); g_object_unref (sink); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (start_on_handoff), loop); g_object_unref (fakesink); gst_element_set_state (pipeline, GST_STATE_PLAYING); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (bus); g_object_unref (pipeline); g_main_loop_unref (loop); } GST_END_TEST; GST_START_TEST (video_dimension_change_force_output) { GstElement *fakesink; GstPad *sink; GstElement *pipeline = gst_parse_launch ("videotestsrc is-live=true ! capsfilter name=capsfilter caps=video/x-raw,format=(string)I420,width=(int)320,height=(int)240 ! agnosticbin ! video/x-vp8 ! agnosticbin ! video/x-vp8,width=(int)320,height=(int)240 ! fakesink async=true sync=true name=sink signal-handoffs=true", NULL); GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); loop = g_main_loop_new (NULL, TRUE); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); fakesink = gst_bin_get_by_name (GST_BIN (pipeline), "sink"); sink = gst_element_get_static_pad (fakesink, "sink"); gst_pad_add_probe (sink, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, sink_probe, pipeline, NULL); g_object_unref (sink); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (start_on_handoff), loop); g_object_unref (fakesink); gst_element_set_state (pipeline, GST_STATE_PLAYING); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (bus); g_object_unref (pipeline); g_main_loop_unref (loop); } GST_END_TEST; GST_START_TEST (test_raw_to_rtp) { GstElement *fakesink; GstElement *pipeline = gst_parse_launch ("videotestsrc is-live=true ! agnosticbin ! application/x-rtp,media=(string)video,encoding-name=(string)VP8,clock-rate=(int)90000 ! fakesink async=true sync=true name=sink signal-handoffs=true", NULL); GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); loop = g_main_loop_new (NULL, TRUE); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); fakesink = gst_bin_get_by_name (GST_BIN (pipeline), "sink"); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (fakesink_hand_off), loop); g_object_unref (fakesink); gst_element_set_state (pipeline, GST_STATE_PLAYING); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (bus); g_object_unref (pipeline); g_main_loop_unref (loop); } GST_END_TEST; GST_START_TEST (test_codec_to_rtp) { GstElement *fakesink; GstElement *pipeline = gst_parse_launch ("videotestsrc is-live=true ! agnosticbin ! video/x-vp8 ! agnosticbin ! application/x-rtp,media=(string)video,encoding-name=(string)VP8,clock-rate=(int)90000 ! fakesink async=true sync=true name=sink signal-handoffs=true", NULL); GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); loop = g_main_loop_new (NULL, TRUE); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); fakesink = gst_bin_get_by_name (GST_BIN (pipeline), "sink"); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (fakesink_hand_off), loop); g_object_unref (fakesink); gst_element_set_state (pipeline, GST_STATE_PLAYING); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (bus); g_object_unref (pipeline); g_main_loop_unref (loop); } GST_END_TEST; static void check_properties (GstElement * encoder, const GstStructure * config) { guint n_props = 0, i; GParamSpec **props; props = g_object_class_list_properties (G_OBJECT_GET_CLASS (encoder), &n_props); for (i = 0; i < n_props; i++) { const gchar *name = g_param_spec_get_name (props[i]); if (gst_structure_has_field (config, name)) { GValue final_value = { 0, }; gchar *st_value; const GValue *val; gchar *serialized; val = gst_structure_get_value (config, name); st_value = gst_value_serialize (val); if (G_TYPE_IS_ENUM (props[i]->value_type) || G_TYPE_IS_FLAGS (props[i]->value_type)) { GValue second_serialized = { 0, }; g_value_init (&second_serialized, props[i]->value_type); gst_value_deserialize (&second_serialized, st_value); g_free (st_value); st_value = gst_value_serialize (&second_serialized); g_value_reset (&second_serialized); GST_TRACE ("Value type is %s, serialized again to: %s", G_TYPE_IS_ENUM (props[i]->value_type) ? "enum" : "flags", st_value); } GST_INFO ("Processing property: %s -> %s", name, st_value); g_value_init (&final_value, props[i]->value_type); g_object_get_property (G_OBJECT (encoder), name, &final_value); serialized = gst_value_serialize (&final_value); fail_unless (serialized); GST_INFO ("Got value from object: %s", serialized); fail_if (g_strcmp0 (st_value, serialized)); g_free (serialized); g_free (st_value); g_value_reset (&final_value); } } g_free (props); } static gboolean check_encoder (GQuark field_id, const GValue * value, gpointer obj) { if (G_VALUE_HOLDS (value, GST_TYPE_STRUCTURE)) { if (g_str_has_prefix (GST_OBJECT_NAME (obj), g_quark_to_string (field_id))) { GST_DEBUG ("%" GST_PTR_FORMAT " has matching name", obj); check_properties (obj, GST_STRUCTURE (g_value_get_boxed (value))); return FALSE; } } return TRUE; } static void check_element_properties (const GValue * item, gpointer codec_config) { GstElement *obj = g_value_get_object (item); if (GST_IS_BIN (obj)) { GstIterator *it = gst_bin_iterate_elements (GST_BIN (obj)); gst_iterator_foreach (it, check_element_properties, codec_config); gst_iterator_free (it); } else if (GST_IS_ELEMENT (obj)) { gst_structure_foreach (GST_STRUCTURE (codec_config), check_encoder, obj); } } static void test_codec_config (const gchar * pipeline_str, const gchar * config_str, const gchar * codec_name, const gchar * agnostic_name) { GstElement *fakesink, *agnostic; GstStructure *codec_configs, *vp8config; GstElement *pipeline = gst_parse_launch (pipeline_str, NULL); GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); GstIterator *it; loop = g_main_loop_new (NULL, TRUE); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); agnostic = gst_bin_get_by_name (GST_BIN (pipeline), agnostic_name); fail_unless (agnostic); vp8config = gst_structure_new_from_string (config_str); codec_configs = gst_structure_new ("codec-config", codec_name, GST_TYPE_STRUCTURE, vp8config, NULL); gst_structure_free (vp8config); g_object_set (agnostic, "codec-config", codec_configs, NULL); fakesink = gst_bin_get_by_name (GST_BIN (pipeline), "sink"); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (fakesink_hand_off), loop); g_object_unref (fakesink); gst_element_set_state (pipeline, GST_STATE_PLAYING); mark_point (); g_main_loop_run (loop); mark_point (); it = gst_bin_iterate_elements (GST_BIN (agnostic)); gst_iterator_foreach (it, check_element_properties, codec_configs); gst_iterator_free (it); g_object_unref (agnostic); gst_structure_free (codec_configs); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (bus); g_object_unref (pipeline); g_main_loop_unref (loop); } GST_START_TEST (test_codec_config_vp8) { const gchar *pipeline_str = "videotestsrc is-live=true ! agnosticbin name=ag ! capsfilter caps=video/x-vp8 ! fakesink async=true sync=true name=sink signal-handoffs=true"; const gchar *config_str = "vp8,deadline=(string)10,threads=(string)1,cpu-used=16,keyframe-mode=auto"; const gchar *codec_name = "vp8"; const gchar *agnostic_name = "ag"; test_codec_config (pipeline_str, config_str, codec_name, agnostic_name); } GST_END_TEST; GST_START_TEST (test_codec_config_x264) { const gchar *pipeline_str = "videotestsrc is-live=true ! agnosticbin name=ag ! capsfilter caps=video/x-h264 ! fakesink async=true sync=true name=sink signal-handoffs=true"; const gchar *config_str = "x264,pass=qual,quantizer=30,speed-preset=faster,tune=zerolatency+stillimage"; const gchar *codec_name = "x264"; const gchar *agnostic_name = "ag"; test_codec_config (pipeline_str, config_str, codec_name, agnostic_name); } GST_END_TEST; GST_START_TEST (test_codec_config_openh264) { const gchar *pipeline_str = "videotestsrc is-live=true ! agnosticbin name=ag ! capsfilter caps=video/x-h264 ! fakesink async=true sync=true name=sink signal-handoffs=true"; const gchar *config_str = "openh264,deblocking=off,complexity=low,gop-size=60"; const gchar *codec_name = "openh264"; const gchar *agnostic_name = "ag"; test_codec_config (pipeline_str, config_str, codec_name, agnostic_name); } GST_END_TEST; /* * End of test cases */ static Suite * agnostic2_suite (void) { Suite *s = suite_create ("agnosticbin"); TCase *tc_chain = tcase_create ("element"); suite_add_tcase (s, tc_chain); tcase_add_test (tc_chain, create_test); tcase_add_test (tc_chain, simple_link); tcase_add_test (tc_chain, encoded_input_link); tcase_add_test (tc_chain, static_link); tcase_add_test (tc_chain, reconnect_test); if (FALSE) { // FIXME: Disabled until fixed, there is a race condition in tests // more accusated when running with valgrind tcase_add_test (tc_chain, valve_test); } tcase_add_test (tc_chain, delay_stream); tcase_add_test (tc_chain, add_later); tcase_add_test (tc_chain, input_reconfiguration); tcase_add_test (tc_chain, input_caps_reconfiguration); tcase_add_test (tc_chain, encoded_input_n_encoded_output); tcase_add_test (tc_chain, h264_encoding_odd_dimension); tcase_add_test (tc_chain, video_dimension_change); tcase_add_test (tc_chain, video_dimension_change_force_output); tcase_add_test (tc_chain, test_codec_config_vp8); tcase_add_test (tc_chain, test_codec_config_x264); tcase_add_test (tc_chain, test_codec_config_openh264); tcase_add_test (tc_chain, test_raw_to_rtp); tcase_add_test (tc_chain, test_codec_to_rtp); return s; } GST_CHECK_MAIN (agnostic2);
bjxagu/kms-core
src/gst-plugins/kmsagnosticbin3.c
/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include "kmsagnosticbin3.h" #include "kmsagnosticcaps.h" #include "kms-core-marshal.h" #include "kmsutils.h" #define PLUGIN_NAME "agnosticbin3" #define KMS_AGNOSTICBIN3_SRC_PAD_DATA "kms-agnosticbin3-src-pad-data" G_DEFINE_QUARK (KMS_AGNOSTICBIN3_SRC_PAD_DATA, kms_agnosticbin3_src_pad_data); #define GST_CAT_DEFAULT kms_agnostic_bin3_debug GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define kms_agnostic_bin3_parent_class parent_class G_DEFINE_TYPE (KmsAgnosticBin3, kms_agnostic_bin3, GST_TYPE_BIN); #define KMS_AGNOSTIC_BIN3_GET_PRIVATE(obj) ( \ G_TYPE_INSTANCE_GET_PRIVATE ( \ (obj), \ KMS_TYPE_AGNOSTIC_BIN3, \ KmsAgnosticBin3Private \ ) \ ) struct _KmsAgnosticBin3Private { GRecMutex mutex; GSList *agnosticbins; GHashTable *sinkcaps; guint src_pad_count; guint sink_pad_count; guint last; }; #define KMS_AGNOSTIC_BIN3_LOCK(obj) ( \ g_rec_mutex_lock (&KMS_AGNOSTIC_BIN3 (obj)->priv->mutex) \ ) #define KMS_AGNOSTIC_BIN3_UNLOCK(obj) ( \ g_rec_mutex_unlock (&KMS_AGNOSTIC_BIN3 (obj)->priv->mutex) \ ) typedef enum { KMS_SRC_PAD_STATE_UNCONFIGURED, KMS_SRC_PAD_STATE_CONFIGURING, KMS_SRC_PAD_STATE_CONFIGURED, KMS_SRC_PAD_STATE_WAITING, KMS_SRC_PAD_STATE_LINKED } KmsSrcPadState; typedef struct _KmsSrcPadData { GMutex mutex; KmsSrcPadState state; GstCaps *caps; } KmsSrcPadData; /* Object signals */ enum { SIGNAL_CAPS, LAST_SIGNAL }; static guint agnosticbin3_signals[LAST_SIGNAL] = { 0 }; #define AGNOSTICBIN3_SINK_PAD_PREFIX "sink_" #define AGNOSTICBIN3_SRC_PAD_PREFIX "src_" #define AGNOSTICBIN3_SINK_PAD AGNOSTICBIN3_SINK_PAD_PREFIX "%u" #define AGNOSTICBIN3_SRC_PAD AGNOSTICBIN3_SRC_PAD_PREFIX "%u" /* the capabilities of the inputs and outputs. */ static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE (AGNOSTICBIN3_SINK_PAD, GST_PAD_SINK, GST_PAD_REQUEST, GST_STATIC_CAPS (KMS_AGNOSTIC_CAPS_CAPS) ); static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE (AGNOSTICBIN3_SRC_PAD, GST_PAD_SRC, GST_PAD_REQUEST, GST_STATIC_CAPS (KMS_AGNOSTIC_CAPS_CAPS) ); static gboolean set_transcoder_src_target_pad (GstGhostPad *, GstElement *); static GstElement *kms_agnosticbin3_get_element_for_transcoding (KmsAgnosticBin3 *); static KmsSrcPadData * create_src_pad_data () { KmsSrcPadData *data; data = g_slice_new0 (KmsSrcPadData); g_mutex_init (&data->mutex); data->state = KMS_SRC_PAD_STATE_UNCONFIGURED; return data; } static void destroy_src_pad_data (KmsSrcPadData * data) { if (data->caps != NULL) { gst_caps_unref (data->caps); } g_mutex_clear (&data->mutex); g_slice_free (KmsSrcPadData, data); } static const gchar * pad_state2string (KmsSrcPadState state) { switch (state) { case KMS_SRC_PAD_STATE_UNCONFIGURED: return "UNCONFIGURED"; case KMS_SRC_PAD_STATE_CONFIGURING: return "CONFIGURING"; case KMS_SRC_PAD_STATE_CONFIGURED: return "CONFIGURED"; case KMS_SRC_PAD_STATE_WAITING: return "WAITING"; case KMS_SRC_PAD_STATE_LINKED: return "LINKED"; default: return NULL; } } static void kms_agnostic_bin3_append_pending_src_pad (KmsAgnosticBin3 * self, GstPad * pad) { if (GST_STATE (self) >= GST_STATE_PAUSED || GST_STATE_PENDING (self) >= GST_STATE_PAUSED || GST_STATE_TARGET (self) >= GST_STATE_PAUSED) { gst_pad_set_active (pad, TRUE); } gst_element_add_pad (GST_ELEMENT (self), pad); } static GstElement * get_transcoder_connected_to_sinkpad (GstPad * pad) { GstElement *transcoder; GstProxyPad *proxypad; GstPad *sinkpad; proxypad = gst_proxy_pad_get_internal (GST_PROXY_PAD (pad)); sinkpad = gst_pad_get_peer (GST_PAD (proxypad)); transcoder = gst_pad_get_parent_element (sinkpad); g_object_unref (proxypad); g_object_unref (sinkpad); return transcoder; } static void connect_srcpad_to_encoder (GstPad * srcpad, GstPad * sinkpad) { GstCaps *current_caps = NULL, *caps = NULL; GstElement *transcoder; KmsAgnosticBin3 *self; KmsSrcPadData *data; GstPad *target; gboolean transcode; data = g_object_get_qdata (G_OBJECT (srcpad), kms_agnosticbin3_src_pad_data_quark ()); if (data == NULL) { GST_ERROR_OBJECT (srcpad, "No configuration data"); return; } self = KMS_AGNOSTIC_BIN3 (gst_pad_get_parent_element (sinkpad)); if (self == NULL) { GST_ERROR_OBJECT (sinkpad, "No parent object"); return; } g_mutex_lock (&data->mutex); GST_DEBUG_OBJECT (srcpad, "state: %s", pad_state2string (data->state)); if (data->state == KMS_SRC_PAD_STATE_LINKED) { goto end; } current_caps = g_hash_table_lookup (self->priv->sinkcaps, sinkpad); switch (data->state) { case KMS_SRC_PAD_STATE_UNCONFIGURED:{ caps = gst_pad_peer_query_caps (srcpad, current_caps); transcode = gst_caps_is_empty (caps); break; } case KMS_SRC_PAD_STATE_CONFIGURED: caps = gst_caps_ref (data->caps); transcode = !gst_caps_can_intersect (caps, current_caps); break; default: GST_ERROR_OBJECT (srcpad, "TODO: Operate in %s", pad_state2string (data->state)); goto end; } if (transcode) { gboolean supported; if (g_hash_table_size (self->priv->sinkcaps) != g_slist_length (self->priv->agnosticbins)) { /* Other transcoder which is not yet configured could */ /* manage these capabilities */ goto end; } /* This is the last transcoder expected to be in this element so far */ /* Ask to see if anyone upstream supports this caps */ g_signal_emit (G_OBJECT (self), agnosticbin3_signals[SIGNAL_CAPS], 0, caps, &supported); if (supported) { GST_DEBUG_OBJECT (srcpad, "Upstream element support %" GST_PTR_FORMAT, caps); goto end; } /* no one upstream supports these capabilities we need to transcode */ transcoder = kms_agnosticbin3_get_element_for_transcoding (self); GST_DEBUG_OBJECT (srcpad, "Connection requires transcoding"); } else { transcoder = get_transcoder_connected_to_sinkpad (sinkpad); GST_DEBUG_OBJECT (srcpad, "Connection does not require transcoding"); } if (transcoder == NULL) { GST_ERROR_OBJECT (sinkpad, "No transcoder available"); goto end; } target = gst_element_get_request_pad (transcoder, "src_%u"); g_object_unref (transcoder); GST_DEBUG_OBJECT (srcpad, "Setting target %" GST_PTR_FORMAT, target); if (!gst_ghost_pad_set_target (GST_GHOST_PAD (srcpad), target)) { GST_ERROR_OBJECT (srcpad, "Can not set target pad"); gst_element_release_request_pad (transcoder, target); } else { data->state = KMS_SRC_PAD_STATE_LINKED; } g_object_unref (target); end: if (caps != NULL) { gst_caps_unref (caps); } g_mutex_unlock (&data->mutex); g_object_unref (self); } static void link_pending_src_pads (GstPad * srcpad, GstPad * sinkpad) { KmsAgnosticBin3 *self = KMS_AGNOSTIC_BIN3 (gst_pad_get_parent_element (sinkpad)); if (self == NULL) { GST_ERROR_OBJECT (sinkpad, "No parent object"); return; } if (!gst_pad_is_linked (srcpad)) { GST_DEBUG_OBJECT (self, "Unlinked pad %" GST_PTR_FORMAT, srcpad); } else { connect_srcpad_to_encoder (srcpad, sinkpad); } g_object_unref (self); } static void append_transcoder_to_list (GstPad * sink, GSList ** elements) { GstElement *e; e = get_transcoder_connected_to_sinkpad (sink); *elements = g_slist_prepend (*elements, e); } static GSList * kms_agnosticbin3_get_configured_transcoders (KmsAgnosticBin3 * self) { GSList *transcoders = NULL; GList *pads; pads = g_hash_table_get_keys (self->priv->sinkcaps); if (g_list_length (pads) <= 0) { goto end; } g_list_foreach (pads, (GFunc) append_transcoder_to_list, &transcoders); end: if (pads != NULL) { g_list_free (pads); } return transcoders; } /* Gets the transcoder that can manage these caps or NULL. [Transfer full] */ static GstElement * kms_agnosticbin3_get_element_for_transcoding (KmsAgnosticBin3 * self) { GstElement *transcoder = NULL; guint index, len; GSList *l, *transcoders; index = (guint) g_atomic_int_add (&self->priv->last, 1); KMS_AGNOSTIC_BIN3_LOCK (self); transcoders = kms_agnosticbin3_get_configured_transcoders (self); len = g_slist_length (transcoders); if (len <= 0) { goto end; } index %= len; l = g_slist_nth (transcoders, index); transcoder = l->data; end: KMS_AGNOSTIC_BIN3_UNLOCK (self); if (transcoder != NULL) g_object_ref (transcoder); if (transcoders != NULL) { g_slist_free_full (transcoders, (GDestroyNotify) g_object_unref); } return transcoder; } static GstPadProbeReturn kms_agnostic_bin3_sink_caps_probe (GstPad * pad, GstPadProbeInfo * info, gpointer data) { GstEvent *event = gst_pad_probe_info_get_event (info); KmsAgnosticBin3 *self; GstCaps *caps, *current_caps; if (GST_EVENT_TYPE (event) != GST_EVENT_CAPS) { return GST_PAD_PROBE_OK; } GST_DEBUG_OBJECT (pad, "Event received %" GST_PTR_FORMAT, event); gst_event_parse_caps (event, &caps); self = KMS_AGNOSTIC_BIN3 (data); if (caps == NULL) { GST_ERROR_OBJECT (self, "Unexpected NULL caps"); return GST_PAD_PROBE_OK; } KMS_AGNOSTIC_BIN3_LOCK (self); current_caps = g_hash_table_lookup (self->priv->sinkcaps, pad); if (current_caps == NULL) { GST_DEBUG_OBJECT (pad, "Current input caps %" GST_PTR_FORMAT, caps); g_hash_table_insert (self->priv->sinkcaps, pad, gst_caps_copy (caps)); } else if (gst_caps_is_equal (caps, current_caps)) { GST_DEBUG_OBJECT (pad, "Caps already set %" GST_PTR_FORMAT, caps); goto end; } else { GST_WARNING_OBJECT (pad, "TODO: Input caps changed %" GST_PTR_FORMAT, caps); goto end; } kms_element_for_each_src_pad (GST_ELEMENT (self), (KmsPadCallback) link_pending_src_pads, pad); end: KMS_AGNOSTIC_BIN3_UNLOCK (self); return GST_PAD_PROBE_OK; } static GstPad * kms_agnostic_bin3_request_sink_pad (KmsAgnosticBin3 * self, GstPadTemplate * templ, const gchar * name, const GstCaps * caps) { GstElement *agnosticbin; GstPad *target, *pad = NULL; gchar *padname; agnosticbin = gst_element_factory_make ("agnosticbin", NULL); gst_bin_add (GST_BIN (self), agnosticbin); gst_element_sync_state_with_parent (agnosticbin); target = gst_element_get_static_pad (agnosticbin, "sink"); padname = g_strdup_printf (AGNOSTICBIN3_SINK_PAD, g_atomic_int_add (&self->priv->sink_pad_count, 1)); pad = gst_ghost_pad_new (padname, target); if (GST_STATE (self) >= GST_STATE_PAUSED || GST_STATE_PENDING (self) >= GST_STATE_PAUSED || GST_STATE_TARGET (self) >= GST_STATE_PAUSED) { gst_pad_set_active (pad, TRUE); } gst_element_add_pad (GST_ELEMENT (self), pad); g_free (padname); g_object_unref (target); KMS_AGNOSTIC_BIN3_LOCK (self); self->priv->agnosticbins = g_slist_prepend (self->priv->agnosticbins, agnosticbin); KMS_AGNOSTIC_BIN3_UNLOCK (self); gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, kms_agnostic_bin3_sink_caps_probe, self, NULL); return pad; } /* Gets the transcoder that can manage these caps or NULL. [Transfer full] */ /* Call this function with mutex held */ static GstElement * kms_agnostic_bin3_get_transcoder_by_srcpads (KmsAgnosticBin3 * self, const GstCaps * caps) { GstElement *transcoder = NULL; GSList *l; /* Check all agnostic's src pads looking for compatible capabilities */ /* If we find them it means that this element is already transcoding */ for (l = self->priv->agnosticbins; l != NULL; l = l->next) { GValue val = G_VALUE_INIT; GstElement *agnosticbin; gboolean done = FALSE; GstIterator *it; agnosticbin = GST_ELEMENT (l->data); it = gst_element_iterate_src_pads (agnosticbin); do { switch (gst_iterator_next (it, &val)) { case GST_ITERATOR_OK: { GstPad *srcpad; GstCaps *current_caps; srcpad = g_value_get_object (&val); current_caps = gst_pad_get_current_caps (srcpad); if (gst_caps_is_always_compatible (current_caps, caps)) { GST_INFO_OBJECT (agnosticbin, "Supports %" GST_PTR_FORMAT, caps); /* This function returns a tranfer full element */ transcoder = g_object_ref (agnosticbin); done = TRUE; } gst_caps_unref (current_caps); g_value_reset (&val); break; } case GST_ITERATOR_RESYNC: gst_iterator_resync (it); break; case GST_ITERATOR_ERROR: GST_ERROR ("Error iterating over %s's src pads", GST_ELEMENT_NAME (agnosticbin)); case GST_ITERATOR_DONE: done = TRUE; break; } } while (!done); g_value_unset (&val); gst_iterator_free (it); if (transcoder != NULL) { break; } } return transcoder; } /* Gets the transcoder that can manage these caps or NULL. [Transfer full] */ /* Call this function with mutex held */ static GstElement * kms_agnostic_bin3_get_compatible_transcoder_tree (KmsAgnosticBin3 * self, const GstCaps * caps) { GHashTableIter iter; gpointer key, value; /* Check out all agnosticbin's sink capabilities */ if (g_hash_table_size (self->priv->sinkcaps) <= 0) { GST_DEBUG_OBJECT (self, "No transcoder initialized yet"); return NULL; } g_hash_table_iter_init (&iter, self->priv->sinkcaps); while (g_hash_table_iter_next (&iter, &key, &value)) { GstPad *sinkpad = GST_PAD (key); GstCaps *sinkcaps = GST_CAPS (value); if (gst_caps_can_intersect (caps, sinkcaps)) { GST_DEBUG_OBJECT (sinkpad, "Compatible with caps %" GST_PTR_FORMAT, caps); return get_transcoder_connected_to_sinkpad (sinkpad); } } return kms_agnostic_bin3_get_transcoder_by_srcpads (self, caps); } static GstPad * kms_agnostic_bin3_create_new_src_pad (KmsAgnosticBin3 * self, GstPadTemplate * templ) { gchar *padname; GstPad *pad; padname = g_strdup_printf (AGNOSTICBIN3_SRC_PAD, g_atomic_int_add (&self->priv->src_pad_count, 1)); pad = gst_ghost_pad_new_no_target_from_template (padname, templ); g_free (padname); return pad; } static GstPad * kms_agnostic_bin3_create_src_pad_with_transcodification (KmsAgnosticBin3 * self, GstPadTemplate * templ, const GstCaps * caps) { GstElement *transcoder = NULL; GstPad *pad; pad = kms_agnostic_bin3_create_new_src_pad (self, templ); KMS_AGNOSTIC_BIN3_LOCK (self); if (g_slist_length (self->priv->agnosticbins) == 0) { GST_DEBUG_OBJECT (self, "No transcoders available"); goto end; } transcoder = kms_agnostic_bin3_get_compatible_transcoder_tree (self, caps); if (transcoder != NULL) { GST_DEBUG_OBJECT (pad, "Connect without transcoding"); set_transcoder_src_target_pad (GST_GHOST_PAD (pad), transcoder); goto end; } GST_DEBUG_OBJECT (pad, "Connect forcing transcode"); /* No compatible transcoder found. Force transcodification in one of them */ /* Get any available transcoder. Round robin will be used */ transcoder = kms_agnosticbin3_get_element_for_transcoding (self); if (transcoder != NULL) { set_transcoder_src_target_pad (GST_GHOST_PAD (pad), transcoder); } else { /* There is not any configured transcoder yet */ GST_DEBUG_OBJECT (pad, "Can not connect to any transcoder"); } end: KMS_AGNOSTIC_BIN3_UNLOCK (self); if (transcoder != NULL) { g_object_unref (transcoder); } return pad; } static gboolean set_transcoder_src_target_pad (GstGhostPad * pad, GstElement * transcoder) { GstPad *target; gboolean ret; target = gst_element_get_request_pad (transcoder, "src_%u"); if (!(ret = gst_ghost_pad_set_target (GST_GHOST_PAD (pad), target))) { GST_ERROR_OBJECT (pad, "Can not set target pad"); gst_element_release_request_pad (transcoder, target); } else { GST_LOG_OBJECT (pad, "Set target %" GST_PTR_FORMAT, target); } g_object_unref (target); return ret; } static GstPad * kms_agnostic_bin3_create_src_pad_with_caps (KmsAgnosticBin3 * self, GstPadTemplate * templ, const gchar * name, const GstCaps * caps) { GstElement *element = NULL; KmsSrcPadData *paddata; gboolean ret = FALSE; GstPad *pad; paddata = create_src_pad_data (); paddata->caps = gst_caps_copy (caps); KMS_AGNOSTIC_BIN3_LOCK (self); element = kms_agnostic_bin3_get_compatible_transcoder_tree (self, caps); if (element != NULL) { KMS_AGNOSTIC_BIN3_UNLOCK (self); /* Create ghost pad connected to the transcoder element */ pad = kms_agnostic_bin3_create_new_src_pad (self, templ); if (set_transcoder_src_target_pad (GST_GHOST_PAD (pad), element)) { paddata->state = KMS_SRC_PAD_STATE_LINKED; } else { /* We got caps but we could not link with this agnostic */ paddata->state = KMS_SRC_PAD_STATE_CONFIGURED; } g_object_unref (element); goto end; } KMS_AGNOSTIC_BIN3_UNLOCK (self); /* Trigger caps signal */ g_signal_emit (G_OBJECT (self), agnosticbin3_signals[SIGNAL_CAPS], 0, caps, &ret); if (ret) { /* Someone upstream supports these caps */ paddata->state = KMS_SRC_PAD_STATE_WAITING; pad = kms_agnostic_bin3_create_new_src_pad (self, templ); } else { GstPad *target; /* Transcode will be done in any available agnosticbin */ pad = kms_agnostic_bin3_create_src_pad_with_transcodification (self, templ, caps); target = gst_ghost_pad_get_target (GST_GHOST_PAD (pad)); if (target != NULL) { paddata->state = KMS_SRC_PAD_STATE_LINKED; g_object_unref (target); } else { paddata->state = KMS_SRC_PAD_STATE_CONFIGURED; } } end: g_object_set_qdata_full (G_OBJECT (pad), kms_agnosticbin3_src_pad_data_quark (), paddata, (GDestroyNotify) destroy_src_pad_data); kms_agnostic_bin3_append_pending_src_pad (self, pad); return pad; } static GstPad * kms_agnostic_bin3_create_src_pad_without_caps (KmsAgnosticBin3 * self, GstPadTemplate * templ, const gchar * name) { KmsSrcPadData *paddata; GstPad *pad; paddata = create_src_pad_data (); pad = kms_agnostic_bin3_create_new_src_pad (self, templ); g_object_set_qdata_full (G_OBJECT (pad), kms_agnosticbin3_src_pad_data_quark (), paddata, (GDestroyNotify) destroy_src_pad_data); kms_agnostic_bin3_append_pending_src_pad (self, pad); return pad; } static void kms_agnostic_bin3_src_pad_linked (GstPad * pad, GstPad * peer, gpointer user_data) { KmsAgnosticBin3 *self = KMS_AGNOSTIC_BIN3 (user_data); KmsSrcPadState new_state = KMS_SRC_PAD_STATE_UNCONFIGURED; GstElement *element; KmsSrcPadData *data; GstCaps *caps = NULL; gboolean ret; data = g_object_get_qdata (G_OBJECT (pad), kms_agnosticbin3_src_pad_data_quark ()); if (data == NULL) { GST_ERROR_OBJECT (pad, "No configuration data"); return; } g_mutex_lock (&data->mutex); if (data->state != KMS_SRC_PAD_STATE_UNCONFIGURED) { GST_DEBUG_OBJECT (pad, "Already configured"); g_mutex_unlock (&data->mutex); return; } data->state = KMS_SRC_PAD_STATE_CONFIGURING; g_mutex_unlock (&data->mutex); caps = gst_pad_query_caps (peer, NULL); KMS_AGNOSTIC_BIN3_LOCK (self); if (g_slist_length (self->priv->agnosticbins) == 0) { GST_DEBUG_OBJECT (self, "No transcoders available"); new_state = KMS_SRC_PAD_STATE_UNCONFIGURED; goto change_state; } element = kms_agnostic_bin3_get_compatible_transcoder_tree (self, caps); if (element != NULL) { GST_DEBUG_OBJECT (pad, "Connected without transcoding to %" GST_PTR_FORMAT, element); goto connect_transcoder; } if (g_hash_table_size (self->priv->sinkcaps) != g_slist_length (self->priv->agnosticbins)) { /* There is still pending agnosticbins that are not yet configured */ /* Any of them may support this pad without transcoding. Wait until */ /* agnosticbins negotiate caps. They will connect pending pads as */ /* soon as they get the caps event */ new_state = KMS_SRC_PAD_STATE_UNCONFIGURED; goto change_state; } g_signal_emit (G_OBJECT (self), agnosticbin3_signals[SIGNAL_CAPS], 0, caps, &ret); if (ret) { /* Someone upstream supports these caps, there is not need to transcode */ new_state = KMS_SRC_PAD_STATE_WAITING; goto change_state; } /* Get any available transcoder. Round robin will be ussed */ element = kms_agnosticbin3_get_element_for_transcoding (self); if (element == NULL) { GST_DEBUG_OBJECT (pad, "Can not connect to any encoder yet"); goto change_state; } GST_DEBUG_OBJECT (pad, "Connected transcoding"); connect_transcoder: { if (set_transcoder_src_target_pad (GST_GHOST_PAD (pad), element)) { new_state = KMS_SRC_PAD_STATE_LINKED; } else { new_state = KMS_SRC_PAD_STATE_UNCONFIGURED; } g_object_unref (element); } change_state: { g_mutex_lock (&data->mutex); data->state = new_state; g_mutex_unlock (&data->mutex); KMS_AGNOSTIC_BIN3_UNLOCK (self); if (caps != NULL) { gst_caps_unref (caps); } } } static GstPad * kms_agnostic_bin3_request_src_pad (KmsAgnosticBin3 * self, GstPadTemplate * templ, const gchar * name, const GstCaps * caps) { GstPad *pad; if (caps != NULL) { pad = kms_agnostic_bin3_create_src_pad_with_caps (self, templ, name, caps); } else { pad = kms_agnostic_bin3_create_src_pad_without_caps (self, templ, name); } if (pad != NULL) { g_signal_connect (pad, "linked", G_CALLBACK (kms_agnostic_bin3_src_pad_linked), self); } return pad; } static GstPad * kms_agnostic_bin3_request_new_pad (GstElement * element, GstPadTemplate * templ, const gchar * name, const GstCaps * caps) { KmsAgnosticBin3 *self = KMS_AGNOSTIC_BIN3 (element); if (templ == gst_element_class_get_pad_template (GST_ELEMENT_CLASS (G_OBJECT_GET_CLASS (element)), AGNOSTICBIN3_SINK_PAD)) { return kms_agnostic_bin3_request_sink_pad (self, templ, name, caps); } else if (templ == gst_element_class_get_pad_template (GST_ELEMENT_CLASS (G_OBJECT_GET_CLASS (element)), AGNOSTICBIN3_SRC_PAD)) { return kms_agnostic_bin3_request_src_pad (self, templ, name, caps); } else { GST_ERROR_OBJECT (element, "Unsupported pad template %" GST_PTR_FORMAT, templ); return NULL; } } static void kms_agnostic_bin3_release_pad (GstElement * element, GstPad * pad) { /* TODO: */ GST_DEBUG_OBJECT (element, "Release pad %" GST_PTR_FORMAT, pad); } static void kms_agnostic_bin3_finalize (GObject * object) { KmsAgnosticBin3 *self = KMS_AGNOSTIC_BIN3 (object); g_slist_free (self->priv->agnosticbins); g_hash_table_unref (self->priv->sinkcaps); g_rec_mutex_clear (&self->priv->mutex); G_OBJECT_CLASS (parent_class)->finalize (object); } static void kms_agnostic_bin3_class_init (KmsAgnosticBin3Class * klass) { GObjectClass *gobject_class; GstElementClass *gstelement_class; gobject_class = G_OBJECT_CLASS (klass); gobject_class->finalize = kms_agnostic_bin3_finalize; gstelement_class = GST_ELEMENT_CLASS (klass); gst_element_class_set_details_simple (gstelement_class, "Agnostic connector 3rd version", "Generic/Bin/Connector", "Automatically encodes/decodes media to match sink and source pads caps", "<NAME> <<EMAIL>>"); gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&src_factory)); gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&sink_factory)); gstelement_class->request_new_pad = GST_DEBUG_FUNCPTR (kms_agnostic_bin3_request_new_pad); gstelement_class->release_pad = GST_DEBUG_FUNCPTR (kms_agnostic_bin3_release_pad); /* set signals */ agnosticbin3_signals[SIGNAL_CAPS] = g_signal_new ("caps", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (KmsAgnosticBin3Class, caps_signal), NULL, NULL, __kms_core_marshal_BOOLEAN__BOXED, G_TYPE_BOOLEAN, 1, GST_TYPE_CAPS); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, PLUGIN_NAME, 0, PLUGIN_NAME); g_type_class_add_private (klass, sizeof (KmsAgnosticBin3Private)); } static void kms_agnostic_bin3_init (KmsAgnosticBin3 * self) { self->priv = KMS_AGNOSTIC_BIN3_GET_PRIVATE (self); g_rec_mutex_init (&self->priv->mutex); self->priv->sinkcaps = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, (GDestroyNotify) gst_caps_unref); } gboolean kms_agnostic_bin3_plugin_init (GstPlugin * plugin) { return gst_element_register (plugin, PLUGIN_NAME, GST_RANK_NONE, KMS_TYPE_AGNOSTIC_BIN3); }
bjxagu/kms-core
tests/check/element/passthrough.c
/* * (C) Copyright 2015 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <gst/check/gstcheck.h> #include <gst/gst.h> #include "../../src/gst-plugins/commons/kmselementpadtype.h" #define KMS_VIDEO_PREFIX "video_src_" #define KMS_AUDIO_PREFIX "audio_src_" #define VIDEO_SINK "video-sink" G_DEFINE_QUARK (VIDEO_SINK, video_sink); #define BITRATE 500000 static gboolean quit_main_loop_idle (gpointer data) { GMainLoop *loop = data; g_main_loop_quit (loop); return FALSE; } static void bus_msg (GstBus * bus, GstMessage * msg, gpointer pipe) { switch (GST_MESSAGE_TYPE (msg)) { case GST_MESSAGE_ERROR:{ gchar *error_file = g_strdup_printf ("error-%s", GST_OBJECT_NAME (pipe)); GST_ERROR ("Error: %" GST_PTR_FORMAT, msg); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipe), GST_DEBUG_GRAPH_SHOW_ALL, error_file); g_free (error_file); fail ("Error received on bus"); break; } case GST_MESSAGE_WARNING:{ gchar *warn_file = g_strdup_printf ("warning-%s", GST_OBJECT_NAME (pipe)); GST_WARNING ("Warning: %" GST_PTR_FORMAT, msg); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipe), GST_DEBUG_GRAPH_SHOW_ALL, warn_file); g_free (warn_file); break; } default: break; } } static void fakesink_hand_off_check_size (GstElement * fakesink, GstBuffer * buf, GstPad * pad, gpointer data) { static int count = 0; static gsize size = 0; GMainLoop *loop = (GMainLoop *) data; size += gst_buffer_get_size (buf); if (count++ >= 60) { gsize bitrate = size * 8 / (count / 30); // TODO: Count for size GST_INFO ("Bitrate is: %ld bits", bitrate); fail_if (abs (bitrate - BITRATE) > BITRATE * 0.15); g_object_set (G_OBJECT (fakesink), "signal-handoffs", FALSE, NULL); g_idle_add (quit_main_loop_idle, loop); } } static void fakesink_hand_off (GstElement * fakesink, GstBuffer * buf, GstPad * pad, gpointer data) { static int count = 0; GMainLoop *loop = (GMainLoop *) data; if (count++ > 40) { g_object_set (G_OBJECT (fakesink), "signal-handoffs", FALSE, NULL); g_idle_add (quit_main_loop_idle, loop); } } static gboolean timeout_check (gpointer pipeline) { if (GST_IS_BIN (pipeline)) { gchar *timeout_file = g_strdup_printf ("timeout-%s", GST_OBJECT_NAME (pipeline)); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline), GST_DEBUG_GRAPH_SHOW_ALL, timeout_file); g_free (timeout_file); } return FALSE; } typedef struct _KmsConnectData { GstElement *src; GstBin *pipe; const gchar *pad_prefix; gulong id; } KmsConnectData; static gboolean connect_sink_async (GstElement * passthrough, GstElement * src, GstElement * pipe, const gchar * pad_prefix) { GstPad *pad = gst_element_get_static_pad (passthrough, pad_prefix); if (pad == NULL) { return FALSE; } gst_bin_add (GST_BIN (pipe), src); gst_element_link_pads (src, NULL, passthrough, pad_prefix); gst_element_sync_state_with_parent (src); g_object_unref (pad); return TRUE; } static void connect_sink_on_srcpad_added (GstElement * element, GstPad * pad) { GstElement *sink; GstPad *sinkpad; GST_DEBUG_OBJECT (element, "Added pad %" GST_PTR_FORMAT, pad); if (g_str_has_prefix (GST_PAD_NAME (pad), KMS_AUDIO_PREFIX)) { GST_ERROR_OBJECT (pad, "Not connecting audio stream, it is not expected"); return; } else if (g_str_has_prefix (GST_PAD_NAME (pad), KMS_VIDEO_PREFIX)) { GST_DEBUG_OBJECT (pad, "Connecting video stream"); sink = g_object_get_qdata (G_OBJECT (element), video_sink_quark ()); } else { GST_TRACE_OBJECT (pad, "Not src pad type"); return; } sinkpad = gst_element_get_static_pad (sink, "sink"); gst_pad_link (pad, sinkpad); g_object_unref (sinkpad); gst_element_sync_state_with_parent (sink); } static gboolean kms_element_request_srcpad (GstElement * src, KmsElementPadType pad_type) { gchar *padname; gboolean ret; g_signal_emit_by_name (src, "request-new-pad", pad_type, NULL, GST_PAD_SRC, &padname); ret = padname != NULL; g_free (padname); return ret; } static void on_pad_added_cb (GstElement * element, GstPad * pad, gpointer user_data) { GST_DEBUG_OBJECT (element, "Pad added %" GST_PTR_FORMAT, pad); if (gst_pad_get_direction (pad) == GST_PAD_SRC) { connect_sink_on_srcpad_added (element, pad); } } GST_START_TEST (check_connecion) { GMainLoop *loop = g_main_loop_new (NULL, TRUE); GstElement *pipeline = gst_pipeline_new (__FUNCTION__); GstElement *videotestsrc = gst_element_factory_make ("videotestsrc", NULL); GstElement *fakesink = gst_element_factory_make ("fakesink", NULL); GstElement *passthrough = gst_element_factory_make ("passthrough", NULL); GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); KmsConnectData data; data.src = videotestsrc; data.pipe = GST_BIN (pipeline); data.pad_prefix = "sink_video_default"; g_object_set (G_OBJECT (videotestsrc), "is-live", TRUE, NULL); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); g_object_set (G_OBJECT (fakesink), "sync", TRUE, "signal-handoffs", TRUE, "async", FALSE, NULL); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (fakesink_hand_off), loop); g_object_set_qdata (G_OBJECT (passthrough), video_sink_quark (), fakesink); g_signal_connect (passthrough, "pad-added", G_CALLBACK (on_pad_added_cb), &data); mark_point (); gst_bin_add_many (GST_BIN (pipeline), passthrough, fakesink, NULL); mark_point (); fail_unless (kms_element_request_srcpad (passthrough, KMS_ELEMENT_PAD_TYPE_VIDEO)); fail_if (!connect_sink_async (passthrough, videotestsrc, pipeline, data.pad_prefix)); mark_point (); gst_element_set_state (pipeline, GST_STATE_PLAYING); mark_point (); g_timeout_add_seconds (10, timeout_check, pipeline); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (bus); g_object_unref (pipeline); g_main_loop_unref (loop); } GST_END_TEST; GST_START_TEST (check_bitrate) { GMainLoop *loop = g_main_loop_new (NULL, TRUE); GstElement *pipeline = gst_pipeline_new (__FUNCTION__); GstElement *videotestsrc = gst_element_factory_make ("videotestsrc", NULL); GstElement *fakesink = gst_element_factory_make ("fakesink", NULL); GstElement *passthrough = gst_element_factory_make ("passthrough", NULL); GstElement *capsfilter = gst_element_factory_make ("capsfilter", NULL); GstCaps *caps = gst_caps_from_string ("video/x-vp8,framerate=30/1"); GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); KmsConnectData data; data.src = videotestsrc; data.pipe = GST_BIN (pipeline); data.pad_prefix = "sink_video_default"; g_object_set (G_OBJECT (videotestsrc), "is-live", TRUE, NULL); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); g_object_set (G_OBJECT (fakesink), "sync", TRUE, "signal-handoffs", TRUE, "async", FALSE, NULL); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (fakesink_hand_off_check_size), loop); g_object_set (capsfilter, "caps", caps, NULL); gst_caps_unref (caps); g_object_set (passthrough, "min-output-bitrate", BITRATE, "max-output-bitrate", BITRATE, NULL); g_object_set_qdata (G_OBJECT (passthrough), video_sink_quark (), capsfilter); g_signal_connect (passthrough, "pad-added", G_CALLBACK (on_pad_added_cb), NULL); mark_point (); gst_bin_add_many (GST_BIN (pipeline), passthrough, capsfilter, fakesink, NULL); gst_element_link (capsfilter, fakesink); mark_point (); fail_if (!connect_sink_async (passthrough, videotestsrc, pipeline, data.pad_prefix)); fail_unless (kms_element_request_srcpad (passthrough, KMS_ELEMENT_PAD_TYPE_VIDEO)); mark_point (); gst_element_set_state (pipeline, GST_STATE_PLAYING); mark_point (); g_timeout_add_seconds (10, timeout_check, pipeline); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (bus); g_object_unref (pipeline); g_main_loop_unref (loop); } GST_END_TEST; /* Suite initialization */ static Suite * passthrough_suite (void) { Suite *s = suite_create ("filterelement"); TCase *tc_chain = tcase_create ("element"); suite_add_tcase (s, tc_chain); tcase_add_test (tc_chain, check_connecion); tcase_add_test (tc_chain, check_bitrate); return s; } GST_CHECK_MAIN (passthrough);
bjxagu/kms-core
src/gst-plugins/commons/sdpagent/kmsisdppayloadmanager.h
/* * (C) Copyright 2015 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef __KMS_I_SDP_PAYLOAD_MANAGER_H__ #define __KMS_I_SDP_PAYLOAD_MANAGER_H__ #include <gst/gst.h> #define KMS_TYPE_I_SDP_PAYLOAD_MANAGER \ (kms_i_sdp_payload_manager_get_type ()) #define KMS_I_SDP_PAYLOAD_MANAGER(obj) \ (G_TYPE_CHECK_INSTANCE_CAST ((obj), KMS_TYPE_I_SDP_PAYLOAD_MANAGER, KmsISdpPayloadManager)) #define KMS_IS_I_SDP_PAYLOAD_MANAGER(obj) \ (G_TYPE_CHECK_INSTANCE_TYPE ((obj), KMS_TYPE_I_SDP_PAYLOAD_MANAGER)) #define KMS_I_SDP_PAYLOAD_MANAGER_GET_INTERFACE(inst) \ (G_TYPE_INSTANCE_GET_INTERFACE ((inst), KMS_TYPE_I_SDP_PAYLOAD_MANAGER, KmsISdpPayloadManagerInterface)) typedef struct _KmsISdpPayloadManager KmsISdpPayloadManager; typedef struct _KmsISdpPayloadManagerInterface KmsISdpPayloadManagerInterface; struct _KmsISdpPayloadManagerInterface { GTypeInterface parent; gint (*get_dynamic_pt) (KmsISdpPayloadManager *self, GError **error); }; GType kms_i_sdp_payload_manager_get_type (void); gint kms_i_sdp_payload_manager_get_dynamic_pt (KmsISdpPayloadManager *self, GError **error); #endif /* __KMS_I_SDP_PAYLOAD_MANAGER_H__ */
bjxagu/kms-core
src/gst-plugins/commons/sdpagent/kmssdpcontext.c
<filename>src/gst-plugins/commons/sdpagent/kmssdpcontext.c /* * (C) Copyright 2015 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "kmsrefstruct.h" #include "sdp_utils.h" #include "constants.h" #include "kmsutils.h" #include "kmssdpagent.h" #include "kmssdpcontext.h" #include <stdlib.h> #define GST_CAT_DEFAULT sdp_context GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "sdp_context" #define ORIGIN_ATTR_NETTYPE "IN" #define ORIGIN_ATTR_ADDR_TYPE_IP4 "IP4" #define ORIGIN_ATTR_ADDR_TYPE_IP6 "IP6" #define DEFAULT_IP4_ADDR "0.0.0.0" #define DEFAULT_IP6_ADDR "::" struct _SdpMediaGroup { guint id; GSList *medias; }; struct _SdpMediaConfig { guint id; gchar *mid; SdpMediaGroup *group; GstSDPMedia *media; }; struct _SdpMessageContext { KmsRefStruct ref; KmsSdpMessageType type; GstSDPMessage *msg; GSList *medias; /* list of SdpMediaConfigs */ GSList *grouped_medias; GHashTable *mids; GSList *groups; }; static SdpMediaGroup * kms_sdp_context_new_media_group (guint gid) { SdpMediaGroup *group; group = g_slice_new0 (SdpMediaGroup); group->id = gid; return group; } static void kms_sdp_context_destroy_media_group (SdpMediaGroup * group) { g_slist_free (group->medias); g_slice_free (SdpMediaGroup, group); } static SdpMediaConfig * kms_sdp_context_new_media_config (guint id, gchar * mid, GstSDPMedia * media) { SdpMediaConfig *mconf; mconf = g_slice_new0 (SdpMediaConfig); mconf->id = id; mconf->mid = mid; mconf->media = media; return mconf; } static void kms_sdp_context_destroy_media_config (SdpMediaConfig * mconf) { if (mconf->media != NULL) { gst_sdp_media_free (mconf->media); } g_free (mconf->mid); g_slice_free (SdpMediaConfig, mconf); } const gchar * kms_sdp_message_context_ipv2str (SdpIPv ipv) { switch (ipv) { case IPV4: return ORIGIN_ATTR_ADDR_TYPE_IP4; case IPV6: return ORIGIN_ATTR_ADDR_TYPE_IP6; default: return NULL; } } static gboolean kms_sdp_message_context_set_default_session_attributes (GstSDPMessage * msg, GError ** error) { const gchar *err_attr; if (gst_sdp_message_set_version (msg, "0") != GST_SDP_OK) { err_attr = "version"; goto error; } if (gst_sdp_message_set_session_name (msg, "Kurento Media Server") != GST_SDP_OK) { err_attr = "session"; goto error; } return TRUE; error: g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_PARAMETER, "Can not set attr: %s", err_attr); return FALSE; } static void kms_sdp_message_context_destroy (SdpMessageContext * ctx) { if (ctx->msg != NULL) { gst_sdp_message_free (ctx->msg); } g_hash_table_unref (ctx->mids); g_slist_free_full (ctx->grouped_medias, (GDestroyNotify) kms_sdp_context_destroy_media_config); g_slist_free_full (ctx->medias, (GDestroyNotify) kms_sdp_context_destroy_media_config); g_slist_free_full (ctx->groups, (GDestroyNotify) kms_sdp_context_destroy_media_group); g_slice_free (SdpMessageContext, ctx); } SdpMessageContext * kms_sdp_message_context_new (GError ** error) { SdpMessageContext *ctx; ctx = g_slice_new0 (SdpMessageContext); kms_ref_struct_init (KMS_REF_STRUCT_CAST (ctx), (GDestroyNotify) kms_sdp_message_context_destroy); gst_sdp_message_new (&ctx->msg); ctx->mids = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) kms_utils_destroy_guint); if (!kms_sdp_message_context_set_default_session_attributes (ctx->msg, error)) { kms_sdp_message_context_destroy (ctx); return NULL; } return ctx; } SdpMessageContext * kms_sdp_message_context_ref (SdpMessageContext * ctx) { return (SdpMessageContext *) kms_ref_struct_ref (KMS_REF_STRUCT_CAST (ctx)); } void kms_sdp_message_context_unref (SdpMessageContext * ctx) { kms_ref_struct_unref (KMS_REF_STRUCT_CAST (ctx)); } static gboolean intersect_session_attr (const GstSDPAttribute * attr, gpointer user_data) { SdpMessageContext *ctx = user_data; guint i, len; if (g_strcmp0 (attr->key, "group") == 0) { /* Exclude group attributes so they are managed indepently */ return TRUE; } /* Check that this attribute is already in the message */ len = gst_sdp_message_attributes_len (ctx->msg); for (i = 0; i < len; i++) { const GstSDPAttribute *a; a = gst_sdp_message_get_attribute (ctx->msg, i); if (g_strcmp0 (attr->key, a->key) == 0 && g_strcmp0 (attr->value, a->value) == 0) { return FALSE; } } return gst_sdp_message_add_attribute (ctx->msg, attr->key, attr->value) == GST_SDP_OK; } gboolean kms_sdp_message_context_set_common_session_attributes (SdpMessageContext * ctx, const GstSDPMessage * msg, GError ** error) { if (!sdp_utils_intersect_session_attributes (msg, intersect_session_attr, ctx)) { g_set_error_literal (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_PARAMETER, "Can not interset session attributes"); return FALSE; } return TRUE; } static gboolean configure_pending_mediaconfig (SdpMessageContext * ctx, GstSDPMedia * media, SdpMediaConfig ** mconf) { const gchar *val; GSList *l; val = gst_sdp_media_get_attribute_val (media, "mid"); if (val == NULL) { /* No grouped */ return FALSE; } for (l = ctx->groups; l != NULL; l = l->next) { SdpMediaGroup *group = l->data; GSList *ll; for (ll = group->medias; ll != NULL; ll = ll->next) { SdpMediaConfig *m; m = ll->data; if (m->media != NULL) { continue; } if (g_strcmp0 (m->mid, val) == 0) { m->media = media; m->group = group; *mconf = m; return TRUE; } } } return FALSE; } static void configure_new_mediaconfig (SdpMessageContext * ctx, GstSDPMedia * media, SdpMediaConfig ** mconf) { gchar *mid; mid = g_strdup (gst_sdp_media_get_attribute_val (media, "mid")); if (mid == NULL) { const gchar *media_type; guint *counter; media_type = gst_sdp_media_get_media (media); counter = g_hash_table_lookup (ctx->mids, media_type); if (counter == NULL) { /* No stored medias of this type yet */ counter = g_slice_new0 (guint); g_hash_table_insert (ctx->mids, g_strdup (media_type), counter); } mid = g_strdup_printf ("%s%u", media_type, (*counter)++); } *mconf = kms_sdp_context_new_media_config (g_slist_length (ctx->medias), mid, media); } SdpMediaConfig * kms_sdp_message_context_add_media (SdpMessageContext * ctx, GstSDPMedia * media, GError ** error) { SdpMediaConfig *mconf; if (ctx->type == KMS_SDP_ANSWER && g_slist_length (ctx->groups) > 0 && gst_sdp_media_get_attribute_val (media, "mid") == NULL) { g_set_error_literal (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_UNEXPECTED_ERROR, "Missing mid attribute for media"); return NULL; } if (configure_pending_mediaconfig (ctx, media, &mconf)) { ctx->grouped_medias = g_slist_remove (ctx->grouped_medias, mconf); /* Set proper id */ mconf->id = g_slist_length (ctx->medias); goto end; } configure_new_mediaconfig (ctx, media, &mconf); end: ctx->medias = g_slist_append (ctx->medias, mconf); return mconf; } gint kms_sdp_media_config_get_id (SdpMediaConfig * mconf) { return mconf->id; } const gchar * kms_sdp_media_config_get_mid (SdpMediaConfig * mconf) { return mconf->mid; } gboolean kms_sdp_media_config_is_rtcp_mux (SdpMediaConfig * mconf) { return gst_sdp_media_get_attribute_val (mconf->media, "rtcp-mux") != NULL; } SdpMediaGroup * kms_sdp_media_config_get_group (SdpMediaConfig * mconf) { return mconf->group; } GstSDPMedia * kms_sdp_media_config_get_sdp_media (SdpMediaConfig * mconf) { return mconf->media; } gboolean kms_sdp_media_config_is_inactive (SdpMediaConfig * mconf) { return (gst_sdp_media_get_attribute_val (mconf->media, "inactive") != NULL) || (gst_sdp_media_get_port (mconf->media) == 0); } gint kms_sdp_media_config_get_abs_send_time_id (SdpMediaConfig * mconf) { GstSDPMedia *media = kms_sdp_media_config_get_sdp_media (mconf); guint a; for (a = 0;; a++) { const gchar *attr; gchar **tokens; attr = gst_sdp_media_get_attribute_val_n (media, EXT_MAP, a); if (attr == NULL) { break; } tokens = g_strsplit (attr, " ", 0); if (g_strcmp0 (RTP_HDR_EXT_ABS_SEND_TIME_URI, tokens[1]) == 0) { gint ret = atoi (tokens[0]); g_strfreev (tokens); return ret; } g_strfreev (tokens); } return -1; } static gboolean add_media_to_sdp_message (SdpMediaConfig * mconf, GstSDPMessage * msg, GError ** error) { GstSDPMedia *cpy; if (gst_sdp_media_get_attribute_val (mconf->media, "mid") == NULL) { /* When group attribute is present, the mid attribute */ /* in media is mandatory */ gst_sdp_media_add_attribute (mconf->media, "mid", mconf->mid); } if (gst_sdp_media_copy (mconf->media, &cpy) != GST_SDP_OK) { g_set_error_literal (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_UNEXPECTED_ERROR, "can not create media entry"); return FALSE; } gst_sdp_message_add_media (msg, cpy); gst_sdp_media_free (cpy); return TRUE; } static void add_group_to_sdp_message (SdpMediaGroup * group, GstSDPMessage * msg) { gchar *val; GSList *l; if (g_slist_length (group->medias) <= 0) { /* No medias in group */ return; } val = g_strdup ("BUNDLE"); for (l = group->medias; l != NULL; l = l->next) { SdpMediaConfig *mconf = l->data; gchar *tmp; if (mconf->media == NULL || gst_sdp_media_get_port (mconf->media) == 0) { /* Move this media out the group */ continue; } tmp = val; val = g_strdup_printf ("%s %s", tmp, mconf->mid); g_free (tmp); } gst_sdp_message_add_attribute (msg, "group", val); g_free (val); } GstSDPMessage * kms_sdp_message_context_pack (SdpMessageContext * ctx, GError ** error) { GstSDPMessage *msg; gchar *sdp_str; GSList *l; gst_sdp_message_new (&msg); /* Context's message only stores media session attributes */ sdp_str = gst_sdp_message_as_text (ctx->msg); if (gst_sdp_message_parse_buffer ((const guint8 *) sdp_str, -1, msg) != GST_SDP_OK) { g_set_error_literal (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_UNEXPECTED_ERROR, "Can not create SDP message"); g_free (sdp_str); return NULL; } g_free (sdp_str); /* Add group attributes */ g_slist_foreach (ctx->groups, (GFunc) add_group_to_sdp_message, msg); /* Append medias to the message */ for (l = ctx->medias; l != NULL; l = g_slist_next (l)) { if (!add_media_to_sdp_message (l->data, msg, error)) { gst_sdp_message_free (msg); return NULL; } } return msg; } SdpMediaGroup * kms_sdp_message_context_create_group (SdpMessageContext * ctx, guint gid) { SdpMediaGroup *group; group = kms_sdp_context_new_media_group (gid); ctx->groups = g_slist_append (ctx->groups, group); return group; } gboolean kms_sdp_message_context_has_groups (SdpMessageContext * ctx) { return g_slist_length (ctx->groups) > 0; } gint kms_sdp_media_group_get_id (SdpMediaGroup * group) { return group->id; } SdpMediaGroup * kms_sdp_message_context_get_group (SdpMessageContext * ctx, guint gid) { GSList *l; for (l = ctx->groups; l != NULL; l = l->next) { SdpMediaGroup *group = l->data; if (group->id == gid) { return group; } } return NULL; } gboolean kms_sdp_message_context_add_media_to_group (SdpMediaGroup * group, SdpMediaConfig * media, GError ** error) { if (media->group != NULL) { g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_UNEXPECTED_ERROR, "Media already belongs to group (%d)", group->id); return FALSE; } group->medias = g_slist_append (group->medias, media); media->group = group; return TRUE; } static gint compare_media_config_by_id (SdpMediaConfig * mconf, guint * id) { return *id - mconf->id; } gboolean kms_sdp_message_context_remove_media_from_group (SdpMediaGroup * group, guint id, GError ** error) { GSList *l; l = g_slist_find_custom (group->medias, &id, (GCompareFunc) compare_media_config_by_id); if (l == NULL) { return FALSE; } group->medias = g_slist_remove (group->medias, l->data); return TRUE; } gboolean kms_sdp_message_context_parse_groups_from_offer (SdpMessageContext * ctx, const GstSDPMessage * offer, GError ** error) { guint i, gid = 0; for (i = 0;; i++) { SdpMediaGroup *mgroup; gboolean is_bundle; const gchar *val; gchar **grp; guint j; val = gst_sdp_message_get_attribute_val_n (offer, "group", i); if (val == NULL) { return TRUE; } grp = g_strsplit (val, " ", 0); is_bundle = g_strcmp0 (grp[0] /* group type */ , "BUNDLE") == 0; if (!is_bundle) { GST_WARNING ("Group '%s' is not supported", grp[0]); g_strfreev (grp); continue; } mgroup = kms_sdp_message_context_create_group (ctx, gid++); for (j = 1; grp[j] != NULL; j++) { SdpMediaConfig *mconf; mconf = kms_sdp_context_new_media_config (0, g_strdup (grp[j]), NULL); ctx->grouped_medias = g_slist_append (ctx->grouped_medias, mconf); if (!kms_sdp_message_context_add_media_to_group (mgroup, mconf, error)) { g_strfreev (grp); return FALSE; } } g_strfreev (grp); } } struct SdpMediaContextData { SdpMessageContext *ctx; GError **err; }; static gboolean add_media_context (const GstSDPMedia * media, struct SdpMediaContextData *data) { SdpMessageContext *ctx = data->ctx; GstSDPMedia *cpy; if (gst_sdp_media_copy (media, &cpy) != GST_SDP_OK) { g_set_error_literal (data->err, KMS_SDP_AGENT_ERROR, SDP_AGENT_UNEXPECTED_ERROR, "Can not copy media entry"); return FALSE; } if (kms_sdp_message_context_add_media (ctx, cpy, data->err) == NULL) { return FALSE; } return TRUE; } static gboolean copy_session_attributes (SdpMessageContext * ctx, const GstSDPMessage * msg, GError ** error) { const GstSDPOrigin *o1; const gchar *s; o1 = gst_sdp_message_get_origin (msg); if (gst_sdp_message_set_origin (ctx->msg, o1->username, o1->sess_id, o1->sess_version, o1->nettype, o1->addrtype, o1->addr) != GST_SDP_OK) { g_set_error_literal (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_PARAMETER, "Can not set origin"); return FALSE; } s = gst_sdp_message_get_session_name (msg); if (gst_sdp_message_set_session_name (ctx->msg, s) != GST_SDP_OK) { g_set_error_literal (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_PARAMETER, "Can not set session name"); return FALSE; } if (!sdp_utils_intersect_session_attributes (msg, intersect_session_attr, ctx)) { g_set_error_literal (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_PARAMETER, "Can not interset session attributes"); return FALSE; } return TRUE; } SdpMessageContext * kms_sdp_message_context_new_from_sdp (GstSDPMessage * sdp, GError ** error) { struct SdpMediaContextData data; SdpMessageContext *ctx; const GstSDPOrigin *o; ctx = kms_sdp_message_context_new (error); if (ctx == NULL) { return NULL; } o = gst_sdp_message_get_origin (sdp); if (!kms_sdp_message_context_set_origin (ctx, o, error)) { goto error; } if (!kms_sdp_message_context_parse_groups_from_offer (ctx, sdp, error)) { goto error; } if (!copy_session_attributes (ctx, sdp, error)) { goto error; } data.ctx = ctx; data.err = error; if (!sdp_utils_for_each_media (sdp, (GstSDPMediaFunc) add_media_context, &data)) { g_set_error_literal (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_UNEXPECTED_ERROR, "can not create SDP context"); goto error; } return ctx; error: kms_sdp_message_context_unref (ctx); return NULL; } GstSDPMessage * kms_sdp_message_context_get_sdp_message (SdpMessageContext * ctx) { return ctx->msg; } GSList * kms_sdp_message_context_get_medias (SdpMessageContext * ctx) { return ctx->medias; } SdpMediaConfig * kms_sdp_message_context_get_media (SdpMessageContext * ctx, guint idx) { return (SdpMediaConfig *) g_slist_nth_data (ctx->medias, idx); } void kms_sdp_message_context_set_type (SdpMessageContext * ctx, KmsSdpMessageType type) { ctx->type = type; } KmsSdpMessageType kms_sdp_message_context_get_type (SdpMessageContext * ctx) { return ctx->type; } gboolean kms_sdp_message_context_set_origin (SdpMessageContext * ctx, const GstSDPOrigin * origin, GError ** error) { if (gst_sdp_message_set_origin (ctx->msg, origin->username, origin->sess_id, origin->sess_version, origin->nettype, origin->addrtype, origin->addr) != GST_SDP_OK) { g_set_error_literal (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_PARAMETER, "Can not set attr: origin"); return FALSE; } if (gst_sdp_message_set_connection (ctx->msg, origin->nettype, origin->addrtype, origin->addr, 0, 0) != GST_SDP_OK) { g_set_error_literal (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_PARAMETER, "Can not set attr: connection"); return FALSE; } return TRUE; } KmsSdpMessageType kms_sdp_message_context_get_type (SdpMessageContext * ctx); static void init_debug (void) __attribute__ ((constructor)); static void init_debug (void) { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); }
bjxagu/kms-core
src/gst-plugins/commons/sdpagent/kmssdpbundlegroup.c
/* * (C) Copyright 2015 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "kmssdpbundlegroup.h" #define OBJECT_NAME "sdpbundlegroup" GST_DEBUG_CATEGORY_STATIC (kms_sdp_bundle_group_debug_category); #define GST_CAT_DEFAULT kms_sdp_bundle_group_debug_category #define parent_class kms_sdp_bundle_group_parent_class G_DEFINE_TYPE_WITH_CODE (KmsSdpBundleGroup, kms_sdp_bundle_group, KMS_TYPE_SDP_BASE_GROUP, GST_DEBUG_CATEGORY_INIT (kms_sdp_bundle_group_debug_category, OBJECT_NAME, 0, "debug category for sdp bundle_group")); #define KMS_SDP_BUNDLE_GROUP_GET_PRIVATE(obj) ( \ G_TYPE_INSTANCE_GET_PRIVATE ( \ (obj), \ KMS_TYPE_SDP_BUNDLE_GROUP, \ KmsSdpBundleGroupPrivate \ ) \ ) #define KMS_SDP_BUNDLE_GROUP_SEMANTICS "BUNDLE" struct _KmsSdpBundleGroupPrivate { gchar *semantics; }; static void kms_sdp_bundle_group_finalize (GObject * object) { KmsSdpBundleGroup *self = KMS_SDP_BUNDLE_GROUP (object); GST_DEBUG_OBJECT (self, "finalize"); G_OBJECT_CLASS (parent_class)->finalize (object); } static gboolean kms_sdp_bundle_group_add_media_handler (KmsSdpBaseGroup * grp, KmsSdpHandler * handler, GError ** error) { /* Allow to add this media to this group only if this is not in other group */ if (g_slist_length (handler->groups) > 0) { return FALSE; } return KMS_SDP_BASE_GROUP_CLASS (parent_class)->add_media_handler (grp, handler, error); } static gboolean kms_sdp_bundle_group_add_offer_attributes_impl (KmsSdpBaseGroup * self, GstSDPMessage * offer, GError ** error) { if (gst_sdp_message_get_attribute_val (offer, "group") != NULL) { /* FIXME: Old API still inserts group attributes, do not insert here */ /* until we remove it once and for all */ /* TODO: Check if group is bundle and if there are the same handlers in it */ return TRUE; } return KMS_SDP_BASE_GROUP_CLASS (parent_class)->add_offer_attributes (self, offer, error); } static void kms_sdp_bundle_group_class_init (KmsSdpBundleGroupClass * klass) { KmsSdpBaseGroupClass *base_group_class; GObjectClass *gobject_class; gobject_class = G_OBJECT_CLASS (klass); gobject_class->finalize = kms_sdp_bundle_group_finalize; base_group_class = KMS_SDP_BASE_GROUP_CLASS (klass); base_group_class->add_offer_attributes = kms_sdp_bundle_group_add_offer_attributes_impl; base_group_class->add_media_handler = kms_sdp_bundle_group_add_media_handler; g_type_class_add_private (klass, sizeof (KmsSdpBundleGroupPrivate)); } static void kms_sdp_bundle_group_init (KmsSdpBundleGroup * self) { self->priv = KMS_SDP_BUNDLE_GROUP_GET_PRIVATE (self); g_object_set (self, "pre-media-processing", FALSE, NULL); g_object_set (self, "semantics", KMS_SDP_BUNDLE_GROUP_SEMANTICS, NULL); } KmsSdpBundleGroup * kms_sdp_bundle_group_new () { KmsSdpBundleGroup *obj; obj = KMS_SDP_BUNDLE_GROUP (g_object_new (KMS_TYPE_SDP_BUNDLE_GROUP, "semantics", KMS_SDP_BUNDLE_GROUP_SEMANTICS, NULL)); return obj; }
bjxagu/kms-core
src/gst-plugins/commons/sdpagent/kmssdpconnectionext.c
<gh_stars>0 /* * (C) Copyright 2016 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <string.h> #include "kmssdpconnectionext.h" #include "kmsisdpmediaextension.h" #include "kms-sdp-agent-marshal.h" #define OBJECT_NAME "srcspecattrext" GST_DEBUG_CATEGORY_STATIC (kms_connection_ext_debug_category); #define GST_CAT_DEFAULT kms_connection_ext_debug_category #define parent_class kms_connection_ext_parent_class #define KMS_RESERVED_CONNECTION_SIZE 10 static void kms_i_sdp_media_extension_init (KmsISdpMediaExtensionInterface * iface); G_DEFINE_TYPE_WITH_CODE (KmsConnectionExt, kms_connection_ext, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE (KMS_TYPE_I_SDP_MEDIA_EXTENSION, kms_i_sdp_media_extension_init) GST_DEBUG_CATEGORY_INIT (kms_connection_ext_debug_category, OBJECT_NAME, 0, "debug category for sdp sdes_ext")); enum { SIGNAL_ON_ANSWER_IPS, SIGNAL_ON_OFFER_IPS, SIGNAL_ON_ANSWERED_IPS, LAST_SIGNAL }; static guint obj_signals[LAST_SIGNAL] = { 0 }; static void kms_connection_ext_class_init (KmsConnectionExtClass * klass) { obj_signals[SIGNAL_ON_ANSWER_IPS] = g_signal_new ("on-answer-ips", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (KmsConnectionExtClass, on_answer_ips), NULL, NULL, __kms_sdp_agent_marshal_VOID__BOXED_BOXED, G_TYPE_NONE, 2, G_TYPE_ARRAY, G_TYPE_ARRAY); obj_signals[SIGNAL_ON_OFFER_IPS] = g_signal_new ("on-offer-ips", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (KmsConnectionExtClass, on_offer_ips), NULL, NULL, g_cclosure_marshal_VOID__BOXED, G_TYPE_NONE, 1, G_TYPE_ARRAY); obj_signals[SIGNAL_ON_ANSWERED_IPS] = g_signal_new ("on-answered-ips", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (KmsConnectionExtClass, on_answered_ips), NULL, NULL, g_cclosure_marshal_VOID__BOXED, G_TYPE_NONE, 1, G_TYPE_ARRAY); } static void kms_connection_ext_init (KmsConnectionExt * self) { /* Nothing to do */ } static void kms_connection_attr_ext_add_ips (KmsISdpMediaExtension * ext, GstSDPMedia * media, GArray * ips) { gint i; for (i = 0; i < ips->len; i++) { gchar *nettype, *addrtype, *address; guint ttl, addr_number; const GstStructure *addr; GValue *val; val = &g_array_index (ips, GValue, i); if (!GST_VALUE_HOLDS_STRUCTURE (val)) { GST_WARNING_OBJECT (ext, "Inavalid address provided"); continue; } addr = gst_value_get_structure (val); nettype = addrtype = address = NULL; if (gst_structure_get (addr, "nettype", G_TYPE_STRING, &nettype, "addrtype", G_TYPE_STRING, &addrtype, "address", G_TYPE_STRING, &address, "ttl", G_TYPE_UINT, &ttl, "addrnumber", G_TYPE_UINT, &addr_number, NULL)) { gst_sdp_media_add_connection (media, nettype, addrtype, address, ttl, addr_number); } g_free (nettype); g_free (addrtype); g_free (address); } } static void add_address_to_list (GArray * conns, const GstSDPConnection * conn) { GValue val = G_VALUE_INIT; GstStructure *addr; addr = gst_structure_new ("sdp-connection", "nettype", G_TYPE_STRING, conn->nettype, "addrtype", G_TYPE_STRING, conn->addrtype, "address", G_TYPE_STRING, conn->address, "ttl", G_TYPE_UINT, conn->ttl, "addrnumber", G_TYPE_UINT, conn->addr_number, NULL); g_value_init (&val, GST_TYPE_STRUCTURE); gst_value_set_structure (&val, addr); gst_structure_free (addr); g_array_append_val (conns, val); } static void kms_connection_ext_get_connection_attrs (KmsISdpMediaExtension * ext, const GstSDPMedia * media, GArray * conns) { guint i, len; len = gst_sdp_media_connections_len (media); for (i = 0; i < len; i++) { const GstSDPConnection *conn; conn = gst_sdp_media_get_connection (media, i); add_address_to_list (conns, conn); } } static gboolean kms_connection_ext_add_offer_attributes (KmsISdpMediaExtension * ext, GstSDPMedia * offer, GError ** error) { GArray *ips; ips = g_array_sized_new (FALSE, FALSE, sizeof (GValue), KMS_RESERVED_CONNECTION_SIZE); g_array_set_clear_func (ips, (GDestroyNotify) g_value_unset); g_signal_emit (G_OBJECT (ext), obj_signals[SIGNAL_ON_OFFER_IPS], 0, ips); kms_connection_attr_ext_add_ips (ext, offer, ips); g_array_unref (ips); return TRUE; } static gboolean kms_connection_ext_add_answer_attributes (KmsISdpMediaExtension * ext, const GstSDPMedia * offer, GstSDPMedia * answer, GError ** error) { GArray *ips_offered, *ips_answered; ips_offered = g_array_sized_new (FALSE, FALSE, sizeof (GValue), KMS_RESERVED_CONNECTION_SIZE); ips_answered = g_array_sized_new (FALSE, FALSE, sizeof (GValue), KMS_RESERVED_CONNECTION_SIZE); g_array_set_clear_func (ips_offered, (GDestroyNotify) g_value_unset); g_array_set_clear_func (ips_answered, (GDestroyNotify) g_value_unset); kms_connection_ext_get_connection_attrs (ext, offer, ips_offered); g_signal_emit (G_OBJECT (ext), obj_signals[SIGNAL_ON_ANSWER_IPS], 0, ips_offered, ips_answered); kms_connection_attr_ext_add_ips (ext, answer, ips_answered); g_array_unref (ips_offered); g_array_unref (ips_answered); return TRUE; } static gboolean kms_connection_ext_can_insert_attribute (KmsISdpMediaExtension * ext, const GstSDPMedia * offer, const GstSDPAttribute * attr, GstSDPMedia * answer, SdpMessageContext * ctx) { /* No special management of attributes are required. We leave other */ /* plugin to decide if attributes are going to be added to the answer */ return FALSE; } static gboolean kms_connection_ext_process_answer_attributes (KmsISdpMediaExtension * ext, const GstSDPMedia * answer, GError ** error) { GArray *ips; ips = g_array_sized_new (FALSE, FALSE, sizeof (GValue), KMS_RESERVED_CONNECTION_SIZE); g_array_set_clear_func (ips, (GDestroyNotify) g_value_unset); kms_connection_ext_get_connection_attrs (ext, answer, ips); g_signal_emit (G_OBJECT (ext), obj_signals[SIGNAL_ON_ANSWERED_IPS], 0, ips); g_array_unref (ips); return TRUE; } static void kms_i_sdp_media_extension_init (KmsISdpMediaExtensionInterface * iface) { iface->add_offer_attributes = kms_connection_ext_add_offer_attributes; iface->add_answer_attributes = kms_connection_ext_add_answer_attributes; iface->can_insert_attribute = kms_connection_ext_can_insert_attribute; iface->process_answer_attributes = kms_connection_ext_process_answer_attributes; } KmsConnectionExt * kms_connection_ext_new () { gpointer obj; obj = g_object_new (KMS_TYPE_CONNECTION_EXT, NULL); return KMS_CONNECTION_EXT (obj); }
bjxagu/kms-core
src/gst-plugins/kmsbitratefilter.c
<reponame>bjxagu/kms-core /* * (C) Copyright 2013 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include "kmsbitratefilter.h" #include <commons/kmsutils.h> #define PLUGIN_NAME "bitratefilter" #define GST_CAT_DEFAULT kms_bitrate_filter_debug GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define kms_bitrate_filter_parent_class parent_class G_DEFINE_TYPE (KmsBitrateFilter, kms_bitrate_filter, GST_TYPE_BASE_TRANSFORM); #define KMS_BITRATE_FILTER_GET_PRIVATE(obj) ( \ G_TYPE_INSTANCE_GET_PRIVATE ( \ (obj), \ KMS_TYPE_BITRATE_FILTER, \ KmsBitrateFilterPrivate \ ) \ ) #define BITRATE_CALC_INTERVAL GST_SECOND #define BITRATE_CALC_THRESHOLD 100000 /* bps */ typedef struct _KmsBitrateCalcData { GQueue /*GstClockTime */ * pts_queue; GQueue /*gsize */ * sizes_queue; guint64 total_size; gint bitrate, last_bitrate; /* bps */ } KmsBitrateCalcData; struct _KmsBitrateFilterPrivate { KmsBitrateCalcData bitrate_calc_data; }; static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS_ANY); static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS_ANY); static void kms_bitrate_calc_data_clear (KmsBitrateCalcData * data) { if (data == NULL) { return; } g_queue_free_full (data->pts_queue, (GDestroyNotify) kms_utils_destroy_guint64); g_queue_free (data->sizes_queue); } static void kms_bitrate_calc_data_init (KmsBitrateCalcData * data) { data->pts_queue = g_queue_new (); data->sizes_queue = g_queue_new (); } static void kms_bitrate_calc_data_update (KmsBitrateCalcData * data, GstBuffer * buffer) { gsize size; guint64 *current_pts, *last_pts, diff; current_pts = g_slice_new0 (guint64); *current_pts = buffer->pts; g_queue_push_head (data->pts_queue, current_pts); size = gst_buffer_get_size (buffer); g_queue_push_head (data->sizes_queue, GSIZE_TO_POINTER (size)); data->total_size += size; /* Remove old buffers */ last_pts = (guint64 *) g_queue_peek_tail (data->pts_queue); diff = *current_pts - *last_pts; while (diff > BITRATE_CALC_INTERVAL) { gpointer p; p = g_queue_pop_tail (data->pts_queue); kms_utils_destroy_guint64 (p); p = g_queue_pop_tail (data->sizes_queue); data->total_size -= GPOINTER_TO_SIZE (p); last_pts = (guint64 *) g_queue_peek_tail (data->pts_queue); diff = *current_pts - *last_pts; } if (diff == 0) { data->bitrate = 0; } else { data->bitrate = (8 * GST_SECOND * data->total_size) / diff; } } static GstFlowReturn kms_bitrate_filter_transform_ip (GstBaseTransform * base, GstBuffer * buf) { /* No actual work here. It's all done in the prepare output buffer func */ return GST_FLOW_OK; } static void kms_bitrate_filter_update_src_caps (KmsBitrateFilter * self) { GstBaseTransform *trans = GST_BASE_TRANSFORM (self); KmsBitrateCalcData *data = &self->priv->bitrate_calc_data; GstCaps *caps; if (ABS (data->bitrate - data->last_bitrate) < BITRATE_CALC_THRESHOLD) { return; } caps = gst_pad_get_current_caps (trans->srcpad); if (caps == NULL) { return; } data->last_bitrate = data->bitrate; GST_DEBUG_OBJECT (trans, "Old caps: %" GST_PTR_FORMAT, caps); caps = gst_caps_make_writable (caps); gst_caps_set_simple (caps, "bitrate", G_TYPE_INT, data->bitrate, NULL); gst_pad_set_caps (trans->srcpad, caps); GST_DEBUG_OBJECT (trans, "New caps: %" GST_PTR_FORMAT, caps); gst_caps_unref (caps); } static GstFlowReturn kms_bitrate_filter_prepare_buf (GstBaseTransform * trans, GstBuffer * input, GstBuffer ** buf) { KmsBitrateFilter *self = KMS_BITRATE_FILTER (trans); KmsBitrateCalcData *data = &self->priv->bitrate_calc_data; /* always return the input as output buffer */ *buf = input; kms_bitrate_calc_data_update (data, input); kms_bitrate_filter_update_src_caps (self); GST_TRACE_OBJECT (self, "bitrate: %" G_GINT32_FORMAT " bps", data->bitrate); return GST_FLOW_OK; } static void kms_bitrate_filter_dispose (GObject * object) { KmsBitrateFilter *self = KMS_BITRATE_FILTER (object); kms_bitrate_calc_data_clear (&self->priv->bitrate_calc_data); /* chain up */ G_OBJECT_CLASS (kms_bitrate_filter_parent_class)->dispose (object); } static GstCaps * kms_bitrate_filter_transform_caps (GstBaseTransform * base, GstPadDirection direction, GstCaps * caps, GstCaps * filter) { KmsBitrateFilter *self = KMS_BITRATE_FILTER (base); GstCaps *ret; guint caps_size, i; ret = gst_caps_make_writable (gst_caps_ref (caps)); caps_size = gst_caps_get_size (ret); for (i = 0; i < caps_size; i++) { GstStructure *s = gst_caps_get_structure (ret, i); if (GST_PAD_SRC == direction) { gst_structure_remove_field (s, "bitrate"); } else if (GST_PAD_SINK == direction) { gst_structure_set (s, "bitrate", GST_TYPE_INT_RANGE, 0, G_MAXINT32, NULL); } } GST_DEBUG_OBJECT (self, "Input caps: %" GST_PTR_FORMAT, caps); GST_DEBUG_OBJECT (self, "Filter: %" GST_PTR_FORMAT, filter); GST_DEBUG_OBJECT (self, "Old caps: %" GST_PTR_FORMAT, caps); GST_DEBUG_OBJECT (self, "Output caps: %" GST_PTR_FORMAT, ret); return ret; } static void kms_bitrate_filter_init (KmsBitrateFilter * self) { self->priv = KMS_BITRATE_FILTER_GET_PRIVATE (self); kms_bitrate_calc_data_init (&self->priv->bitrate_calc_data); } static void kms_bitrate_filter_class_init (KmsBitrateFilterClass * klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass); GstBaseTransformClass *trans_class = GST_BASE_TRANSFORM_CLASS (klass); gobject_class->dispose = kms_bitrate_filter_dispose; gst_element_class_set_details_simple (gstelement_class, "BitrateFilter", "Generic", "Pass data without modification, managing bitrate caps.", "<NAME> <<EMAIL>>"); gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&srctemplate)); gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&sinktemplate)); trans_class->transform_ip = GST_DEBUG_FUNCPTR (kms_bitrate_filter_transform_ip); trans_class->prepare_output_buffer = GST_DEBUG_FUNCPTR (kms_bitrate_filter_prepare_buf); trans_class->transform_caps = GST_DEBUG_FUNCPTR (kms_bitrate_filter_transform_caps); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, PLUGIN_NAME, 0, PLUGIN_NAME); g_type_class_add_private (klass, sizeof (KmsBitrateFilterPrivate)); } gboolean kms_bitrate_filter_plugin_init (GstPlugin * plugin) { return gst_element_register (plugin, PLUGIN_NAME, GST_RANK_NONE, KMS_TYPE_BITRATE_FILTER); }
bjxagu/kms-core
src/gst-plugins/commons/kmsbasertpsession.c
/* * (C) Copyright 2015 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include "kmsbasertpsession.h" #include "constants.h" #include "kmsutils.h" #include "sdp_utils.h" #include "kms-core-enumtypes.h" #include "kms-core-marshal.h" #define GST_DEFAULT_NAME "kmsbasertpsession" #define GST_CAT_DEFAULT kms_base_rtp_session_debug GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define kms_base_rtp_session_parent_class parent_class G_DEFINE_TYPE (KmsBaseRtpSession, kms_base_rtp_session, KMS_TYPE_SDP_SESSION); #define BUNDLE_CONN_ADDED "bundle-conn-added" G_DEFINE_QUARK (BUNDLE_CONN_ADDED, bundle_conn_added); #define RTCP_DEMUX_PEER "rtcp-demux-peer" G_DEFINE_QUARK (RTCP_DEMUX_PEER, rtcp_demux_peer); struct _KmsBaseRTPSessionStats { gboolean enabled; gdouble vi; gdouble ai; }; enum { CONNECTION_STATE_CHANGED, LAST_SIGNAL }; static guint obj_signals[LAST_SIGNAL] = { 0 }; #define DEFAULT_CONNECTION_STATE KMS_CONNECTION_STATE_DISCONNECTED enum { PROP_0, PROP_CONNECTION_STATE }; KmsBaseRtpSession * kms_base_rtp_session_new (KmsBaseSdpEndpoint * ep, guint id, KmsIRtpSessionManager * manager) { GObject *obj; KmsBaseRtpSession *self; obj = g_object_new (KMS_TYPE_BASE_RTP_SESSION, NULL); self = KMS_BASE_RTP_SESSION (obj); KMS_BASE_RTP_SESSION_CLASS (G_OBJECT_GET_CLASS (self))->post_constructor (self, ep, id, manager); return self; } /* Connection management begin */ KmsIRtpConnection * kms_base_rtp_session_get_connection_by_name (KmsBaseRtpSession * self, const gchar * name) { gpointer *conn; conn = g_hash_table_lookup (self->conns, name); if (conn == NULL) { return NULL; } return KMS_I_RTP_CONNECTION (conn); } KmsIRtpConnection * kms_base_rtp_session_get_connection (KmsBaseRtpSession * self, SdpMediaConfig * mconf) { gchar *name = kms_utils_create_connection_name_from_media_config (mconf); KmsIRtpConnection *conn; conn = kms_base_rtp_session_get_connection_by_name (self, name); if (conn == NULL) { GST_WARNING_OBJECT (self, "Connection '%s' not found", name); g_free (name); return NULL; } g_free (name); return conn; } static KmsIRtpConnection * kms_base_rtp_session_create_connection_default (KmsBaseRtpSession * self, SdpMediaConfig * mconf, const gchar * name, guint16 min_port, guint16 max_port) { KmsBaseRtpSessionClass *klass = KMS_BASE_RTP_SESSION_CLASS (G_OBJECT_GET_CLASS (self)); if (klass->create_connection == kms_base_rtp_session_create_connection_default) { GST_WARNING_OBJECT (self, "%s does not reimplement 'create_connection'", G_OBJECT_CLASS_NAME (klass)); } return NULL; } static KmsIRtcpMuxConnection * kms_base_rtp_session_create_rtcp_mux_connection_default (KmsBaseRtpSession * self, const gchar * name, guint16 min_port, guint16 max_port) { KmsBaseRtpSessionClass *klass = KMS_BASE_RTP_SESSION_CLASS (G_OBJECT_GET_CLASS (self)); if (klass->create_rtcp_mux_connection == kms_base_rtp_session_create_rtcp_mux_connection_default) { GST_WARNING_OBJECT (self, "%s does not reimplement 'create_rtcp_mux_connection'", G_OBJECT_CLASS_NAME (klass)); } return NULL; } static KmsIBundleConnection * kms_base_rtp_session_create_bundle_connection_default (KmsBaseRtpSession * self, const gchar * name, guint16 min_port, guint16 max_port) { KmsBaseRtpSessionClass *klass = KMS_BASE_RTP_SESSION_CLASS (G_OBJECT_GET_CLASS (self)); if (klass->create_bundle_connection == kms_base_rtp_session_create_bundle_connection_default) { GST_WARNING_OBJECT (self, "%s does not reimplement 'create_bundle_connection'", G_OBJECT_CLASS_NAME (klass)); } return NULL; } static void kms_base_rtp_session_e2e_latency_cb (GstPad * pad, KmsMediaType type, GstClockTimeDiff t, KmsList * mdata, gpointer user_data) { KmsBaseRtpSession *self = KMS_BASE_RTP_SESSION (user_data); KmsListIter iter; gpointer key, value; gchar *name; name = gst_element_get_name (KMS_SDP_SESSION (self)->ep); kms_list_iter_init (&iter, mdata); while (kms_list_iter_next (&iter, &key, &value)) { gchar *id = (gchar *) key; StreamE2EAvgStat *stat; if (!g_str_has_prefix (id, name)) { /* This element did not add this mark to the metada */ continue; } stat = (StreamE2EAvgStat *) value; stat->avg = KMS_STATS_CALCULATE_LATENCY_AVG (t, stat->avg); } } static void kms_base_rtp_session_set_connection_stats (KmsBaseRtpSession * self, KmsIRtpConnection * conn) { kms_i_rtp_connection_set_latency_callback (conn, kms_base_rtp_session_e2e_latency_cb, self); /* Active insertion of metadata if stats are enabled */ kms_i_rtp_connection_collect_latency_stats (conn, self->stats_enabled); } KmsIRtpConnection * kms_base_rtp_session_create_connection (KmsBaseRtpSession * self, SdpMediaConfig * mconf, guint16 min_port, guint16 max_port) { KmsBaseRtpSessionClass *base_rtp_class = KMS_BASE_RTP_SESSION_CLASS (G_OBJECT_GET_CLASS (self)); gchar *name = kms_utils_create_connection_name_from_media_config (mconf); SdpMediaGroup *group = kms_sdp_media_config_get_group (mconf); KmsIRtpConnection *conn; conn = kms_base_rtp_session_get_connection_by_name (self, name); if (conn != NULL) { GST_DEBUG_OBJECT (self, "Re-using connection '%s'", name); goto end; } if (group != NULL) { /* bundle */ conn = KMS_I_RTP_CONNECTION (base_rtp_class->create_bundle_connection (self, name, min_port, max_port)); } else if (kms_sdp_media_config_is_rtcp_mux (mconf)) { conn = KMS_I_RTP_CONNECTION (base_rtp_class->create_rtcp_mux_connection (self, name, min_port, max_port)); } else { conn = base_rtp_class->create_connection (self, mconf, name, min_port, max_port); } if (conn != NULL) { g_hash_table_insert (self->conns, g_strdup (name), conn); kms_base_rtp_session_set_connection_stats (self, conn); } end: g_free (name); return conn; } /* Connection management end */ /* Start Transport Send begin */ static gboolean ssrcs_are_mapped (GstElement * ssrcdemux, guint32 local_ssrc, guint32 remote_ssrc) { GstElement *rtcpdemux = g_object_get_qdata (G_OBJECT (ssrcdemux), rtcp_demux_peer_quark ()); guint local_ssrc_pair; g_signal_emit_by_name (rtcpdemux, "get-local-rr-ssrc-pair", remote_ssrc, &local_ssrc_pair); return ((local_ssrc != 0) && (local_ssrc_pair == local_ssrc)); } static void kms_base_rtp_session_link_pads (GstPad * src, GstPad * sink) { GstPadLinkReturn ret; ret = gst_pad_link_full (src, sink, GST_PAD_LINK_CHECK_CAPS); if (ret != GST_PAD_LINK_OK) { GST_ERROR ("Error linking pads (src: %" GST_PTR_FORMAT ", sink: %" GST_PTR_FORMAT "), ret: '%s'", src, sink, gst_pad_link_get_name (ret)); } } static void rtp_ssrc_demux_new_ssrc_pad (GstElement * ssrcdemux, guint ssrc, GstPad * pad, KmsBaseRtpSession * self) { const gchar *rtp_pad_name = GST_OBJECT_NAME (pad); gchar *rtcp_pad_name; SdpMediaConfig *mconf; GstPad *src, *sink; GST_DEBUG_OBJECT (self, "pad: %" GST_PTR_FORMAT " ssrc: %" G_GUINT32_FORMAT, pad, ssrc); KMS_SDP_SESSION_LOCK (self); if (self->remote_audio_ssrc == ssrc || ssrcs_are_mapped (ssrcdemux, self->local_audio_ssrc, ssrc)) { mconf = self->audio_neg_mconf; } else if (self->remote_video_ssrc == ssrc || ssrcs_are_mapped (ssrcdemux, self->local_video_ssrc, ssrc)) { mconf = self->video_neg_mconf; } else { if (!kms_i_rtp_session_manager_custom_ssrc_management (self->manager, self, ssrcdemux, ssrc, pad)) { GST_ERROR_OBJECT (pad, "SSRC %" G_GUINT32_FORMAT " not matching.", ssrc); } goto end; } /* RTP */ sink = kms_i_rtp_session_manager_request_rtp_sink (self->manager, self, mconf); kms_base_rtp_session_link_pads (pad, sink); g_object_unref (sink); /* RTCP */ rtcp_pad_name = g_strconcat ("rtcp_", rtp_pad_name, NULL); src = gst_element_get_static_pad (ssrcdemux, rtcp_pad_name); g_free (rtcp_pad_name); sink = kms_i_rtp_session_manager_request_rtcp_sink (self->manager, self, mconf); kms_base_rtp_session_link_pads (src, sink); g_object_unref (src); g_object_unref (sink); end: KMS_SDP_SESSION_UNLOCK (self); } static void kms_base_rtp_session_add_bundle_connection (KmsBaseRtpSession * self, KmsIRtpConnection * conn, SdpMediaConfig * mconf, gboolean active) { gboolean added; GstElement *ssrcdemux; GstElement *rtcpdemux; /* FIXME: Useful for local and remote ssrcs mapping */ GstPad *src, *sink; if (GPOINTER_TO_UINT (g_object_get_qdata (G_OBJECT (conn), bundle_conn_added_quark ()))) { GST_DEBUG_OBJECT (self, "Connection configured"); return; } g_object_set_qdata (G_OBJECT (conn), bundle_conn_added_quark (), GUINT_TO_POINTER (TRUE)); g_object_get (conn, "added", &added, NULL); if (!added) { kms_i_rtp_connection_add (conn, GST_BIN (self), active); } ssrcdemux = gst_element_factory_make ("rtpssrcdemux", NULL); rtcpdemux = gst_element_factory_make ("rtcpdemux", NULL); g_object_set_qdata_full (G_OBJECT (ssrcdemux), rtcp_demux_peer_quark (), g_object_ref (rtcpdemux), g_object_unref); g_signal_connect (ssrcdemux, "new-ssrc-pad", G_CALLBACK (rtp_ssrc_demux_new_ssrc_pad), self); kms_i_rtp_connection_sink_sync_state_with_parent (conn); gst_bin_add_many (GST_BIN (self), ssrcdemux, rtcpdemux, NULL); /* RTP */ src = kms_i_rtp_connection_request_rtp_src (conn); sink = gst_element_get_static_pad (ssrcdemux, "sink"); kms_base_rtp_session_link_pads (src, sink); g_object_unref (src); g_object_unref (sink); /* RTCP */ src = kms_i_rtp_connection_request_rtcp_src (conn); sink = gst_element_get_static_pad (rtcpdemux, "sink"); kms_base_rtp_session_link_pads (src, sink); g_object_unref (src); g_object_unref (sink); gst_element_link_pads (rtcpdemux, "rtcp_src", ssrcdemux, "rtcp_sink"); gst_element_sync_state_with_parent_target_state (ssrcdemux); gst_element_sync_state_with_parent_target_state (rtcpdemux); kms_i_rtp_connection_src_sync_state_with_parent (conn); } static void kms_base_rtp_session_add_connection_sink (KmsBaseRtpSession * self, KmsIRtpConnection * conn, SdpMediaConfig * mconf) { GstPad *src, *sink; /* RTP */ src = kms_i_rtp_session_manager_request_rtp_src (self->manager, self, mconf); sink = kms_i_rtp_connection_request_rtp_sink (conn); kms_base_rtp_session_link_pads (src, sink); g_object_unref (src); g_object_unref (sink); /* RTCP */ src = kms_i_rtp_session_manager_request_rtcp_src (self->manager, self, mconf); sink = kms_i_rtp_connection_request_rtcp_sink (conn); kms_base_rtp_session_link_pads (src, sink); g_object_unref (src); g_object_unref (sink); } static void kms_base_rtp_session_add_connection_src (KmsBaseRtpSession * self, KmsIRtpConnection * conn, SdpMediaConfig * mconf) { GstPad *src, *sink; /* RTP */ sink = kms_i_rtp_session_manager_request_rtp_sink (self->manager, self, mconf); src = kms_i_rtp_connection_request_rtp_src (conn); kms_base_rtp_session_link_pads (src, sink); g_object_unref (src); g_object_unref (sink); /* RTCP */ sink = kms_i_rtp_session_manager_request_rtcp_sink (self->manager, self, mconf); src = kms_i_rtp_connection_request_rtcp_src (conn); kms_base_rtp_session_link_pads (src, sink); g_object_unref (src); g_object_unref (sink); } static void kms_base_rtp_session_add_rtcp_mux_connection (KmsBaseRtpSession * self, KmsIRtpConnection * conn, SdpMediaConfig * mconf, gboolean active) { /* FIXME: Useful for local and remote ssrcs mapping */ GstElement *rtcpdemux = gst_element_factory_make ("rtcpdemux", NULL); GstPad *src, *sink; kms_i_rtp_connection_add (conn, GST_BIN (self), active); kms_i_rtp_connection_sink_sync_state_with_parent (conn); gst_bin_add (GST_BIN (self), rtcpdemux); /* RTP */ src = kms_i_rtp_connection_request_rtp_src (conn); sink = kms_i_rtp_session_manager_request_rtp_sink (self->manager, self, mconf); kms_base_rtp_session_link_pads (src, sink); g_object_unref (src); g_object_unref (sink); /* RTCP */ src = gst_element_get_static_pad (rtcpdemux, "rtcp_src"); sink = kms_i_rtp_session_manager_request_rtcp_sink (self->manager, self, mconf); g_object_unref (src); g_object_unref (sink); src = kms_i_rtp_connection_request_rtcp_src (conn); sink = gst_element_get_static_pad (rtcpdemux, "sink"); kms_base_rtp_session_link_pads (src, sink); g_object_unref (src); g_object_unref (sink); gst_element_sync_state_with_parent_target_state (rtcpdemux); kms_base_rtp_session_add_connection_sink (self, conn, mconf); kms_i_rtp_connection_src_sync_state_with_parent (conn); } static void kms_base_rtp_session_add_connection (KmsBaseRtpSession * self, KmsIRtpConnection * conn, SdpMediaConfig * mconf, gboolean active) { kms_i_rtp_connection_add (conn, GST_BIN (self), active); kms_i_rtp_connection_sink_sync_state_with_parent (conn); kms_base_rtp_session_add_connection_sink (self, conn, mconf); kms_base_rtp_session_add_connection_src (self, conn, mconf); kms_i_rtp_connection_src_sync_state_with_parent (conn); } static gboolean kms_base_rtp_session_add_connection_for_session (KmsBaseRtpSession * self, SdpMediaConfig * mconf, gboolean active) { KmsIRtpConnection *conn; SdpMediaGroup *group = kms_sdp_media_config_get_group (mconf); conn = kms_base_rtp_session_get_connection (self, mconf); if (conn == NULL) { return FALSE; } if (group != NULL) { /* bundle */ kms_base_rtp_session_add_bundle_connection (self, conn, mconf, active); kms_base_rtp_session_add_connection_sink (self, conn, mconf); } else if (kms_sdp_media_config_is_rtcp_mux (mconf)) { kms_base_rtp_session_add_rtcp_mux_connection (self, conn, mconf, active); } else { kms_base_rtp_session_add_connection (self, conn, mconf, active); } return TRUE; } static const gchar * kms_base_rtp_session_process_remote_ssrc (KmsBaseRtpSession * self, GstSDPMedia * remote_media, SdpMediaConfig * neg_mconf) { const gchar *media_str = gst_sdp_media_get_media (remote_media); guint ssrc; ssrc = sdp_utils_media_get_fid_ssrc (remote_media, 0); if (ssrc == 0) { ssrc = sdp_utils_media_get_ssrc (remote_media); } if (g_strcmp0 (AUDIO_STREAM_NAME, media_str) == 0) { GST_DEBUG_OBJECT (self, "Add remote audio ssrc: %u", ssrc); self->remote_audio_ssrc = ssrc; self->audio_neg_mconf = neg_mconf; return AUDIO_RTP_SESSION_STR; } else if (g_strcmp0 (VIDEO_STREAM_NAME, media_str) == 0) { GST_DEBUG_OBJECT (self, "Add remote video ssrc: %u", ssrc); self->remote_video_ssrc = ssrc; self->video_neg_mconf = neg_mconf; return VIDEO_RTP_SESSION_STR; } GST_WARNING_OBJECT (self, "Media '%s' not supported", media_str); return NULL; } static gboolean kms_base_rtp_session_configure_connection (KmsBaseRtpSession * self, SdpMediaConfig * neg_mconf, SdpMediaConfig * remote_mconf, gboolean offerer) { GstSDPMedia *neg_media = kms_sdp_media_config_get_sdp_media (neg_mconf); const gchar *neg_proto_str = gst_sdp_media_get_proto (neg_media); const gchar *neg_media_str = gst_sdp_media_get_media (neg_media); GstSDPMedia *remote_media = kms_sdp_media_config_get_sdp_media (remote_mconf); const gchar *remote_proto_str = gst_sdp_media_get_proto (remote_media); const gchar *remote_media_str = gst_sdp_media_get_media (remote_media); gboolean active; if (g_strcmp0 (neg_proto_str, remote_proto_str) != 0) { GST_WARNING_OBJECT (self, "Negotiated proto ('%s') not matching with remote proto ('%s')", neg_proto_str, remote_proto_str); return FALSE; } if (!kms_utils_contains_proto (neg_proto_str, "RTP")) { GST_DEBUG_OBJECT (self, "'%s' protocol does not need RTP connection", neg_proto_str); /* It cannot be managed here but could be managed by the child class */ return FALSE; } if (g_strcmp0 (neg_media_str, remote_media_str) != 0) { GST_WARNING_OBJECT (self, "Negotiated media ('%s') not matching with remote media ('%s')", neg_media_str, remote_media_str); return FALSE; } if (kms_base_rtp_session_process_remote_ssrc (self, remote_media, neg_mconf) == NULL) { return TRUE; /* It cannot be managed here but could be managed by the child class */ } active = sdp_utils_media_is_active (neg_media, offerer); return kms_base_rtp_session_add_connection_for_session (self, neg_mconf, active); } static void kms_base_rtp_session_update_conn_state (KmsBaseRtpSession * self) { GHashTableIter iter; gpointer key, v; gboolean emit = FALSE; KmsConnectionState new_state = KMS_CONNECTION_STATE_CONNECTED; KMS_SDP_SESSION_LOCK (self); g_hash_table_iter_init (&iter, self->conns); while (g_hash_table_iter_next (&iter, &key, &v)) { KmsIRtpConnection *conn = KMS_I_RTP_CONNECTION (v); gboolean connected; g_object_get (conn, "connected", &connected, NULL); if (!connected) { new_state = KMS_CONNECTION_STATE_DISCONNECTED; break; } } if (self->conn_state != new_state) { GST_DEBUG_OBJECT (self, "Connection state changed to '%d'", new_state); self->conn_state = new_state; emit = TRUE; } KMS_SDP_SESSION_UNLOCK (self); if (emit) { g_signal_emit (G_OBJECT (self), obj_signals[CONNECTION_STATE_CHANGED], 0, new_state); } } static void kms_base_rtp_session_connected_cb (KmsIRtpConnection * conn, gpointer user_data) { KmsBaseRtpSession *self = KMS_BASE_RTP_SESSION (user_data); kms_base_rtp_session_update_conn_state (self); } static void kms_base_rtp_session_check_conn_status (KmsBaseRtpSession * self) { GHashTableIter iter; gpointer key, v; KMS_SDP_SESSION_LOCK (self); g_hash_table_iter_init (&iter, self->conns); while (g_hash_table_iter_next (&iter, &key, &v)) { KmsIRtpConnection *conn = KMS_I_RTP_CONNECTION (v); g_signal_connect_data (conn, "connected", G_CALLBACK (kms_base_rtp_session_connected_cb), self, NULL, 0); } KMS_SDP_SESSION_UNLOCK (self); kms_base_rtp_session_update_conn_state (self); } void kms_base_rtp_session_start_transport_send (KmsBaseRtpSession * self, gboolean offerer) { KmsSdpSession *sdp_sess = KMS_SDP_SESSION (self); GSList *item = kms_sdp_message_context_get_medias (sdp_sess->neg_sdp_ctx); GSList *remote_media_list = kms_sdp_message_context_get_medias (sdp_sess->remote_sdp_ctx); kms_base_rtp_session_check_conn_status (self); for (; item != NULL; item = g_slist_next (item)) { SdpMediaConfig *neg_mconf = item->data; gint mid = kms_sdp_media_config_get_id (neg_mconf); SdpMediaConfig *remote_mconf; if (kms_sdp_media_config_is_inactive (neg_mconf)) { GST_DEBUG_OBJECT (self, "Media (id=%d) inactive", mid); continue; } remote_mconf = g_slist_nth_data (remote_media_list, mid); if (remote_mconf == NULL) { GST_WARNING_OBJECT (self, "Media (id=%d) is not in the remote SDP", mid); continue; } if (!kms_base_rtp_session_configure_connection (self, neg_mconf, remote_mconf, offerer)) { GST_WARNING_OBJECT (self, "Cannot configure connection for media %d.", mid); } } } /* Start Transport Send end */ static void kms_base_rtp_session_enable_connection_stats (gpointer key, gpointer value, gpointer user_data) { kms_i_rtp_connection_collect_latency_stats (KMS_I_RTP_CONNECTION (value), TRUE); } static void kms_base_rtp_session_disable_connection_stats (gpointer key, gpointer value, gpointer user_data) { kms_i_rtp_connection_collect_latency_stats (KMS_I_RTP_CONNECTION (value), FALSE); } void kms_base_rtp_session_enable_connections_stats (KmsBaseRtpSession * self) { self->stats_enabled = TRUE; g_hash_table_foreach (self->conns, kms_base_rtp_session_enable_connection_stats, NULL); } void kms_base_rtp_session_disable_connections_stats (KmsBaseRtpSession * self) { self->stats_enabled = FALSE; g_hash_table_foreach (self->conns, kms_base_rtp_session_disable_connection_stats, NULL); } static void kms_base_rtp_session_get_property (GObject * object, guint property_id, GValue * value, GParamSpec * pspec) { KmsBaseRtpSession *self = KMS_BASE_RTP_SESSION (object); KMS_SDP_SESSION_LOCK (self); switch (property_id) { case PROP_CONNECTION_STATE: g_value_set_enum (value, self->conn_state); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); break; } KMS_SDP_SESSION_UNLOCK (self); } static void kms_base_rtp_session_finalize (GObject * object) { KmsBaseRtpSession *self = KMS_BASE_RTP_SESSION (object); GST_DEBUG_OBJECT (self, "finalize"); g_hash_table_destroy (self->conns); /* chain up */ G_OBJECT_CLASS (kms_base_rtp_session_parent_class)->finalize (object); } static void kms_base_rtp_session_post_constructor (KmsBaseRtpSession * self, KmsBaseSdpEndpoint * ep, guint id, KmsIRtpSessionManager * manager) { KmsSdpSession *sdp_sess = KMS_SDP_SESSION (self); self->manager = manager; KMS_SDP_SESSION_CLASS (kms_base_rtp_session_parent_class)->post_constructor (sdp_sess, ep, id); } static void kms_base_rtp_session_init (KmsBaseRtpSession * self) { self->conns = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref); self->stats_enabled = FALSE; } static void kms_base_rtp_session_class_init (KmsBaseRtpSessionClass * klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); gobject_class->finalize = kms_base_rtp_session_finalize; gobject_class->get_property = kms_base_rtp_session_get_property; klass->post_constructor = kms_base_rtp_session_post_constructor; /* Connection management */ klass->create_connection = kms_base_rtp_session_create_connection_default; klass->create_rtcp_mux_connection = kms_base_rtp_session_create_rtcp_mux_connection_default; klass->create_bundle_connection = kms_base_rtp_session_create_bundle_connection_default; gst_element_class_set_details_simple (gstelement_class, "BaseRtpSession", "Generic", "Base bin to manage elements related with a RTP session.", "<NAME> <<EMAIL>>"); g_object_class_install_property (gobject_class, PROP_CONNECTION_STATE, g_param_spec_enum ("connection-state", "Connection state", "Connection state", KMS_TYPE_CONNECTION_STATE, DEFAULT_CONNECTION_STATE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); obj_signals[CONNECTION_STATE_CHANGED] = g_signal_new ("connection-state-changed", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (KmsBaseRtpSessionClass, connection_state_changed), NULL, NULL, __kms_core_marshal_VOID__STRING_ENUM, G_TYPE_NONE, 1, KMS_TYPE_CONNECTION_STATE); }
bjxagu/kms-core
tests/check/element/audiomixerbin.c
/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gst/check/gstcheck.h> #include <gst/gst.h> #include <glib.h> #ifdef MANUAL_CHECK #define FILE_PREFIX "audiomixerbin_file_" static guint id = 0; #endif static GstElement *pipeline, *audiomixer; static GMainLoop *loop; static gboolean quit_main_loop () { g_main_loop_quit (loop); return G_SOURCE_REMOVE; } static void bus_msg (GstBus * bus, GstMessage * msg, gpointer data) { switch (GST_MESSAGE_TYPE (msg)) { case GST_MESSAGE_ERROR:{ GError *err = NULL; gchar *dbg_info = NULL; gchar *err_str; GST_ERROR ("Error: %" GST_PTR_FORMAT, msg); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "bus_error"); gst_message_parse_error (msg, &err, &dbg_info); err_str = g_strdup_printf ("Error received on bus: %s: %s", err->message, dbg_info); g_error_free (err); g_free (dbg_info); fail (err_str); g_free (err_str); break; } case GST_MESSAGE_STATE_CHANGED:{ GST_TRACE ("Event: %" GST_PTR_FORMAT, msg); break; } case GST_MESSAGE_EOS:{ GST_DEBUG ("Receive EOS"); quit_main_loop (); } default: break; } } static GstElement * create_sink_element () { GstElement *sink; #ifdef MANUAL_CHECK { gchar *filename; filename = g_strdup_printf (FILE_PREFIX "%u.wv", id); GST_DEBUG ("Setting location to %s", filename); sink = gst_element_factory_make ("filesink", NULL); g_object_set (G_OBJECT (sink), "location", filename, NULL); g_free (filename); } #else { sink = gst_element_factory_make ("fakesink", NULL); } #endif return sink; } #ifdef ENABLE_DEBUGGING_TESTS GST_START_TEST (check_audio_connection) { GstElement *audiotestsrc1, *audiotestsrc2, *wavenc, *sink; guint bus_watch_id; GstBus *bus; loop = g_main_loop_new (NULL, FALSE); #ifdef MANUAL_CHECK id = 0; #endif /* Create gstreamer elements */ pipeline = gst_pipeline_new ("audimixerbin0-test"); audiotestsrc1 = gst_element_factory_make ("audiotestsrc", NULL); audiotestsrc2 = gst_element_factory_make ("audiotestsrc", NULL); audiomixer = gst_element_factory_make ("audiomixerbin", NULL); wavenc = gst_element_factory_make ("wavenc", NULL); sink = create_sink_element (); g_object_set (G_OBJECT (audiotestsrc1), "wave", 0, "num-buffers", 100, NULL); g_object_set (G_OBJECT (audiotestsrc2), "wave", 11, "num-buffers", 100, NULL); bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); bus_watch_id = gst_bus_add_watch (bus, gst_bus_async_signal_func, NULL); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); g_object_unref (bus); gst_bin_add_many (GST_BIN (pipeline), audiotestsrc1, audiotestsrc2, audiomixer, wavenc, sink, NULL); gst_element_link (audiotestsrc1, audiomixer); gst_element_link (audiotestsrc2, audiomixer); gst_element_link_many (audiomixer, wavenc, sink, NULL); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "entering_main_loop"); gst_element_set_state (pipeline, GST_STATE_PLAYING); GST_DEBUG ("Test running"); g_main_loop_run (loop); GST_DEBUG ("Stop executed"); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "after_main_loop"); GST_DEBUG ("Setting pipline to NULL state"); gst_element_set_state (pipeline, GST_STATE_NULL); GST_DEBUG ("Releasing pipeline"); gst_object_unref (GST_OBJECT (pipeline)); GST_DEBUG ("Pipeline released"); g_source_remove (bus_watch_id); g_main_loop_unref (loop); } GST_END_TEST; static gboolean connect_audio_source (gpointer data) { GstElement *audiotestsrc2; GST_DEBUG ("Adding audio source 2"); audiotestsrc2 = gst_element_factory_make ("audiotestsrc", NULL); g_object_set (G_OBJECT (audiotestsrc2), "wave", 11, "num-buffers", 100, NULL); gst_bin_add (GST_BIN (pipeline), audiotestsrc2); gst_element_link (audiotestsrc2, audiomixer); gst_element_sync_state_with_parent (audiotestsrc2); return G_SOURCE_REMOVE; } GST_START_TEST (check_delayed_audio_connection) { GstElement *audiotestsrc1, *wavenc, *sink; guint bus_watch_id; GstBus *bus; loop = g_main_loop_new (NULL, FALSE); #ifdef MANUAL_CHECK id = 1; #endif /* Create gstreamer elements */ pipeline = gst_pipeline_new ("audimixerbin1-test"); audiotestsrc1 = gst_element_factory_make ("audiotestsrc", NULL); audiomixer = gst_element_factory_make ("audiomixerbin", NULL); wavenc = gst_element_factory_make ("wavenc", NULL); sink = create_sink_element (); g_object_set (G_OBJECT (audiotestsrc1), "wave", 0, "num-buffers", 100, NULL); bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); bus_watch_id = gst_bus_add_watch (bus, gst_bus_async_signal_func, NULL); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); g_object_unref (bus); gst_bin_add_many (GST_BIN (pipeline), audiotestsrc1, audiomixer, wavenc, sink, NULL); gst_element_link_many (audiotestsrc1, audiomixer, wavenc, sink, NULL); g_timeout_add (1000, connect_audio_source, NULL); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "entering_main_loop"); gst_element_set_state (pipeline, GST_STATE_PLAYING); GST_DEBUG ("Test running"); g_main_loop_run (loop); GST_DEBUG ("Stop executed"); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "after_main_loop"); GST_DEBUG ("Setting pipline to NULL state"); gst_element_set_state (pipeline, GST_STATE_NULL); GST_DEBUG ("Releasing pipeline"); gst_object_unref (GST_OBJECT (pipeline)); GST_DEBUG ("Pipeline released"); g_source_remove (bus_watch_id); g_main_loop_unref (loop); } GST_END_TEST; #endif static gboolean remove_audiotestsrc (GstElement * audiotestsrc) { GstElement *pipeline = GST_ELEMENT (gst_element_get_parent (audiotestsrc)); GST_DEBUG ("Remove element %" GST_PTR_FORMAT, audiotestsrc); gst_object_ref (audiotestsrc); gst_element_set_locked_state (audiotestsrc, TRUE); gst_element_set_state (audiotestsrc, GST_STATE_NULL); if (!gst_bin_remove (GST_BIN (pipeline), audiotestsrc)) GST_ERROR ("Can not remove %" GST_PTR_FORMAT, audiotestsrc); gst_object_unref (pipeline); gst_object_unref (audiotestsrc); return G_SOURCE_REMOVE; } static GstPadProbeReturn unlink_audiotestsrc (GstPad * pad, GstPadProbeInfo * info, gpointer user_data) { GstElement *audiotestsrc = GST_ELEMENT (user_data); GstElement *audiomixer; GstPad *sinkpad; GST_DEBUG ("Blocked %" GST_PTR_FORMAT, pad); sinkpad = gst_pad_get_peer (pad); audiomixer = gst_pad_get_parent_element (sinkpad); if (!gst_pad_unlink (pad, sinkpad)) { GST_ERROR ("Can not unilnk pads"); } GST_INFO ("Releasing pad %" GST_PTR_FORMAT, sinkpad); gst_element_release_request_pad (audiomixer, sinkpad); gst_object_unref (sinkpad); gst_object_unref (audiomixer); g_idle_add ((GSourceFunc) remove_audiotestsrc, audiotestsrc); return GST_PAD_PROBE_OK; } static gboolean block_audiotestsrc (GstElement * audiotestsrc) { GstPad *srcpad; GST_DEBUG ("Blocking %" GST_PTR_FORMAT, audiotestsrc); srcpad = gst_element_get_static_pad (audiotestsrc, "src"); gst_pad_add_probe (srcpad, GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM, unlink_audiotestsrc, audiotestsrc, NULL); gst_object_unref (srcpad); return G_SOURCE_REMOVE; } GST_START_TEST (check_audio_disconnection) { GstElement *audiotestsrc1, *audiotestsrc2, *audiotestsrc3, *wavenc, *sink; guint bus_watch_id; GstBus *bus; loop = g_main_loop_new (NULL, FALSE); #ifdef MANUAL_CHECK id = 2; #endif /* Create gstreamer elements */ pipeline = gst_pipeline_new ("audimixer2-test"); audiotestsrc1 = gst_element_factory_make ("audiotestsrc", NULL); audiotestsrc2 = gst_element_factory_make ("audiotestsrc", NULL); audiotestsrc3 = gst_element_factory_make ("audiotestsrc", NULL); audiomixer = gst_element_factory_make ("audiomixerbin", NULL); wavenc = gst_element_factory_make ("wavenc", NULL); sink = create_sink_element (); g_object_set (G_OBJECT (audiotestsrc1), "wave", 0, NULL); g_object_set (G_OBJECT (audiotestsrc2), "wave", 8, NULL); g_object_set (G_OBJECT (audiotestsrc3), "wave", 11, NULL); bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); bus_watch_id = gst_bus_add_watch (bus, gst_bus_async_signal_func, NULL); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); g_object_unref (bus); gst_bin_add_many (GST_BIN (pipeline), audiotestsrc1, audiotestsrc2, audiotestsrc3, audiomixer, wavenc, sink, NULL); gst_element_link (audiotestsrc1, audiomixer); gst_element_link (audiotestsrc2, audiomixer); gst_element_link (audiotestsrc3, audiomixer); gst_element_link (audiomixer, wavenc); gst_element_link (wavenc, sink); g_timeout_add (1000, (GSourceFunc) block_audiotestsrc, audiotestsrc1); g_timeout_add (2000, (GSourceFunc) block_audiotestsrc, audiotestsrc2); g_timeout_add (3000, (GSourceFunc) quit_main_loop, NULL); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "entering_main_loop"); gst_element_set_state (pipeline, GST_STATE_PLAYING); GST_DEBUG ("Test running"); g_main_loop_run (loop); GST_DEBUG ("Stop executed"); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "after_main_loop"); GST_DEBUG ("Setting pipline to NULL state"); gst_element_set_state (pipeline, GST_STATE_NULL); GST_DEBUG ("Releasing pipeline"); gst_object_unref (GST_OBJECT (pipeline)); GST_DEBUG ("Pipeline released"); g_source_remove (bus_watch_id); g_main_loop_unref (loop); } GST_END_TEST /******************************/ /* audiomixer test suit */ /******************************/ static Suite * audiomixerbin_suite (void) { Suite *s = suite_create ("audiomixerbin"); TCase *tc_chain = tcase_create ("element"); suite_add_tcase (s, tc_chain); #ifdef ENABLE_DEBUGGING_TESTS tcase_add_test (tc_chain, check_audio_connection); tcase_add_test (tc_chain, check_delayed_audio_connection); #endif tcase_add_test (tc_chain, check_audio_disconnection); return s; } GST_CHECK_MAIN (audiomixerbin);
bjxagu/kms-core
src/gst-plugins/commons/sdpagent/kmssdpagent.c
/* * (C) Copyright 2015 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "kmsrefstruct.h" #include "kmssdpcontext.h" #include "kmssdpagent.h" #include "sdp_utils.h" #include "kmssdpagentcommon.h" #include "kmssdpgroupmanager.h" #include "kmssdpbasegroup.h" #include "kmssdprejectmediahandler.h" #include "kmssdpmediadirext.h" #include "kmssdpmidext.h" #define PLUGIN_NAME "sdpagent" GST_DEBUG_CATEGORY_STATIC (kms_sdp_agent_debug_category); #define GST_CAT_DEFAULT kms_sdp_agent_debug_category #define parent_class kms_sdp_agent_parent_class #define DEFAULT_USE_IPV6 FALSE #define DEFAULT_BUNDLE FALSE #define ORIGIN_ATTR_NETTYPE "IN" #define ORIGIN_ATTR_ADDR_TYPE_IP4 "IP4" #define ORIGIN_ATTR_ADDR_TYPE_IP6 "IP6" #define DEFAULT_IP4_ADDR "0.0.0.0" #define DEFAULT_IP6_ADDR "::" #define DEFAULT_ADDR DEFAULT_IP4_ADDR #define is_internal_handler(agent, handler) \ (!g_slist_find ((agent)->priv->handlers, handler)) /* * Agent state machine: * * Modification of the SDP media is only allowed when agent is not * negotiating any SDP, so further modifications by adding or removing * media will only allowed when agent is either in in UNNEGOTIATED or * NEGOTIATED state. * * +-------------+ * no | previously | yes * +--------------------------| negotiated? |---------------------------------------+ * | +-------------+ | * | A | * | | cancel_offer() | * | | | * | create_local_offer +-------------+ create_local_offer | * | +--------------------->| LOCAL_OFFER |<-----------------------------------+ | * | | +-------------+ | | * | | | | | * | | | set_local_description() | | * V | V | V * +--+-----------+ +-----------+ set_remote_description() +------------+ * | UNNEGOTIATED | | WAIT_NEGO |------------------------------->| NEGOTIATED | * +--------------+ +-----------+ +------------+ * | _______________________________^ | * | / set_local_description() | * | / | * | +--------------+ set_remote_description() | * +------------------------->| REMOTE_OFFER |<--------------------------------+ * set_remote_description() +--------------+ * */ typedef enum { KMS_SDP_AGENT_STATE_UNNEGOTIATED, KMS_SDP_AGENT_STATE_LOCAL_OFFER, KMS_SDP_AGENT_STATE_REMOTE_OFFER, KMS_SDP_AGENT_STATE_WAIT_NEGO, KMS_SDP_AGENT_STATE_NEGOTIATED } KmsSdpAgentState; static const gchar *kms_sdp_agent_states[] = { "unnegotiated", "local_offer", "remote_offer", "wait_nego", "negotiated" }; /* Object properties */ enum { PROP_0, PROP_USE_IPV6, PROP_ADDR, PROP_LOCAL_DESC, PROP_REMOTE_DESC, N_PROPERTIES }; static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, }; #define KMS_SDP_AGENT_GET_PRIVATE(obj) ( \ G_TYPE_INSTANCE_GET_PRIVATE ( \ (obj), \ KMS_TYPE_SDP_AGENT, \ KmsSdpAgentPrivate \ ) \ ) /* Configure media callback begin */ typedef struct _KmsSdpAgentConfigureMediaCallbackData { KmsSdpAgentConfigureMediaCallback callback; gpointer user_data; GDestroyNotify destroy; } KmsSdpAgentConfigureMediaCallbackData; static KmsSdpAgentConfigureMediaCallbackData * kms_sdp_agent_configure_media_callback_data_new (KmsSdpAgentConfigureMediaCallback callback, gpointer user_data, GDestroyNotify destroy) { KmsSdpAgentConfigureMediaCallbackData *data; data = g_slice_new0 (KmsSdpAgentConfigureMediaCallbackData); data->callback = callback; data->user_data = user_data; data->destroy = destroy; return data; } static void kms_sdp_agent_configure_media_callback_data_clear (KmsSdpAgentConfigureMediaCallbackData ** data) { if (*data == NULL) { return; } if ((*data)->destroy) { (*data)->destroy ((*data)->user_data); } g_slice_free (KmsSdpAgentConfigureMediaCallbackData, *data); *data = NULL; } /* Configure media callback end */ typedef struct _SdpHandlerGroup { KmsRefStruct ref; guint id; guint index; gboolean negotiated; KmsSdpBaseGroup *group; GSList *handlers; /* SdpHandler */ } SdpHandlerGroup; typedef struct _SdpHandler { KmsRefStruct ref; KmsSdpHandler *sdph; gboolean disabled; gboolean unsupported; /* unsupported by local agent */ gboolean rejected; /* unsupported by remote agent */ gboolean offer; GstSDPMedia *unsupported_media; } SdpHandler; typedef struct _SdpSessionDescription { gchar *id; gchar *version; } SdpSessionDescription; typedef struct _KmsSdpAgentCallbacksData { KmsSdpAgentCallbacks callbacks; gpointer user_data; GDestroyNotify destroy; } KmsSdpAgentCallbacksData; struct _KmsSdpAgentPrivate { KmsSdpGroupManager *group_manager; GstSDPMessage *local_description; GstSDPMessage *remote_description; gboolean use_ipv6; gchar *addr; GSList *handlers; GSList *groups; guint hids; /* handler ids */ guint gids; /* group ids */ KmsSdpAgentConfigureMediaCallbackData *configure_media_callback_data; /* deprecated */ KmsSdpAgentCallbacksData callbacks; GRecMutex mutex; KmsSdpAgentState state; GstSDPMessage *prev_sdp; GSList *offer_handlers; SdpSessionDescription local; SdpSessionDescription remote; GSList *extensions; }; #define SDP_AGENT_STATE(agent) kms_sdp_agent_states[(agent)->priv->state] #define SDP_AGENT_NEW_STATE(agent, new_state) do { \ GST_DEBUG_OBJECT ((agent), "State changed from '%s' to '%s'", \ SDP_AGENT_STATE (agent), kms_sdp_agent_states[(new_state)]); \ kms_sdp_agent_commit_state_operations ((agent), new_state); \ (agent)->priv->state = new_state; \ } while (0) #define SDP_AGENT_LOCK(agent) \ (g_rec_mutex_lock (&KMS_SDP_AGENT ((agent))->priv->mutex)) #define SDP_AGENT_UNLOCK(agent) \ (g_rec_mutex_unlock (&KMS_SDP_AGENT ((agent))->priv->mutex)) /* class initialization */ G_DEFINE_TYPE_WITH_CODE (KmsSdpAgent, kms_sdp_agent, G_TYPE_OBJECT, GST_DEBUG_CATEGORY_INIT (kms_sdp_agent_debug_category, PLUGIN_NAME, 0, "debug category for sdp agent")); static guint64 get_ntp_time () { return time (NULL) + G_GUINT64_CONSTANT (2208988800); } static void clear_sdp_session_description (SdpSessionDescription * desc) { g_free (desc->id); g_free (desc->version); desc->id = NULL; desc->version = NULL; } static void set_sdp_session_description (SdpSessionDescription * desc, const gchar * id, const gchar * version) { clear_sdp_session_description (desc); desc->id = g_strdup (id); desc->version = g_strdup (version); } static void generate_sdp_session_description (SdpSessionDescription * desc) { clear_sdp_session_description (desc); /* The method of generating <sess-id> and <sess-version> is up to the */ /* creating tool, but it has been suggested that a Network Time Protocol */ /* (NTP) format timestamp be used to ensure uniqueness [rfc4566] 5.2 */ desc->id = g_strdup_printf ("%" G_GUINT64_FORMAT, get_ntp_time ()); desc->version = g_strdup (desc->id); } static void mark_handler_as_negotiated (gpointer data, gpointer user_data) { SdpHandler *handler = data; handler->sdph->negotiated = TRUE; } static gint disable_handler_cmp_func (SdpHandler * handler, gconstpointer * data) { if (handler->disabled) { return 0; } else { return -1; } } static void kms_sdp_agent_remove_media_handler (KmsSdpAgent * agent, SdpHandler * handler) { if (!kms_sdp_group_manager_remove_handler (agent->priv->group_manager, handler->sdph)) { GST_ERROR_OBJECT (agent, "Problems removing handler %u", handler->sdph->id); } agent->priv->handlers = g_slist_remove (agent->priv->handlers, handler); kms_ref_struct_unref (KMS_REF_STRUCT_CAST (handler)); } static void kms_sdp_agent_remove_disabled_medias (KmsSdpAgent * agent) { GSList *l; while ((l = g_slist_find_custom (agent->priv->handlers, NULL, (GCompareFunc) disable_handler_cmp_func)) != NULL) { kms_sdp_agent_remove_media_handler (agent, l->data); } } static void kms_sdp_agent_commit_state_operations (KmsSdpAgent * agent, KmsSdpAgentState new_state) { switch (new_state) { case KMS_SDP_AGENT_STATE_UNNEGOTIATED: clear_sdp_session_description (&agent->priv->local); clear_sdp_session_description (&agent->priv->remote); g_slist_free_full (agent->priv->offer_handlers, (GDestroyNotify) kms_ref_struct_unref); agent->priv->offer_handlers = NULL; break; case KMS_SDP_AGENT_STATE_NEGOTIATED: if (agent->priv->state != KMS_SDP_AGENT_STATE_LOCAL_OFFER) { /* Offer has not been canceled, so we cant mark medias as negotiated */ g_slist_foreach (agent->priv->offer_handlers, mark_handler_as_negotiated, NULL); } kms_sdp_agent_remove_disabled_medias (agent); break; default: GST_LOG_OBJECT (agent, "Nothing to commit for state '%s'", kms_sdp_agent_states[new_state]); break; } } static void sdp_handler_destroy (SdpHandler * handler) { if (handler->unsupported_media != NULL) { gst_sdp_media_free (handler->unsupported_media); } kms_sdp_agent_common_unref_sdp_handler (handler->sdph); g_slice_free (SdpHandler, handler); } static SdpHandler * sdp_handler_new (guint id, const gchar * media, KmsSdpMediaHandler * handler) { SdpHandler *sdp_handler; sdp_handler = g_slice_new0 (SdpHandler); kms_ref_struct_init (KMS_REF_STRUCT_CAST (sdp_handler), (GDestroyNotify) sdp_handler_destroy); sdp_handler->sdph = kms_sdp_agent_common_new_sdp_handler (id, media, handler); sdp_handler->unsupported = KMS_IS_SDP_REJECT_MEDIA_HANDLER (handler); return sdp_handler; } static void sdp_handler_group_destroy (SdpHandlerGroup * group) { g_slist_free (group->handlers); g_clear_object (&group->group); g_slice_free (SdpHandlerGroup, group); } static SdpHandlerGroup * sdp_handler_group_new (guint id, KmsSdpBaseGroup * group) { SdpHandlerGroup *sdp_group; sdp_group = g_slice_new0 (SdpHandlerGroup); kms_ref_struct_init (KMS_REF_STRUCT_CAST (sdp_group), (GDestroyNotify) sdp_handler_group_destroy); sdp_group->id = id; sdp_group->group = group; return sdp_group; } static void kms_sdp_agent_release_sdp (GstSDPMessage ** sdp) { if (*sdp == NULL) { return; } gst_sdp_message_free (*sdp); *sdp = NULL; } static SdpHandler * kms_sdp_agent_get_handler (KmsSdpAgent * agent, guint hid) { GSList *l; for (l = agent->priv->handlers; l != NULL; l = l->next) { SdpHandler *handler = l->data; if (handler->sdph->id == hid) { return handler; } } return NULL; } static void kms_sdp_agent_finalize (GObject * object) { KmsSdpAgent *self = KMS_SDP_AGENT (object); GST_DEBUG_OBJECT (self, "finalize"); kms_sdp_agent_configure_media_callback_data_clear (&self-> priv->configure_media_callback_data); if (self->priv->callbacks.destroy != NULL && self->priv->callbacks.user_data != NULL) { self->priv->callbacks.destroy (self->priv->callbacks.user_data); } if (self->priv->local_description != NULL) { gst_sdp_message_free (self->priv->local_description); } if (self->priv->prev_sdp != NULL) { gst_sdp_message_free (self->priv->prev_sdp); } kms_sdp_agent_release_sdp (&self->priv->remote_description); g_slist_free_full (self->priv->extensions, g_object_unref); g_slist_free_full (self->priv->offer_handlers, (GDestroyNotify) kms_ref_struct_unref); g_slist_free_full (self->priv->handlers, (GDestroyNotify) kms_ref_struct_unref); g_slist_free_full (self->priv->groups, (GDestroyNotify) kms_ref_struct_unref); g_rec_mutex_clear (&self->priv->mutex); g_free (self->priv->addr); clear_sdp_session_description (&self->priv->local); clear_sdp_session_description (&self->priv->remote); g_clear_object (&self->priv->group_manager); G_OBJECT_CLASS (parent_class)->finalize (object); } static void kms_sdp_agent_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { KmsSdpAgent *self = KMS_SDP_AGENT (object); SDP_AGENT_LOCK (self); switch (prop_id) { case PROP_LOCAL_DESC:{ GstSDPMessage *desc; gst_sdp_message_copy (self->priv->local_description, &desc); g_value_take_boxed (value, desc); break; } case PROP_REMOTE_DESC: g_value_set_boxed (value, self->priv->remote_description); break; case PROP_USE_IPV6: g_value_set_boolean (value, self->priv->use_ipv6); break; case PROP_ADDR: g_value_set_string (value, self->priv->addr); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } SDP_AGENT_UNLOCK (self); } static void kms_sdp_agent_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { KmsSdpAgent *self = KMS_SDP_AGENT (object); SDP_AGENT_LOCK (self); switch (prop_id) { case PROP_USE_IPV6: self->priv->use_ipv6 = g_value_get_boolean (value); if (g_strcmp0 (self->priv->addr, DEFAULT_ADDR) == 0) { g_free (self->priv->addr); if (self->priv->use_ipv6) { self->priv->addr = g_strdup (DEFAULT_IP6_ADDR); } else { self->priv->addr = g_strdup (DEFAULT_IP4_ADDR); } } break; case PROP_ADDR: g_free (self->priv->addr); self->priv->addr = g_value_dup_string (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } SDP_AGENT_UNLOCK (self); } static void kms_sdp_agent_origin_init (KmsSdpAgent * agent, GstSDPOrigin * o, gchar * sess_id, gchar * sess_version) { SdpIPv ipv; ipv = (agent->priv->use_ipv6) ? IPV6 : IPV4; o->username = "-"; o->sess_id = sess_id; o->sess_version = sess_version; o->nettype = "IN"; o->addrtype = (gchar *) kms_sdp_message_context_ipv2str (ipv); o->addr = agent->priv->addr; } static SdpHandler * kms_sdp_agent_create_media_handler (KmsSdpAgent * agent, const gchar * media, KmsSdpMediaHandler * handler) { SdpHandler *sdp_handler; gint id = -1; id = agent->priv->hids++; sdp_handler = sdp_handler_new (id, media, handler); kms_sdp_group_manager_add_handler (agent->priv->group_manager, (KmsSdpHandler *) kms_ref_struct_ref (KMS_REF_STRUCT_CAST (sdp_handler->sdph))); return sdp_handler; } static gint kms_sdp_agent_append_media_handler (KmsSdpAgent * agent, const gchar * media, KmsSdpMediaHandler * handler) { GError *err = NULL; SdpHandler *sdp_handler; const gchar *addr_type; sdp_handler = kms_sdp_agent_create_media_handler (agent, media, handler); if (!kms_sdp_media_handler_set_parent (handler, agent, &err)) { GST_WARNING_OBJECT (agent, "%s", err->message); kms_sdp_agent_remove_media_handler (agent, sdp_handler); g_error_free (err); return -1; } if (!kms_sdp_media_handler_set_id (handler, sdp_handler->sdph->id, &err)) { GST_WARNING_OBJECT (agent, "%s", err->message); kms_sdp_agent_remove_media_handler (agent, sdp_handler); kms_sdp_media_handler_remove_parent (handler); g_error_free (err); return -1; } agent->priv->handlers = g_slist_append (agent->priv->handlers, sdp_handler); if (agent->priv->use_ipv6) { addr_type = ORIGIN_ATTR_ADDR_TYPE_IP6; } else { addr_type = ORIGIN_ATTR_ADDR_TYPE_IP4; } g_object_set (handler, "addr-type", addr_type, "addr", agent->priv->addr, NULL); return sdp_handler->sdph->id; } static gint kms_sdp_agent_add_proto_handler_impl (KmsSdpAgent * agent, const gchar * media, KmsSdpMediaHandler * handler) { gchar *proto; gint id = -1; g_object_get (handler, "proto", &proto, NULL); if (proto == NULL) { GST_WARNING_OBJECT (agent, "Handler's proto can't be NULL"); return -1; } g_free (proto); SDP_AGENT_LOCK (agent); if (agent->priv->state != KMS_SDP_AGENT_STATE_UNNEGOTIATED && agent->priv->state != KMS_SDP_AGENT_STATE_NEGOTIATED) { SDP_AGENT_UNLOCK (agent); GST_WARNING_OBJECT (agent, "Can not manipulate media while negotiation is taking place (state: %s)", kms_sdp_agent_states[agent->priv->state]); return -1; } id = kms_sdp_agent_append_media_handler (agent, media, handler); SDP_AGENT_UNLOCK (agent); return id; } static void kms_sdp_agent_remove_handler_from_groups (KmsSdpAgent * agent, SdpHandler * handler) { GSList *l; kms_sdp_group_manager_remove_handler (agent->priv->group_manager, handler->sdph); /* FIXME: Remove next code (decrecated when we get rid of mconf API) */ for (l = agent->priv->groups; l != NULL; l = l->next) { SdpHandlerGroup *group = l->data; kms_sdp_agent_remove_handler_from_group (agent, group->id, handler->sdph->id); } } gint kms_sdp_agent_get_handler_index_impl (KmsSdpAgent * agent, gint hid) { SdpHandler *sdp_handler; gint index = -1; SDP_AGENT_LOCK (agent); sdp_handler = kms_sdp_agent_get_handler (agent, hid); if (sdp_handler == NULL) { goto end; } if (sdp_handler->disabled) { /* Handler is disabled but is still required by the agent. Do not */ /* provide a vaid index in this case so it is not considered for */ /* effective media negotiation any more. */ goto end; } index = g_slist_index (agent->priv->offer_handlers, sdp_handler); if (index >= 0) { goto end; } /* Perhaps this handler is offered but not yet negotiated so we get the */ /* index which it has been assgined in the offer */ if (sdp_handler->offer) { index = sdp_handler->sdph->index; } end: SDP_AGENT_UNLOCK (agent); return index; } gboolean kms_sdp_agent_remove_proto_handler (KmsSdpAgent * agent, gint hid) { SdpHandler *sdp_handler; gboolean ret = TRUE; SDP_AGENT_LOCK (agent); if (agent->priv->state != KMS_SDP_AGENT_STATE_UNNEGOTIATED && agent->priv->state != KMS_SDP_AGENT_STATE_NEGOTIATED) { SDP_AGENT_UNLOCK (agent); GST_WARNING_OBJECT (agent, "Can not manipulate media while negotiation is taking place"); return FALSE; } sdp_handler = kms_sdp_agent_get_handler (agent, hid); if (sdp_handler == NULL) { ret = FALSE; goto end; } kms_sdp_agent_remove_handler_from_groups (agent, sdp_handler); kms_sdp_media_handler_remove_parent (sdp_handler->sdph->handler); if (!sdp_handler->sdph->negotiated) { /* No previous offer generated so we can just remove the handler */ kms_sdp_agent_remove_media_handler (agent, sdp_handler); } else { /* Desactive handler */ sdp_handler->disabled = TRUE; } end: SDP_AGENT_UNLOCK (agent); return ret; } static GstSDPMedia * kms_sdp_agent_get_negotiated_media (KmsSdpAgent * agent, SdpHandler * sdp_handler, GError ** error) { GstSDPMessage *desc; GstSDPMedia *media = NULL; guint index; index = sdp_handler->sdph->index; if (!sdp_handler->sdph->negotiated) { g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_STATE, "Media handler '%s' at [%d] not negotiated", sdp_handler->sdph->media, index); return NULL; } if (sdp_handler->offer) { /* We offered this media. Remote description has the negotiated media */ desc = agent->priv->remote_description; } else { /* Local description has the media negotiated */ desc = agent->priv->local_description; } if (desc == NULL) { g_set_error_literal (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_STATE, "No previous SDP negotiated"); return NULL; } if (index >= gst_sdp_message_medias_len (desc)) { g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_MEDIA, "Could not process media '%s'", sdp_handler->sdph->media); } else { gst_sdp_media_copy (gst_sdp_message_get_media (desc, index), &media); } return media; } static GstSDPDirection kms_sdp_agent_on_offer_dir (KmsSdpMediaDirectionExt * ext, gpointer user_data) { return GST_SDP_DIRECTION_INACTIVE; } static GstSDPDirection kms_sdp_agent_on_answer_dir (KmsSdpMediaDirectionExt * ext, GstSDPDirection dir, gpointer user_data) { return GST_SDP_DIRECTION_INACTIVE; } static gboolean kms_sdp_agent_on_answer_mid (KmsISdpMediaExtension * ext, gchar * mid, gpointer user_data) { return TRUE; } static KmsSdpMediaHandler * create_reject_handler () { KmsSdpMediaDirectionExt *ext; KmsSdpMediaHandler *handler; handler = KMS_SDP_MEDIA_HANDLER (kms_sdp_reject_media_handler_new ()); ext = kms_sdp_media_direction_ext_new (); g_signal_connect (ext, "on-offer-media-direction", G_CALLBACK (kms_sdp_agent_on_offer_dir), NULL); g_signal_connect (ext, "on-answer-media-direction", G_CALLBACK (kms_sdp_agent_on_answer_dir), NULL); kms_sdp_media_handler_add_media_extension (handler, KMS_I_SDP_MEDIA_EXTENSION (ext)); return handler; } static void reject_sdp_media (GstSDPMedia ** media) { KmsSdpMediaHandler *handler = create_reject_handler (); GstSDPMedia *rejected; KmsSdpMidExt *ext; ext = kms_sdp_mid_ext_new (); g_signal_connect (ext, "on-answer-mid", G_CALLBACK (kms_sdp_agent_on_answer_mid), NULL); kms_sdp_media_handler_add_media_extension (handler, KMS_I_SDP_MEDIA_EXTENSION (ext)); rejected = kms_sdp_media_handler_create_answer (handler, NULL, *media, NULL); g_object_unref (handler); gst_sdp_media_free (*media); *media = rejected; } static GstSDPMedia * kms_sdp_agent_create_proper_media_offer (KmsSdpAgent * agent, SdpHandler * sdp_handler, GError ** err) { GstSDPMedia *media, *prev; guint index; if (sdp_handler->disabled || sdp_handler->rejected) { /* Try to generate an offer to provide a rejected media in the offer. */ /* Objects that use the agent could realize this is a fake offer */ /* checking the index attribute of the media handler */ GST_DEBUG ("Removed negotiated media %u, %s", sdp_handler->sdph->index, sdp_handler->sdph->media); media = kms_sdp_agent_get_negotiated_media (agent, sdp_handler, err); if (media != NULL) { reject_sdp_media (&media); } return media; } if (sdp_handler->unsupported) { gst_sdp_media_copy (sdp_handler->unsupported_media, &media); return media; } if (!sdp_handler->sdph->negotiated) { /* new offer */ media = kms_sdp_media_handler_create_offer (sdp_handler->sdph->handler, sdp_handler->sdph->media, NULL, err); if (media != NULL) { sdp_handler->offer = TRUE; } return media; } index = g_slist_index (agent->priv->offer_handlers, sdp_handler); if (index >= gst_sdp_message_medias_len (agent->priv->local_description)) { g_set_error (err, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_MEDIA, "Could not process media '%s'", sdp_handler->sdph->media); return NULL; } /* Start a new negotiation based on the previous one */ gst_sdp_media_copy (gst_sdp_message_get_media (agent->priv->local_description, index), &prev); media = kms_sdp_media_handler_create_offer (sdp_handler->sdph->handler, sdp_handler->sdph->media, prev, err); gst_sdp_media_free (prev); return media; } static void kms_sdp_agent_fire_on_offer_callback (KmsSdpAgent * agent, KmsSdpMediaHandler * handler, SdpMediaConfig * local_mconf) { /* deprecated */ if (agent->priv->configure_media_callback_data != NULL) { agent->priv->configure_media_callback_data->callback (agent, handler, local_mconf, agent->priv->configure_media_callback_data->user_data); } if (agent->priv->callbacks.callbacks.on_media_offer != NULL) { agent->priv->callbacks.callbacks.on_media_offer (agent, handler, local_mconf, agent->priv->callbacks.user_data); } } static void kms_sdp_agent_fire_on_answer_callback (KmsSdpAgent * agent, KmsSdpMediaHandler * handler, SdpMediaConfig * local_mconf) { /* deprecated */ if (agent->priv->configure_media_callback_data != NULL) { agent->priv->configure_media_callback_data->callback (agent, handler, local_mconf, agent->priv->configure_media_callback_data->user_data); } if (agent->priv->callbacks.callbacks.on_media_answer != NULL) { agent->priv->callbacks.callbacks.on_media_answer (agent, handler, local_mconf, agent->priv->callbacks.user_data); } } static gboolean kms_sdp_agent_make_media_offer (KmsSdpAgent * agent, SdpHandler * sdp_handler, SdpMessageContext * ctx, guint index, GError ** err) { SdpMediaConfig *m_conf; KmsSdpBaseGroup *group; GstSDPMedia *media; media = kms_sdp_agent_create_proper_media_offer (agent, sdp_handler, err); if (media == NULL) { return FALSE; } /* update index */ sdp_handler->sdph->index = index; m_conf = kms_sdp_message_context_add_media (ctx, media, err); if (m_conf == NULL) { return FALSE; } /* Generate a MediaConf with mediagroups so elements still need this */ /* deprecated structure */ group = kms_sdp_group_manager_get_group (agent->priv->group_manager, sdp_handler->sdph); if (group != NULL) { SdpMediaGroup *m_group; guint gid; g_object_get (group, "id", &gid, NULL); g_object_unref (group); m_group = kms_sdp_message_context_get_group (ctx, gid); if (m_group == NULL) { m_group = kms_sdp_message_context_create_group (ctx, gid); } if (!kms_sdp_message_context_add_media_to_group (m_group, m_conf, err)) { return FALSE; } } kms_sdp_agent_fire_on_offer_callback (agent, sdp_handler->sdph->handler, m_conf); return TRUE; } static gboolean increment_sess_version (KmsSdpAgent * agent, SdpMessageContext * new_offer, GError ** error) { guint64 sess_version; const GstSDPOrigin *orig; GstSDPOrigin new_orig; gboolean ret; orig = gst_sdp_message_get_origin (agent->priv->local_description); sess_version = g_ascii_strtoull (orig->sess_version, NULL, 10); g_free (agent->priv->local.version); agent->priv->local.version = g_strdup_printf ("%" G_GUINT64_FORMAT, ++sess_version); new_orig.username = orig->username; new_orig.sess_id = orig->sess_id; new_orig.sess_version = agent->priv->local.version; new_orig.nettype = orig->nettype; new_orig.addrtype = orig->addrtype; new_orig.addr = orig->addr; ret = kms_sdp_message_context_set_origin (new_offer, &new_orig, error); return ret; } static gboolean kms_sdp_agent_update_session_version (KmsSdpAgent * agent, SdpMessageContext * new_offer, GError ** error) { GstSDPMessage *new_sdp = NULL; gboolean ret = TRUE; /* rfc3264 8 Modifying the Session: */ /* When issuing an offer that modifies the session, the "o=" line of the */ /* new SDP MUST be identical to that in the previous SDP, except that the */ /* version in the origin field MUST increment by one from the previous SDP. */ if (agent->priv->local_description == NULL) { return TRUE; } new_sdp = kms_sdp_message_context_pack (new_offer, error); if (new_sdp == NULL) { ret = FALSE; goto end; } if (!sdp_utils_equal_messages (agent->priv->local_description, new_sdp)) { ret = increment_sess_version (agent, new_offer, error); } end: if (new_sdp != NULL) { gst_sdp_message_free (new_sdp); } return ret; } static gpointer sdp_handler_ref (SdpHandler * sdp_handler, gpointer user_data) { return kms_ref_struct_ref (KMS_REF_STRUCT_CAST (sdp_handler)); } static gint handler_cmp_func (SdpHandler * h1, SdpHandler * h2) { return h1->sdph->id - h2->sdph->id; } static void kms_sdp_agent_merge_handler_func (SdpHandler * handler, KmsSdpAgent * agent) { GSList *l; if (handler->sdph->negotiated || handler->disabled) { /* This handler is already in the offer */ return; } l = g_slist_find_custom (agent->priv->offer_handlers, handler, (GCompareFunc) handler_cmp_func); if (l == NULL) { /* This handler is not yet in the offer */ GST_DEBUG ("Adding handler %u", handler->sdph->id); agent->priv->offer_handlers = g_slist_append (agent->priv->offer_handlers, kms_ref_struct_ref (KMS_REF_STRUCT_CAST (handler))); } } static SdpHandler * kms_sdp_agent_get_first_not_negotiated_handler (KmsSdpAgent * agent) { GSList *l; for (l = agent->priv->handlers; l != NULL; l = g_slist_next (l)) { SdpHandler *handler; handler = l->data; if (handler->sdph->negotiated) { continue; } if (g_slist_find_custom (agent->priv->offer_handlers, handler, (GCompareFunc) handler_cmp_func) == NULL) { /* This handler is not yet added */ return handler; } } return NULL; } static gint reusable_slot_cmp (SdpHandler * handler, gconstpointer * data) { if (handler->disabled || handler->unsupported) { return 0; } else { return -1; } } static void kms_sdp_agent_merge_offer_handlers (KmsSdpAgent * agent) { GSList *l; if (agent->priv->state == KMS_SDP_AGENT_STATE_UNNEGOTIATED) { /* No preivous offer generated */ agent->priv->offer_handlers = g_slist_copy_deep (agent->priv->handlers, (GCopyFunc) sdp_handler_ref, NULL); return; } while ((l = g_slist_find_custom (agent->priv->offer_handlers, NULL, (GCompareFunc) reusable_slot_cmp)) != NULL) { SdpHandler *old_handler, *new_handler; new_handler = kms_sdp_agent_get_first_not_negotiated_handler (agent); if (new_handler == NULL) { /* No more new handlers available to fix slots */ break; } /* rfc3264 [8.1] */ /* New media streams are created by new additional media descriptions */ /* below the existing ones, or by reusing the "slot" used by an old */ /* media stream which had been disabled by setting its port to zero. */ old_handler = l->data; kms_ref_struct_unref (KMS_REF_STRUCT_CAST (old_handler)); l->data = kms_ref_struct_ref (KMS_REF_STRUCT_CAST (new_handler)); } /* Add the rest of new handlers */ g_slist_foreach (agent->priv->handlers, (GFunc) kms_sdp_agent_merge_handler_func, agent); } static gboolean kms_sdp_agent_create_media_offer (KmsSdpAgent * agent, SdpMessageContext * ctx, GError ** error) { guint index = 0; GSList *l; for (l = agent->priv->offer_handlers; l != NULL; l = g_slist_next (l)) { if (!kms_sdp_agent_make_media_offer (agent, l->data, ctx, index++, error)) { return FALSE; } } return TRUE; } static gboolean kms_sdp_agent_exec_pre_processing_extensions (KmsSdpAgent * agent, SdpMessageContext * ctx, GError ** error) { GstSDPMessage *offer; gboolean pre_proc; GSList *l; offer = kms_sdp_message_context_get_sdp_message (ctx); for (l = agent->priv->extensions; l != NULL; l = g_slist_next (l)) { KmsISdpSessionExtension *ext = l->data; g_object_get (ext, "pre-media-processing", &pre_proc, NULL); if (!pre_proc) { /* this extension should be executed at the end */ continue; } if (!kms_i_sdp_session_extension_add_offer_attributes (ext, offer, error)) { return FALSE; } } return TRUE; } static gboolean kms_sdp_agent_exec_post_processing_extensions (KmsSdpAgent * agent, GstSDPMessage * offer, GError ** error) { gboolean pre_proc; GSList *l; for (l = agent->priv->extensions; l != NULL; l = g_slist_next (l)) { KmsISdpSessionExtension *ext = l->data; g_object_get (ext, "pre-media-processing", &pre_proc, NULL); if (pre_proc) { /* this extension has been executed already */ continue; } if (!kms_i_sdp_session_extension_add_offer_attributes (ext, offer, error)) { return FALSE; } } return TRUE; } static GstSDPMessage * kms_sdp_agent_create_offer_impl (KmsSdpAgent * agent, GError ** error) { SdpMessageContext *ctx = NULL; GstSDPMessage *offer = NULL; gchar *ntp = NULL; GstSDPOrigin o; GSList *tmp = NULL; SDP_AGENT_LOCK (agent); if (agent->priv->state != KMS_SDP_AGENT_STATE_UNNEGOTIATED && agent->priv->state != KMS_SDP_AGENT_STATE_NEGOTIATED) { g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_STATE, "Agent in state %s", SDP_AGENT_STATE (agent)); goto end; } ctx = kms_sdp_message_context_new (error); if (ctx == NULL) { goto end; } if (agent->priv->state == KMS_SDP_AGENT_STATE_NEGOTIATED) { const GstSDPOrigin *orig; orig = gst_sdp_message_get_origin (agent->priv->local_description); set_sdp_session_description (&agent->priv->local, orig->sess_id, orig->sess_version); } else { generate_sdp_session_description (&agent->priv->local); } kms_sdp_agent_origin_init (agent, &o, agent->priv->local.id, agent->priv->local.version); if (!kms_sdp_message_context_set_origin (ctx, &o, error)) { g_free (ntp); goto end; } g_free (ntp); kms_sdp_message_context_set_type (ctx, KMS_SDP_OFFER); /* Execute pre-processing extensions */ if (!kms_sdp_agent_exec_pre_processing_extensions (agent, ctx, error)) { goto end; } tmp = g_slist_copy_deep (agent->priv->offer_handlers, (GCopyFunc) sdp_handler_ref, NULL); kms_sdp_agent_merge_offer_handlers (agent); /* Process medias */ if (!kms_sdp_agent_create_media_offer (agent, ctx, error)) { goto end; } if (!kms_sdp_agent_update_session_version (agent, ctx, error)) { goto end; } offer = kms_sdp_message_context_pack (ctx, error); if (offer == NULL) { goto end; } /* Execute post-processing extensions */ if (!kms_sdp_agent_exec_post_processing_extensions (agent, offer, error)) { gst_sdp_message_free (offer); offer = NULL; goto end; } g_slist_free_full (tmp, (GDestroyNotify) kms_ref_struct_unref); SDP_AGENT_NEW_STATE (agent, KMS_SDP_AGENT_STATE_LOCAL_OFFER); tmp = NULL; end: if (tmp != NULL) { g_slist_free_full (agent->priv->offer_handlers, (GDestroyNotify) kms_ref_struct_unref); agent->priv->offer_handlers = tmp; } SDP_AGENT_UNLOCK (agent); if (ctx != NULL) { kms_sdp_message_context_unref (ctx); } return offer; } struct SdpAnswerData { guint index; KmsSdpAgent *agent; SdpMessageContext *ctx; const GstSDPMessage *offer; GError **err; }; static SdpHandler * kms_sdp_agent_request_handler (KmsSdpAgent * agent, const GstSDPMedia * media) { KmsSdpMediaHandler *handler; gchar *proto; gint hid; if (agent->priv->callbacks.callbacks.on_handler_required == NULL) { return NULL; } handler = agent->priv->callbacks.callbacks.on_handler_required (agent, media, agent->priv->callbacks.user_data); if (handler == NULL) { return NULL; } g_object_get (handler, "proto", &proto, NULL); if (proto == NULL) { GST_WARNING_OBJECT (agent, "Handler's proto can't be NULL"); g_object_unref (handler); return NULL; } g_free (proto); if (!kms_sdp_media_handler_manage_protocol (handler, gst_sdp_media_get_proto (media))) { GST_WARNING_OBJECT (agent, "Handler can not manage media: %s", gst_sdp_media_get_media (media)); g_object_unref (handler); return NULL; } hid = kms_sdp_agent_append_media_handler (agent, gst_sdp_media_get_media (media), handler); if (hid < 0) { g_object_unref (handler); return NULL; } else { return kms_sdp_agent_get_handler (agent, hid); } } static void kms_sdp_agent_set_handler_group (KmsSdpAgent * agent, SdpHandler * handler, const GstSDPMedia * media, const GstSDPMessage * offer) { const gchar *mid, *mids; SdpHandlerGroup *grp; gchar *semantics = NULL; gchar **items; guint i, len; len = g_slist_length (agent->priv->groups); if (len == 0) { GST_DEBUG_OBJECT (agent, "No groups supported"); return; } else if (len > 1) { GST_ERROR_OBJECT (agent, "Only one group is supported"); return; } mid = gst_sdp_media_get_attribute_val (media, "mid"); if (mid == NULL) { GST_ERROR_OBJECT (agent, "No mid attribute"); return; } /* FIXME: Only one group is supported so far */ grp = agent->priv->groups->data; mids = gst_sdp_message_get_attribute_val (offer, "group"); if (mids == NULL) { GST_DEBUG_OBJECT (agent, "Group not provided"); return; } g_object_get (grp->group, "semantics", &semantics, NULL); items = g_strsplit (mids, " ", 0); if (items[0] == NULL || g_strcmp0 (items[0], semantics) != 0) { GST_ERROR_OBJECT (agent, "Invalid group %s", items[0]); goto end; } for (i = 1; items[i] != NULL; i++) { if (g_strcmp0 (items[i], mid) == 0) { kms_sdp_group_manager_add_handler_to_group (agent->priv->group_manager, grp->id, handler->sdph->id); break; } } end: g_strfreev (items); g_free (semantics); } static SdpHandler * kms_sdp_agent_get_handler_for_media (KmsSdpAgent * agent, const GstSDPMedia * media, const GstSDPMessage * offer) { SdpHandler *handler; GSList *l; for (l = agent->priv->handlers; l != NULL; l = l->next) { SdpHandler *sdp_handler; sdp_handler = l->data; if (sdp_handler->sdph->negotiated) { continue; } if (g_strcmp0 (sdp_handler->sdph->media, gst_sdp_media_get_media (media)) != 0) { /* This handler can not manage this media */ continue; } if (!kms_sdp_media_handler_manage_protocol (sdp_handler->sdph->handler, gst_sdp_media_get_proto (media))) { continue; } if (g_slist_find (agent->priv->offer_handlers, sdp_handler)) { /* Handler used for answering other media */ continue; } return sdp_handler; } handler = kms_sdp_agent_request_handler (agent, media); if (handler != NULL) { kms_sdp_agent_set_handler_group (agent, handler, media, offer); } return handler; } static SdpHandler * kms_sdp_agent_create_reject_media_handler (KmsSdpAgent * agent, const GstSDPMedia * media) { return kms_sdp_agent_create_media_handler (agent, gst_sdp_media_get_media (media), create_reject_handler ()); } static SdpHandler * kms_sdp_agent_replace_offered_handler (KmsSdpAgent * agent, const GstSDPMedia * media, const GstSDPMessage * offer, SdpHandler * handler) { SdpHandler *candidate; GSList *l; l = g_slist_find (agent->priv->offer_handlers, handler); if (l == NULL) { GST_ERROR_OBJECT (agent, "Can not get a new candidate"); return NULL; } kms_ref_struct_unref (KMS_REF_STRUCT_CAST (l->data)); /* Try to get a new handler for this media */ candidate = kms_sdp_agent_get_handler_for_media (agent, media, offer); if (candidate == NULL) { GST_WARNING_OBJECT (agent, "No handler for '%s' media proto '%s' found", gst_sdp_media_get_media (media), gst_sdp_media_get_proto (media)); candidate = kms_sdp_agent_create_reject_media_handler (agent, media); } else { candidate = (SdpHandler *) kms_ref_struct_ref (KMS_REF_STRUCT_CAST (candidate)); } /* Upate position of the offer list with the new handler */ l->data = candidate; return candidate; } static SdpHandler * kms_sdp_agent_get_proper_handler (KmsSdpAgent * agent, const GstSDPMedia * media, const GstSDPMessage * offer, SdpHandler * handler) { if (!handler->rejected) { return handler; } if (gst_sdp_media_get_port (media) == 0) { /* Handler was rejected but media is still disabled */ return handler; } /* Media was rejected and the new media is not desabled, this mean that */ /* current slot has been replaced for another new media. Let's look for */ /* a compatible handler to manage it */ handler->sdph->negotiated = FALSE; handler->rejected = FALSE; handler->offer = FALSE; if (g_strcmp0 (handler->sdph->media, gst_sdp_media_get_media (media)) != 0) { /* This handler can not manage this media */ return kms_sdp_agent_replace_offered_handler (agent, media, offer, handler); } if (kms_sdp_media_handler_manage_protocol (handler->sdph->handler, gst_sdp_media_get_proto (media))) { /* The previously rejected handler is capable of managing this media */ return handler; } else { return kms_sdp_agent_replace_offered_handler (agent, media, offer, handler); } } static SdpHandler * kms_sdp_agent_select_handler_to_answer_media (KmsSdpAgent * agent, guint index, const GstSDPMedia * media, const GstSDPMessage * offer) { SdpHandler *handler; if (agent->priv->offer_handlers == NULL) { return kms_sdp_agent_get_handler_for_media (agent, media, offer); } handler = g_slist_nth_data (agent->priv->offer_handlers, index); if (handler != NULL) { return kms_sdp_agent_get_proper_handler (agent, media, offer, handler); } if (handler == NULL) { /* the position is off the end of the list */ handler = kms_sdp_agent_get_handler_for_media (agent, media, offer); } return handler; } static gboolean create_media_answer (const GstSDPMedia * media, struct SdpAnswerData *data) { KmsSdpAgent *agent = data->agent; GstSDPMedia *answer_media = NULL; SdpMediaConfig *mconf = NULL; SdpHandler *sdp_handler; GError **err = data->err; gboolean ret = TRUE; sdp_handler = kms_sdp_agent_select_handler_to_answer_media (agent, data->index, media, data->offer); if (sdp_handler == NULL) { GST_WARNING_OBJECT (agent, "No handler for '%s' media proto '%s' found", gst_sdp_media_get_media (media), gst_sdp_media_get_proto (media)); sdp_handler = kms_sdp_agent_create_reject_media_handler (agent, media); } else if (gst_sdp_media_get_port (media) == 0) { if (sdp_handler->sdph->negotiated) { answer_media = kms_sdp_agent_get_negotiated_media (agent, sdp_handler, err); if (answer_media == NULL) { return FALSE; } } else { /* Process offer as usual and reject it later */ GST_WARNING_OBJECT (agent, "Not negotiated media offered with port set to 0"); answer_media = kms_sdp_media_handler_create_answer (sdp_handler->sdph->handler, data->ctx, media, err); } /* RFC rfc3264 [8.2]: A stream that is offered with a port */ /* of zero MUST be marked with port zero in the answer */ reject_sdp_media (&answer_media); goto answer; } answer_media = kms_sdp_media_handler_create_answer (sdp_handler->sdph->handler, data->ctx, media, err); if (answer_media == NULL) { ret = FALSE; goto end; } answer: if (sdp_handler->unsupported && sdp_handler->unsupported_media == NULL) { gst_sdp_media_copy (answer_media, &sdp_handler->unsupported_media); } mconf = kms_sdp_message_context_add_media (data->ctx, answer_media, err); if (mconf == NULL) { ret = FALSE; } end: if (!ret && is_internal_handler (agent, sdp_handler)) { /* Remove internal handler on error */ kms_ref_struct_unref (KMS_REF_STRUCT_CAST (sdp_handler)); } else if (ret && !g_slist_find (agent->priv->offer_handlers, sdp_handler)) { if (!is_internal_handler (agent, sdp_handler)) { /* This is not an internal handler */ sdp_handler = (SdpHandler *) kms_ref_struct_ref (KMS_REF_STRUCT_CAST (sdp_handler)); } /* add handler to the sdp ordered list */ sdp_handler->sdph->index = data->index; agent->priv->offer_handlers = g_slist_append (agent->priv->offer_handlers, sdp_handler); } if (mconf != NULL) { kms_sdp_agent_fire_on_answer_callback (data->agent, sdp_handler->sdph->handler, mconf); } /* Update index for next media */ data->index++; return ret; } static gboolean kms_sdp_agent_cancel_offer_impl (KmsSdpAgent * agent, GError ** error) { gboolean ret; SDP_AGENT_LOCK (agent); if (agent->priv->state != KMS_SDP_AGENT_STATE_LOCAL_OFFER) { g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_STATE, "Agent in state %s", SDP_AGENT_STATE (agent)); ret = FALSE; } else { KmsSdpAgentState new_state; new_state = (agent->priv->prev_sdp != NULL) ? KMS_SDP_AGENT_STATE_NEGOTIATED : KMS_SDP_AGENT_STATE_UNNEGOTIATED; SDP_AGENT_NEW_STATE (agent, new_state); ret = TRUE; } SDP_AGENT_UNLOCK (agent); return ret; } static SdpMessageContext * kms_sdp_agent_generate_answer_compat (KmsSdpAgent * agent, const GstSDPMessage * offer, GError ** error) { struct SdpAnswerData data; SdpMessageContext *ctx; gboolean bundle; GstSDPOrigin o; kms_sdp_agent_origin_init (agent, &o, agent->priv->local.id, agent->priv->local.version); bundle = g_slist_length (agent->priv->groups) > 0; ctx = kms_sdp_message_context_new (error); if (ctx == NULL) { return NULL; } if (!kms_sdp_message_context_set_origin (ctx, &o, error)) { kms_sdp_message_context_unref (ctx); return NULL; } kms_sdp_message_context_set_type (ctx, KMS_SDP_ANSWER); if (bundle && !kms_sdp_message_context_parse_groups_from_offer (ctx, offer, error)) { goto error; } if (!kms_sdp_message_context_set_common_session_attributes (ctx, offer, error)) { goto error; } data.agent = agent; data.ctx = ctx; data.err = error; data.offer = offer; data.index = 0; if (sdp_utils_for_each_media (offer, (GstSDPMediaFunc) create_media_answer, &data)) { return ctx; } error: kms_sdp_message_context_unref (ctx); return NULL; } static SdpMessageContext * kms_sdp_agent_create_answer_impl (KmsSdpAgent * agent, GError ** error) { SdpMessageContext *ctx = NULL; SDP_AGENT_LOCK (agent); if (agent->priv->state != KMS_SDP_AGENT_STATE_REMOTE_OFFER) { g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_STATE, "Agent in state %s", SDP_AGENT_STATE (agent)); SDP_AGENT_UNLOCK (agent); return NULL; } if (agent->priv->local.id == NULL || agent->priv->local.version == NULL) { generate_sdp_session_description (&agent->priv->local); } ctx = kms_sdp_agent_generate_answer_compat (agent, agent->priv->remote_description, error); SDP_AGENT_UNLOCK (agent); return ctx; } static void kms_sdp_agent_fire_on_answered_callback (KmsSdpAgent * agent, SdpHandler * sdp_handler, SdpMediaConfig * neg_mconf, gboolean local_offerer) { if (agent->priv->callbacks.callbacks.on_media_answered != NULL) { agent->priv->callbacks.callbacks.on_media_answered (agent, sdp_handler->sdph->handler, neg_mconf, local_offerer, agent->priv->callbacks.user_data); } } static gint handler_media_config_cmp_func (SdpHandler * h, gconstpointer * mid_pointer) { gint mid = GPOINTER_TO_INT (mid_pointer); return h->sdph->index - mid; } typedef struct _KmsSdpAgentProcessAnsweredMediaConfigData { KmsSdpAgent *agent; gboolean local_offerer; } KmsSdpAgentProcessAnsweredMediaConfigData; static void kms_sdp_agent_process_answered_media_config (SdpMediaConfig * mconf, KmsSdpAgentProcessAnsweredMediaConfigData * data) { KmsSdpAgent *agent = data->agent; gboolean local_offerer = data->local_offerer; gint mid = kms_sdp_media_config_get_id (mconf); GSList *l; l = g_slist_find_custom (agent->priv->offer_handlers, GINT_TO_POINTER (mid), (GCompareFunc) handler_media_config_cmp_func); if (l == NULL) { GST_WARNING_OBJECT (agent, "SDP handler not found for media posistion '%u'", mid); return; } kms_sdp_agent_fire_on_answered_callback (agent, l->data, mconf, local_offerer); } static void kms_sdp_agent_process_answered_context (KmsSdpAgent * agent, SdpMessageContext * ctx, gboolean local_offerer) { KmsSdpAgentProcessAnsweredMediaConfigData data; data.agent = agent; data.local_offerer = local_offerer; g_slist_foreach (kms_sdp_message_context_get_medias (ctx), (GFunc) kms_sdp_agent_process_answered_media_config, &data); } static void kms_sdp_agent_process_answered_description (KmsSdpAgent * agent, GstSDPMessage * desc, gboolean local_offerer) { SdpMessageContext *ctx; GError *err = NULL; ctx = kms_sdp_message_context_new_from_sdp (desc, &err); if (err != NULL) { GST_ERROR_OBJECT (agent, "Error generating SDP message context (%s)", err->message); g_error_free (err); return; } kms_sdp_agent_process_answered_context (agent, ctx, local_offerer); kms_sdp_message_context_unref (ctx); } static gboolean kms_sdp_agent_set_local_description_impl (KmsSdpAgent * agent, GstSDPMessage * description, GError ** error) { KmsSdpAgentState new_state; const GstSDPOrigin *orig; gboolean ret = FALSE; SDP_AGENT_LOCK (agent); if (agent->priv->state != KMS_SDP_AGENT_STATE_LOCAL_OFFER && agent->priv->state != KMS_SDP_AGENT_STATE_REMOTE_OFFER) { g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_STATE, "Agent in state %s", SDP_AGENT_STATE (agent)); goto end; } orig = gst_sdp_message_get_origin (description); if (g_strcmp0 (orig->sess_id, agent->priv->local.id)) { g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_PARAMETER, "Unexpected sdp session %s", orig->sess_id); goto end; } if (agent->priv->local_description != NULL) { gst_sdp_message_free (agent->priv->local_description); } gst_sdp_message_copy (description, &agent->priv->local_description); if (agent->priv->state == KMS_SDP_AGENT_STATE_REMOTE_OFFER) { if (agent->priv->prev_sdp != NULL) { gst_sdp_message_free (agent->priv->prev_sdp); } gst_sdp_message_copy (description, &agent->priv->prev_sdp); } new_state = (agent->priv->state == KMS_SDP_AGENT_STATE_LOCAL_OFFER) ? KMS_SDP_AGENT_STATE_WAIT_NEGO : KMS_SDP_AGENT_STATE_NEGOTIATED; SDP_AGENT_NEW_STATE (agent, new_state); ret = TRUE; if (new_state == KMS_SDP_AGENT_STATE_NEGOTIATED) { kms_sdp_agent_process_answered_description (agent, agent->priv->local_description, FALSE); } end: SDP_AGENT_UNLOCK (agent); return ret; } static void update_rejected_medias (KmsSdpAgent * agent, const GstSDPMessage * desc) { guint i, len; len = gst_sdp_message_medias_len (desc); for (i = 0; i < len; i++) { const GstSDPMedia *media; SdpHandler *handler; media = gst_sdp_message_get_media (desc, i); handler = g_slist_nth_data (agent->priv->offer_handlers, i); if (handler == NULL) { GST_DEBUG_OBJECT (agent, "No handler for media at position %u", i); continue; } if (!handler->rejected && gst_sdp_media_get_port (media) == 0) { handler->rejected = TRUE; } } } static void kms_sdp_agent_process_answer (KmsSdpAgent * agent) { GError *err = NULL; guint i, len; len = gst_sdp_message_medias_len (agent->priv->prev_sdp); for (i = 0; i < len; i++) { const GstSDPMedia *media; SdpHandler *handler; media = gst_sdp_message_get_media (agent->priv->prev_sdp, i); handler = g_slist_nth_data (agent->priv->offer_handlers, i); if (handler == NULL) { GST_ERROR_OBJECT (agent, "Can not process answer in handler %u", i); continue; } if (!kms_sdp_media_handler_process_answer (handler->sdph->handler, media, &err)) { GST_ERROR_OBJECT (agent, "Error processing answer: %s", err->message); g_clear_error (&err); } } } static gboolean is_valid_session_version (const gchar * session1, const gchar * session2) { guint64 v1, v2; v1 = g_ascii_strtoull (session1, NULL, 10); v2 = g_ascii_strtoull (session2, NULL, 10); return (v1 == v2 || (v1 + 1) == v2); } static gboolean kms_sdp_agent_set_remote_description_impl (KmsSdpAgent * agent, GstSDPMessage * description, GError ** error) { gboolean ret = TRUE; SDP_AGENT_LOCK (agent); switch (agent->priv->state) { case KMS_SDP_AGENT_STATE_WAIT_NEGO:{ const GstSDPOrigin *orig; orig = gst_sdp_message_get_origin (description); if (agent->priv->remote.id == NULL && agent->priv->remote.version == NULL) { /* First answer received from remote side => establish the session */ set_sdp_session_description (&agent->priv->remote, orig->sess_id, orig->sess_version); } else if (g_strcmp0 (agent->priv->remote.id, orig->sess_id) == 0 && is_valid_session_version (agent->priv->remote.version, orig->sess_version)) { g_free (agent->priv->remote.version); agent->priv->remote.version = g_strdup (orig->sess_version); } else { g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_PARAMETER, "Invalid sdp session %s %s, expected %s %s", orig->sess_id, orig->sess_version, agent->priv->remote.id, agent->priv->remote.version); ret = FALSE; break; } if (agent->priv->prev_sdp != NULL) { gst_sdp_message_free (agent->priv->prev_sdp); } update_rejected_medias (agent, description); gst_sdp_message_copy (description, &agent->priv->prev_sdp); kms_sdp_agent_process_answer (agent); SDP_AGENT_NEW_STATE (agent, KMS_SDP_AGENT_STATE_NEGOTIATED); break; } case KMS_SDP_AGENT_STATE_UNNEGOTIATED:{ const GstSDPOrigin *orig; orig = gst_sdp_message_get_origin (description); set_sdp_session_description (&agent->priv->remote, orig->sess_id, orig->sess_version); SDP_AGENT_NEW_STATE (agent, KMS_SDP_AGENT_STATE_REMOTE_OFFER); break; } case KMS_SDP_AGENT_STATE_NEGOTIATED:{ const GstSDPOrigin *orig; orig = gst_sdp_message_get_origin (description); if ((g_strcmp0 (agent->priv->remote.id, orig->sess_id) == 0) && is_valid_session_version (agent->priv->remote.version, orig->sess_version)) { update_rejected_medias (agent, description); g_free (agent->priv->remote.version); agent->priv->remote.version = g_strdup (orig->sess_version); SDP_AGENT_NEW_STATE (agent, KMS_SDP_AGENT_STATE_REMOTE_OFFER); } else { g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_PARAMETER, "Invalid sdp session: %s %s, expected %s %s", orig->sess_id, orig->sess_version, agent->priv->remote.id, agent->priv->remote.version); ret = FALSE; } break; } default: g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_STATE, "Agent in state %s", SDP_AGENT_STATE (agent)); ret = FALSE; } if (ret) { kms_sdp_agent_release_sdp (&agent->priv->remote_description); agent->priv->remote_description = description; if (agent->priv->state == KMS_SDP_AGENT_STATE_NEGOTIATED) { kms_sdp_agent_process_answered_description (agent, description, TRUE); } } SDP_AGENT_UNLOCK (agent); return ret; } gint kms_sdp_agent_create_bundle_group_impl (KmsSdpAgent * agent) { SdpHandlerGroup *group; guint id; SDP_AGENT_LOCK (agent); if (agent->priv->state != KMS_SDP_AGENT_STATE_UNNEGOTIATED && agent->priv->state != KMS_SDP_AGENT_STATE_NEGOTIATED) { SDP_AGENT_UNLOCK (agent); GST_WARNING_OBJECT (agent, "Can not manipulate media while negotiation is taking place"); return -1; } id = agent->priv->gids++; group = sdp_handler_group_new (id, NULL); agent->priv->groups = g_slist_append (agent->priv->groups, group); SDP_AGENT_UNLOCK (agent); return id; } static SdpHandlerGroup * kms_sdp_agent_get_group (KmsSdpAgent * agent, guint gid) { GSList *l; for (l = agent->priv->groups; l != NULL; l = l->next) { SdpHandlerGroup *group = l->data; if (group->id == gid) { return group; } } return NULL; } gboolean kms_sdp_agent_add_handler_to_group_impl (KmsSdpAgent * agent, guint gid, guint hid) { SdpHandlerGroup *group; SdpHandler *handler; gboolean ret = FALSE; GSList *l; SDP_AGENT_LOCK (agent); if (agent->priv->state != KMS_SDP_AGENT_STATE_UNNEGOTIATED && agent->priv->state != KMS_SDP_AGENT_STATE_NEGOTIATED) { SDP_AGENT_UNLOCK (agent); GST_WARNING_OBJECT (agent, "Can not manipulate media while negotiation is taking place"); goto end; } group = kms_sdp_agent_get_group (agent, gid); if (group == NULL) { goto end; } handler = kms_sdp_agent_get_handler (agent, hid); if (handler == NULL) { goto end; } ret = TRUE; for (l = group->handlers; l != NULL; l = l->next) { SdpHandler *h = l->data; if (h->sdph->id == hid) { goto end; } } group->handlers = g_slist_append (group->handlers, handler); end: SDP_AGENT_UNLOCK (agent); return ret; } gboolean kms_sdp_agent_remove_handler_from_group_impl (KmsSdpAgent * agent, guint gid, guint hid) { SdpHandlerGroup *group; SdpHandler *handler; gboolean ret = FALSE; SDP_AGENT_LOCK (agent); if (agent->priv->state != KMS_SDP_AGENT_STATE_UNNEGOTIATED && agent->priv->state != KMS_SDP_AGENT_STATE_NEGOTIATED) { SDP_AGENT_UNLOCK (agent); GST_WARNING_OBJECT (agent, "Can not manipulate media while negotiation is taking place"); goto end; } group = kms_sdp_agent_get_group (agent, gid); if (group == NULL) { goto end; } handler = kms_sdp_agent_get_handler (agent, hid); if (handler == NULL) { goto end; } if (!g_slist_find (group->handlers, handler)) { goto end; } group->handlers = g_slist_remove (group->handlers, handler); ret = TRUE; end: SDP_AGENT_UNLOCK (agent); return ret; } static void kms_sdp_agent_class_init (KmsSdpAgentClass * klass) { GObjectClass *gobject_class; gobject_class = G_OBJECT_CLASS (klass); gobject_class->get_property = kms_sdp_agent_get_property; gobject_class->set_property = kms_sdp_agent_set_property; gobject_class->finalize = kms_sdp_agent_finalize; obj_properties[PROP_USE_IPV6] = g_param_spec_boolean ("use-ipv6", "Use ipv6 in SDPs", "Use ipv6 addresses in generated sdp offers and answers", DEFAULT_USE_IPV6, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS); obj_properties[PROP_ADDR] = g_param_spec_string ("addr", "Address", "The IP address used to negotiate SDPs", DEFAULT_ADDR, G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS); obj_properties[PROP_LOCAL_DESC] = g_param_spec_boxed ("local-description", "Local description", "The local SDP description", GST_TYPE_SDP_MESSAGE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); obj_properties[PROP_REMOTE_DESC] = g_param_spec_boxed ("remote-description", "Remote description", "The temote SDP description", GST_TYPE_SDP_MESSAGE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); g_object_class_install_properties (gobject_class, N_PROPERTIES, obj_properties); klass->add_proto_handler = kms_sdp_agent_add_proto_handler_impl; klass->get_handler_index = kms_sdp_agent_get_handler_index_impl; klass->create_offer = kms_sdp_agent_create_offer_impl; klass->create_answer = kms_sdp_agent_create_answer_impl; klass->cancel_offer = kms_sdp_agent_cancel_offer_impl; klass->set_local_description = kms_sdp_agent_set_local_description_impl; klass->set_remote_description = kms_sdp_agent_set_remote_description_impl; klass->create_bundle_group = kms_sdp_agent_create_bundle_group_impl; klass->add_handler_to_group = kms_sdp_agent_add_handler_to_group_impl; klass->remove_handler_from_group = kms_sdp_agent_remove_handler_from_group_impl; g_type_class_add_private (klass, sizeof (KmsSdpAgentPrivate)); } static void kms_sdp_agent_init_callbacks (KmsSdpAgent * self) { self->priv->callbacks.user_data = NULL; self->priv->callbacks.destroy = NULL; self->priv->callbacks.callbacks.on_media_answer = NULL; self->priv->callbacks.callbacks.on_media_offer = NULL; self->priv->callbacks.callbacks.on_handler_required = NULL; } static void kms_sdp_agent_init (KmsSdpAgent * self) { self->priv = KMS_SDP_AGENT_GET_PRIVATE (self); self->priv->group_manager = kms_sdp_group_manager_new (); g_rec_mutex_init (&self->priv->mutex); self->priv->state = KMS_SDP_AGENT_STATE_UNNEGOTIATED; kms_sdp_agent_init_callbacks (self); } KmsSdpAgent * kms_sdp_agent_new () { KmsSdpAgent *agent; agent = KMS_SDP_AGENT (g_object_new (KMS_TYPE_SDP_AGENT, NULL)); return agent; } /* TODO: rename to _add_media_handler */ gint kms_sdp_agent_add_proto_handler (KmsSdpAgent * agent, const gchar * media, KmsSdpMediaHandler * handler) { g_return_val_if_fail (KMS_IS_SDP_AGENT (agent), -1); return KMS_SDP_AGENT_GET_CLASS (agent)->add_proto_handler (agent, media, handler); } GstSDPMessage * kms_sdp_agent_create_offer (KmsSdpAgent * agent, GError ** error) { g_return_val_if_fail (KMS_IS_SDP_AGENT (agent), NULL); return KMS_SDP_AGENT_GET_CLASS (agent)->create_offer (agent, error); } /* Deprecated: Use kms_sdp_agent_generate_answer instead */ SdpMessageContext * kms_sdp_agent_create_answer (KmsSdpAgent * agent, GError ** error) { g_return_val_if_fail (KMS_IS_SDP_AGENT (agent), NULL); return KMS_SDP_AGENT_GET_CLASS (agent)->create_answer (agent, error); } gboolean kms_sdpagent_cancel_offer (KmsSdpAgent * agent, GError ** error) { g_return_val_if_fail (KMS_IS_SDP_AGENT (agent), FALSE); return KMS_SDP_AGENT_GET_CLASS (agent)->cancel_offer (agent, error); } gboolean kms_sdp_agent_set_local_description (KmsSdpAgent * agent, GstSDPMessage * description, GError ** error) { g_return_val_if_fail (KMS_IS_SDP_AGENT (agent), FALSE); return KMS_SDP_AGENT_GET_CLASS (agent)->set_local_description (agent, description, error); } gboolean kms_sdp_agent_set_remote_description (KmsSdpAgent * agent, GstSDPMessage * description, GError ** error) { g_return_val_if_fail (KMS_IS_SDP_AGENT (agent), FALSE); return KMS_SDP_AGENT_GET_CLASS (agent)->set_remote_description (agent, description, error); } gint kms_sdp_agent_create_bundle_group (KmsSdpAgent * agent) { g_return_val_if_fail (KMS_IS_SDP_AGENT (agent), -1); return KMS_SDP_AGENT_GET_CLASS (agent)->create_bundle_group (agent); } gboolean kms_sdp_agent_add_handler_to_group (KmsSdpAgent * agent, guint gid, guint hid) { g_return_val_if_fail (KMS_IS_SDP_AGENT (agent), FALSE); return KMS_SDP_AGENT_GET_CLASS (agent)->add_handler_to_group (agent, gid, hid); } gboolean kms_sdp_agent_remove_handler_from_group (KmsSdpAgent * agent, guint gid, guint hid) { g_return_val_if_fail (KMS_IS_SDP_AGENT (agent), FALSE); return KMS_SDP_AGENT_GET_CLASS (agent)->remove_handler_from_group (agent, gid, hid); } void kms_sdp_agent_set_configure_media_callback (KmsSdpAgent * agent, KmsSdpAgentConfigureMediaCallback callback, gpointer user_data, GDestroyNotify destroy) { KmsSdpAgentConfigureMediaCallbackData *old_data; SDP_AGENT_LOCK (agent); old_data = agent->priv->configure_media_callback_data; agent->priv->configure_media_callback_data = kms_sdp_agent_configure_media_callback_data_new (callback, user_data, destroy); SDP_AGENT_UNLOCK (agent); kms_sdp_agent_configure_media_callback_data_clear (&old_data); } void kms_sdp_agent_set_callbacks (KmsSdpAgent * agent, KmsSdpAgentCallbacks * callbacks, gpointer user_data, GDestroyNotify destroy) { GDestroyNotify notify; gpointer old_data; g_return_if_fail (KMS_IS_SDP_AGENT (agent)); SDP_AGENT_LOCK (agent); notify = agent->priv->callbacks.destroy; old_data = agent->priv->callbacks.user_data; agent->priv->callbacks.destroy = destroy; agent->priv->callbacks.user_data = user_data; agent->priv->callbacks.callbacks.on_media_answer = callbacks->on_media_answer; agent->priv->callbacks.callbacks.on_media_answered = callbacks->on_media_answered; agent->priv->callbacks.callbacks.on_media_offer = callbacks->on_media_offer; agent->priv->callbacks.callbacks.on_handler_required = callbacks->on_handler_required; SDP_AGENT_UNLOCK (agent); if (notify != NULL && old_data != NULL) { notify (old_data); } } gint kms_sdp_agent_create_group (KmsSdpAgent * agent, GType group_type, const char *optname1, ...) { gboolean failed; gpointer obj; va_list ap; gint gid; va_start (ap, optname1); obj = g_object_new_valist (group_type, optname1, ap); va_end (ap); if (!KMS_IS_SDP_BASE_GROUP (obj)) { GST_WARNING_OBJECT (agent, "Trying to create an invalid group"); g_object_unref (obj); return -1; } SDP_AGENT_LOCK (agent); if (agent->priv->state != KMS_SDP_AGENT_STATE_UNNEGOTIATED && agent->priv->state != KMS_SDP_AGENT_STATE_NEGOTIATED) { SDP_AGENT_UNLOCK (agent); g_object_unref (obj); GST_WARNING_OBJECT (agent, "Can not manipulate media while negotiation is taking place"); return -1; } gid = kms_sdp_group_manager_add_group (agent->priv->group_manager, KMS_SDP_BASE_GROUP (obj)); failed = gid < 0; if (!failed) { /* Add group extension */ agent->priv->extensions = g_slist_append (agent->priv->extensions, g_object_ref (obj)); agent->priv->groups = g_slist_append (agent->priv->groups, sdp_handler_group_new (gid, g_object_ref (obj))); } SDP_AGENT_UNLOCK (agent); if (failed) { GST_WARNING_OBJECT (agent, "Can not create group"); g_object_unref (obj); return -1; } return gid; } gboolean kms_sdp_agent_group_add (KmsSdpAgent * agent, guint gid, guint hid) { gboolean ret = FALSE; SDP_AGENT_LOCK (agent); if (agent->priv->state != KMS_SDP_AGENT_STATE_UNNEGOTIATED && agent->priv->state != KMS_SDP_AGENT_STATE_NEGOTIATED) { GST_WARNING_OBJECT (agent, "Can not manipulate media while negotiation is taking place"); goto end; } ret = kms_sdp_group_manager_add_handler_to_group (agent->priv->group_manager, gid, hid); end: SDP_AGENT_UNLOCK (agent); return ret; } gboolean kms_sdp_agent_group_remove (KmsSdpAgent * agent, guint gid, guint hid) { gboolean ret = FALSE; SDP_AGENT_LOCK (agent); if (agent->priv->state != KMS_SDP_AGENT_STATE_UNNEGOTIATED && agent->priv->state != KMS_SDP_AGENT_STATE_NEGOTIATED) { GST_WARNING_OBJECT (agent, "Can not manipulate media while negotiation is taking place"); goto end; } ret = kms_sdp_group_manager_remove_handler_from_group (agent-> priv->group_manager, gid, hid); end: SDP_AGENT_UNLOCK (agent); return ret; } gint kms_sdp_agent_get_handler_index (KmsSdpAgent * agent, gint hid) { g_return_val_if_fail (KMS_IS_SDP_AGENT (agent), -1); return KMS_SDP_AGENT_GET_CLASS (agent)->get_handler_index (agent, hid); }
bjxagu/kms-core
src/gst-plugins/commons/sdpagent/kmssdppayloadmanager.h
<gh_stars>0 /* * (C) Copyright 2015 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _KMS_SDP_PAYLOAD_MANAGER_H_ #define _KMS_SDP_PAYLOAD_MANAGER_H_ #include <gst/gst.h> G_BEGIN_DECLS #define KMS_TYPE_SDP_PAYLOAD_MANAGER \ (kms_sdp_payload_manager_get_type()) #define KMS_SDP_PAYLOAD_MANAGER(obj) ( \ G_TYPE_CHECK_INSTANCE_CAST ( \ (obj), \ KMS_TYPE_SDP_PAYLOAD_MANAGER, \ KmsSdpPayloadManager \ ) \ ) #define KMS_SDP_PAYLOAD_MANAGER_CLASS(klass) ( \ G_TYPE_CHECK_CLASS_CAST ( \ (klass), \ KMS_TYPE_SDP_PAYLOAD_MANAGER, \ KmsSdpPayloadManagerClass \ ) \ ) #define KMS_IS_SDP_PAYLOAD_MANAGER(obj) ( \ G_TYPE_CHECK_INSTANCE_TYPE ( \ (obj), \ KMS_TYPE_SDP_PAYLOAD_MANAGER \ ) \ ) #define KMS_IS_SDP_PAYLOAD_MANAGER_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE((klass),KMS_TYPE_SDP_PAYLOAD_MANAGER)) #define KMS_SDP_PAYLOAD_MANAGER_GET_CLASS(obj) ( \ G_TYPE_INSTANCE_GET_CLASS ( \ (obj), \ KMS_TYPE_SDP_PAYLOAD_MANAGER, \ KmsSdpPayloadManagerClass \ ) \ ) typedef struct _KmsSdpPayloadManager KmsSdpPayloadManager; typedef struct _KmsSdpPayloadManagerClass KmsSdpPayloadManagerClass; typedef struct _KmsSdpPayloadManagerPrivate KmsSdpPayloadManagerPrivate; struct _KmsSdpPayloadManager { GObject parent; /*< private > */ KmsSdpPayloadManagerPrivate *priv; }; struct _KmsSdpPayloadManagerClass { GObjectClass parent_class; }; GType kms_sdp_payload_manager_get_type (); KmsSdpPayloadManager * kms_sdp_payload_manager_new (); G_END_DECLS #endif /* _KMS_SDP_PAYLOAD_MANAGER_H_ */
bjxagu/kms-core
src/gst-plugins/commons/kmsirtpsessionmanager.c
/* * (C) Copyright 2015 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "kmsirtpsessionmanager.h" G_DEFINE_INTERFACE (KmsIRtpSessionManager, kms_i_rtp_session_manager, 0); static void kms_i_rtp_session_manager_default_init (KmsIRtpSessionManagerInterface * iface) { /* do nothing */ } GstPad * kms_i_rtp_session_manager_request_rtp_sink (KmsIRtpSessionManager * self, KmsBaseRtpSession * sess, SdpMediaConfig * mconf) { g_return_val_if_fail (KMS_IS_I_RTP_SESSION_MANAGER (self), NULL); return KMS_I_RTP_SESSION_MANAGER_GET_INTERFACE (self)->request_rtp_sink (self, sess, mconf); } GstPad * kms_i_rtp_session_manager_request_rtp_src (KmsIRtpSessionManager * self, KmsBaseRtpSession * sess, SdpMediaConfig * mconf) { g_return_val_if_fail (KMS_IS_I_RTP_SESSION_MANAGER (self), NULL); return KMS_I_RTP_SESSION_MANAGER_GET_INTERFACE (self)->request_rtp_src (self, sess, mconf); } GstPad * kms_i_rtp_session_manager_request_rtcp_sink (KmsIRtpSessionManager * self, KmsBaseRtpSession * sess, SdpMediaConfig * mconf) { g_return_val_if_fail (KMS_IS_I_RTP_SESSION_MANAGER (self), NULL); return KMS_I_RTP_SESSION_MANAGER_GET_INTERFACE (self)->request_rtcp_sink (self, sess, mconf); } GstPad * kms_i_rtp_session_manager_request_rtcp_src (KmsIRtpSessionManager * self, KmsBaseRtpSession * sess, SdpMediaConfig * mconf) { g_return_val_if_fail (KMS_IS_I_RTP_SESSION_MANAGER (self), NULL); return KMS_I_RTP_SESSION_MANAGER_GET_INTERFACE (self)->request_rtcp_src (self, sess, mconf); } gboolean kms_i_rtp_session_manager_custom_ssrc_management (KmsIRtpSessionManager * self, KmsBaseRtpSession * sess, GstElement * ssrcdemux, guint ssrc, GstPad * pad) { g_return_val_if_fail (KMS_IS_I_RTP_SESSION_MANAGER (self), FALSE); return KMS_I_RTP_SESSION_MANAGER_GET_INTERFACE (self)->custom_ssrc_management (self, sess, ssrcdemux, ssrc, pad); }
bjxagu/kms-core
src/gst-plugins/commons/sdpagent/kmssdpmediadirext.h
/* * (C) Copyright 2016 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef __KMS_SDP_MEDIA_DIRECTION_EXT_H__ #define __KMS_SDP_MEDIA_DIRECTION_EXT_H__ #include <gst/gst.h> #include <commons/sdp_utils.h> G_BEGIN_DECLS #define KMS_TYPE_SDP_MEDIA_DIRECTION_EXT \ (kms_sdp_media_direction_ext_get_type()) #define KMS_SDP_MEDIA_DIRECTION_EXT(obj) ( \ G_TYPE_CHECK_INSTANCE_CAST ( \ (obj), \ KMS_TYPE_SDP_MEDIA_DIRECTION_EXT, \ KmsSdpMediaDirectionExt \ ) \ ) #define KMS_SDP_MEDIA_DIRECTION_EXT_CLASS(klass) ( \ G_TYPE_CHECK_CLASS_CAST ( \ (klass), \ KMS_TYPE_SDP_MEDIA_DIRECTION_EXT, \ KmsSdpMediaDirectionExtClass \ ) \ ) #define KMS_IS_SDP_MEDIA_DIRECTION_EXT(obj) ( \ G_TYPE_CHECK_INSTANCE_TYPE ( \ (obj), \ KMS_TYPE_SDP_MEDIA_DIRECTION_EXT \ ) \ ) #define KMS_IS_SDP_MEDIA_DIRECTION_EXT_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE((klass),KMS_TYPE_SDP_MEDIA_DIRECTION_EXT)) #define KMS_SDP_MEDIA_DIRECTION_EXT_GET_CLASS(obj) ( \ G_TYPE_INSTANCE_GET_CLASS ( \ (obj), \ KMS_TYPE_SDP_MEDIA_DIRECTION_EXT, \ KmsSdpMediaDirectionExtClass \ ) \ ) typedef struct _KmsSdpMediaDirectionExt KmsSdpMediaDirectionExt; typedef struct _KmsSdpMediaDirectionExtClass KmsSdpMediaDirectionExtClass; typedef struct _KmsSdpMediaDirectionExtPrivate KmsSdpMediaDirectionExtPrivate; struct _KmsSdpMediaDirectionExt { GObject parent; /*< private > */ KmsSdpMediaDirectionExtPrivate *priv; }; struct _KmsSdpMediaDirectionExtClass { GObjectClass parent_class; /* signals */ GstSDPDirection (*on_offer_media_direction) (KmsSdpMediaDirectionExt * ext); GstSDPDirection (*on_answer_media_direction) (KmsSdpMediaDirectionExt * ext, GstSDPDirection dir); void (*on_answered_media_direction) (KmsSdpMediaDirectionExt * ext, GstSDPDirection dir); }; GType kms_sdp_media_direction_ext_get_type (); KmsSdpMediaDirectionExt * kms_sdp_media_direction_ext_new (); G_END_DECLS #endif /* __KMS_SDP_MEDIA_DIRECTION_EXT_H__ */
bjxagu/kms-core
src/gst-plugins/commons/kmsparsetreebin.c
<filename>src/gst-plugins/commons/kmsparsetreebin.c<gh_stars>1-10 /* * (C) Copyright 2014 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include "kmsparsetreebin.h" #include <kmsutils.h> #define GST_DEFAULT_NAME "parsetreebin" #define GST_CAT_DEFAULT kms_parse_tree_bin_debug GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define kms_parse_tree_bin_parent_class parent_class G_DEFINE_TYPE (KmsParseTreeBin, kms_parse_tree_bin, KMS_TYPE_TREE_BIN); #define KMS_PARSE_TREE_BIN_GET_PRIVATE(obj) ( \ G_TYPE_INSTANCE_GET_PRIVATE ( \ (obj), \ KMS_TYPE_PARSE_TREE_BIN, \ KmsParseTreeBinPrivate \ ) \ ) #define BITRATE_THRESHOLD 0.07 struct _KmsParseTreeBinPrivate { GstElement *parser; /* Bitrate calculation */ GstClockTime last_buffer_pts; GstClockTime last_buffer_dts; guint bitrate_mean; guint last_pushed_bitrate; }; static GstElement * create_parser_for_caps (const GstCaps * caps) { GList *parser_list, *filtered_list, *l; GstElementFactory *parser_factory = NULL; GstElement *parser = NULL; parser_list = gst_element_factory_list_get_elements (GST_ELEMENT_FACTORY_TYPE_PARSER, GST_RANK_NONE); filtered_list = gst_element_factory_list_filter (parser_list, caps, GST_PAD_SINK, FALSE); for (l = filtered_list; l != NULL && parser_factory == NULL; l = l->next) { parser_factory = GST_ELEMENT_FACTORY (l->data); if (gst_element_factory_get_num_pad_templates (parser_factory) != 2) parser_factory = NULL; } if (parser_factory != NULL) { parser = gst_element_factory_create (parser_factory, NULL); } else { parser = gst_element_factory_make ("capsfilter", NULL); } gst_plugin_feature_list_free (filtered_list); gst_plugin_feature_list_free (parser_list); return parser; } static gboolean difference_over_threshold (guint a, guint b, float th) { return (a > b ? (a - b) > (a * th) : (b - a) > (b * th)); } static GstPadProbeReturn bitrate_calculation_probe (GstPad * pad, GstPadProbeInfo * info, gpointer data) { KmsParseTreeBin *self = data; if (GST_PAD_PROBE_INFO_TYPE (info) | GST_PAD_PROBE_TYPE_BUFFER) { GstBuffer *buffer = gst_pad_probe_info_get_buffer (info); GstClockTime timediff = GST_CLOCK_TIME_NONE; guint bitrate; if (GST_CLOCK_TIME_IS_VALID (buffer->dts) && GST_CLOCK_TIME_IS_VALID (self->priv->last_buffer_dts)) { timediff = buffer->dts - self->priv->last_buffer_dts; } else if (GST_CLOCK_TIME_IS_VALID (buffer->pts) && GST_CLOCK_TIME_IS_VALID (self->priv->last_buffer_pts)) { timediff = buffer->pts - self->priv->last_buffer_pts; } if (timediff > 0) { bitrate = (gst_buffer_get_size (buffer) * GST_SECOND * 8) / timediff; self->priv->bitrate_mean = (self->priv->bitrate_mean * 7 + bitrate) / 8; if (self->priv->last_pushed_bitrate == 0 || difference_over_threshold (self->priv->bitrate_mean, self->priv->last_pushed_bitrate, BITRATE_THRESHOLD)) { GstTagList *taglist = NULL; GstEvent *previous_tag_event; GST_TRACE_OBJECT (self, "Bitrate: %u", bitrate); GST_TRACE_OBJECT (self, "Bitrate_mean:\t\t%u", self->priv->bitrate_mean); previous_tag_event = gst_pad_get_sticky_event (pad, GST_EVENT_TAG, 0); if (previous_tag_event) { GST_TRACE_OBJECT (self, "Previous tag event: %" GST_PTR_FORMAT, previous_tag_event); gst_event_parse_tag (previous_tag_event, &taglist); taglist = gst_tag_list_copy (taglist); gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, "bitrate", self->priv->bitrate_mean, NULL); gst_event_unref (previous_tag_event); } if (!taglist) { taglist = gst_tag_list_new ("bitrate", self->priv->bitrate_mean, NULL); } gst_pad_send_event (pad, gst_event_new_tag (taglist)); self->priv->last_pushed_bitrate = self->priv->bitrate_mean; } } self->priv->last_buffer_pts = buffer->pts; self->priv->last_buffer_dts = buffer->dts; } else if (GST_PAD_PROBE_INFO_TYPE (info) | GST_PAD_PROBE_TYPE_BUFFER_LIST) { GST_WARNING_OBJECT (self, "Bufferlist is not supported yet for bitrate calculation"); } return GST_PAD_PROBE_OK; } static void kms_parse_tree_bin_configure (KmsParseTreeBin * self, const GstCaps * caps) { KmsTreeBin *tree_bin = KMS_TREE_BIN (self); GstElement *output_tee; self->priv->parser = create_parser_for_caps (caps); gst_bin_add (GST_BIN (self), self->priv->parser); gst_element_sync_state_with_parent (self->priv->parser); kms_tree_bin_set_input_element (tree_bin, self->priv->parser); output_tee = kms_tree_bin_get_output_tee (tree_bin); if (!kms_utils_caps_are_raw (caps) && kms_utils_caps_are_video (caps)) { GstPad *sink = gst_element_get_static_pad (output_tee, "sink"); gst_pad_add_probe (sink, GST_PAD_PROBE_TYPE_BUFFER | GST_PAD_PROBE_TYPE_BUFFER_LIST, bitrate_calculation_probe, self, NULL); g_object_unref (sink); } gst_element_link_many (self->priv->parser, output_tee, NULL); } KmsParseTreeBin * kms_parse_tree_bin_new (const GstCaps * caps) { GObject *parse; parse = g_object_new (KMS_TYPE_PARSE_TREE_BIN, NULL); kms_parse_tree_bin_configure (KMS_PARSE_TREE_BIN (parse), caps); return KMS_PARSE_TREE_BIN (parse); } GstElement * kms_parse_tree_bin_get_parser (KmsParseTreeBin * self) { return self->priv->parser; } static void kms_parse_tree_bin_init (KmsParseTreeBin * self) { self->priv = KMS_PARSE_TREE_BIN_GET_PRIVATE (self); self->priv->last_buffer_dts = GST_CLOCK_TIME_NONE; self->priv->last_buffer_pts = GST_CLOCK_TIME_NONE; } static void kms_parse_tree_bin_class_init (KmsParseTreeBinClass * klass) { GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass); gst_element_class_set_details_simple (gstelement_class, "ParseTreeBin", "Generic", "Bin to parse and distribute media.", "<NAME> <<EMAIL>>"); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); g_type_class_add_private (klass, sizeof (KmsParseTreeBinPrivate)); }
bjxagu/kms-core
src/gst-plugins/commons/sdpagent/kmssdprtpsavpfmediahandler.h
<reponame>bjxagu/kms-core<filename>src/gst-plugins/commons/sdpagent/kmssdprtpsavpfmediahandler.h /* * (C) Copyright 2015 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _KMS_SDP_RTP_SAVPF_MEDIA_HANDLER_H_ #define _KMS_SDP_RTP_SAVPF_MEDIA_HANDLER_H_ #include "kmssdprtpavpfmediahandler.h" G_BEGIN_DECLS #define KMS_TYPE_SDP_RTP_SAVPF_MEDIA_HANDLER \ (kms_sdp_rtp_savpf_media_handler_get_type()) #define KMS_SDP_RTP_SAVPF_MEDIA_HANDLER(obj) ( \ G_TYPE_CHECK_INSTANCE_CAST ( \ (obj), \ KMS_TYPE_SDP_RTP_SAVPF_MEDIA_HANDLER, \ KmsSdpRtpSavpfMediaHandler \ ) \ ) #define KMS_SDP_RTP_SAVPF_MEDIA_HANDLER_CLASS(klass) ( \ G_TYPE_CHECK_CLASS_CAST ( \ (klass), \ KMS_TYPE_SDP_RTP_SAVPF_MEDIA_HANDLER, \ KmsSdpRtpSavpfMediaHandlerClass \ ) \ ) #define KMS_IS_SDP_RTP_SAVPF_MEDIA_HANDLER(obj) ( \ G_TYPE_CHECK_INSTANCE_TYPE ( \ (obj), \ KMS_TYPE_SDP_RTP_SAVPF_MEDIA_HANDLER \ ) \ ) #define KMS_IS_SDP_RTP_SAVPF_MEDIA_HANDLER_CLASS(klass) \ (G_TYPE_CHECK_CLASS_TYPE((klass),KMS_TYPE_SDP_RTP_SAVPF_MEDIA_HANDLER)) #define KMS_SDP_RTP_SAVPF_MEDIA_HANDLER_GET_CLASS(obj) ( \ G_TYPE_INSTANCE_GET_CLASS ( \ (obj), \ KMS_TYPE_SDP_RTP_SAVPF_MEDIA_HANDLER, \ KmsSdpRtpSavpfMediaHandlerClass \ ) \ ) typedef struct _KmsSdpRtpSavpfMediaHandler KmsSdpRtpSavpfMediaHandler; typedef struct _KmsSdpRtpSavpfMediaHandlerClass KmsSdpRtpSavpfMediaHandlerClass; typedef struct _KmsSdpRtpSavpfMediaHandlerPrivate KmsSdpRtpSavpfMediaHandlerPrivate; struct _KmsSdpRtpSavpfMediaHandler { KmsSdpRtpAvpfMediaHandler parent; /*< private > */ KmsSdpRtpSavpfMediaHandlerPrivate *priv; }; struct _KmsSdpRtpSavpfMediaHandlerClass { KmsSdpRtpAvpfMediaHandlerClass parent_class; }; GType kms_sdp_rtp_savpf_media_handler_get_type (); KmsSdpRtpSavpfMediaHandler * kms_sdp_rtp_savpf_media_handler_new (); G_END_DECLS #endif /* _KMS_SDP_RTP_SAVPF_MEDIA_HANDLER_H_ */
bjxagu/kms-core
src/gst-plugins/commons/sdpagent/kmssdpagent.h
<filename>src/gst-plugins/commons/sdpagent/kmssdpagent.h<gh_stars>0 /* * (C) Copyright 2015 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef __KMS_SDP_AGENT_H__ #define __KMS_SDP_AGENT_H__ #include <gst/gst.h> #include <gst/sdp/gstsdpmessage.h> #include "kmssdpcontext.h" #include "kmssdpmediahandler.h" #include "kmssdpcontext.h" G_BEGIN_DECLS #define KMS_SDP_AGENT_ERROR \ g_quark_from_static_string("kms-sdp-agent-error-quark") typedef enum { SDP_AGENT_INVALID_MEDIA, SDP_AGENT_INVALID_PARAMETER, SDP_AGENT_INVALID_PROTOCOL, SDP_AGENT_INVALID_STATE, SDP_AGENT_UNEXPECTED_ERROR } SdpAgentError; #define KMS_TYPE_SDP_AGENT \ (kms_sdp_agent_get_type()) #define KMS_SDP_AGENT(obj) ( \ G_TYPE_CHECK_INSTANCE_CAST ( \ (obj), \ KMS_TYPE_SDP_AGENT, \ KmsSdpAgent \ ) \ ) #define KMS_SDP_AGENT_CLASS(klass) ( \ G_TYPE_CHECK_CLASS_CAST ( \ (klass), \ KMS_TYPE_SDP_AGENT, \ KmsSdpAgentClass \ ) \ ) #define KMS_IS_SDP_AGENT(obj) ( \ G_TYPE_CHECK_INSTANCE_TYPE ( \ (obj), \ KMS_TYPE_SDP_AGENT \ ) \ ) #define KMS_IS_SDP_AGENT_CLASS(klass) ( \ G_TYPE_CHECK_CLASS_TYPE ( \ (klass), \ KMS_TYPE_SDP_AGENT \ ) \ ) #define KMS_SDP_AGENT_GET_CLASS(obj) ( \ G_TYPE_INSTANCE_GET_CLASS ( \ (obj), \ KMS_TYPE_SDP_AGENT, \ KmsSdpAgentClass \ ) \ ) typedef struct _KmsSdpAgent KmsSdpAgent; typedef struct _KmsSdpAgentClass KmsSdpAgentClass; typedef struct _KmsSdpAgentPrivate KmsSdpAgentPrivate; struct _KmsSdpAgent { GObject parent; /*< private > */ KmsSdpAgentPrivate *priv; }; struct _KmsSdpAgentClass { GObjectClass parent_class; /* methods */ gint (*add_proto_handler) (KmsSdpAgent * agent, const gchar *media, KmsSdpMediaHandler *handler); gint (*get_handler_index) (KmsSdpAgent * agent, gint hid); GstSDPMessage *(*create_offer) (KmsSdpAgent * agent, GError **error); SdpMessageContext *(*create_answer) (KmsSdpAgent * agent, GError **error); gboolean (*cancel_offer) (KmsSdpAgent * agent, GError **error); gboolean (*set_local_description) (KmsSdpAgent * agent, GstSDPMessage * description, GError **error); gboolean (*set_remote_description) (KmsSdpAgent * agent, GstSDPMessage * description, GError **error); /* Deprecated */ gint (*create_bundle_group) (KmsSdpAgent * agent); gboolean (*add_handler_to_group) (KmsSdpAgent * agent, guint gid, guint mid); gboolean (*remove_handler_from_group) (KmsSdpAgent * agent, guint gid, guint hid); }; GType kms_sdp_agent_get_type (); KmsSdpAgent * kms_sdp_agent_new (); gint kms_sdp_agent_add_proto_handler (KmsSdpAgent * agent, const gchar *media, KmsSdpMediaHandler *handler); gboolean kms_sdp_agent_remove_proto_handler (KmsSdpAgent * agent, gint hid); gint kms_sdp_agent_get_handler_index (KmsSdpAgent * agent, gint hid); SdpMessageContext * kms_sdp_agent_create_answer (KmsSdpAgent * agent, GError **error); gboolean kms_sdpagent_cancel_offer (KmsSdpAgent * agent, GError **error); GstSDPMessage * kms_sdp_agent_create_offer (KmsSdpAgent * agent, GError **error); gboolean kms_sdp_agent_set_local_description (KmsSdpAgent * agent, GstSDPMessage * description, GError **error); gboolean kms_sdp_agent_set_remote_description (KmsSdpAgent * agent, GstSDPMessage * description, GError **error); gint kms_sdp_agent_create_group (KmsSdpAgent * agent, GType group_type, const char *optname1, ...); gboolean kms_sdp_agent_group_add (KmsSdpAgent * agent, guint gid, guint hid); gboolean kms_sdp_agent_group_remove (KmsSdpAgent * agent, guint gid, guint hid); /* Deprecated begin */ gint kms_sdp_agent_create_bundle_group (KmsSdpAgent * agent); gboolean kms_sdp_agent_add_handler_to_group (KmsSdpAgent * agent, guint gid, guint hid); gboolean kms_sdp_agent_remove_handler_from_group (KmsSdpAgent * agent, guint gid, guint hid); typedef gboolean (*KmsSdpAgentConfigureMediaCallback) (KmsSdpAgent *agent, KmsSdpMediaHandler *handler, SdpMediaConfig *mconf, gpointer user_data); void kms_sdp_agent_set_configure_media_callback (KmsSdpAgent * agent, KmsSdpAgentConfigureMediaCallback callback, gpointer user_data, GDestroyNotify destroy); /* Deprecated end */ typedef struct { void (*on_media_offer) (KmsSdpAgent *agent, KmsSdpMediaHandler *handler, SdpMediaConfig *local_mconf, gpointer user_data); void (*on_media_answered) (KmsSdpAgent *agent, KmsSdpMediaHandler *handler, SdpMediaConfig *neg_mconf, gboolean local_offerer, gpointer user_data); void (*on_media_answer) (KmsSdpAgent *agent, KmsSdpMediaHandler *handler, SdpMediaConfig *local_mconf, gpointer user_data); KmsSdpMediaHandler * (*on_handler_required) (KmsSdpAgent *agent, const GstSDPMedia *media, gpointer user_data); } KmsSdpAgentCallbacks; void kms_sdp_agent_set_callbacks (KmsSdpAgent * agent, KmsSdpAgentCallbacks * callbacks, gpointer user_data, GDestroyNotify destroy); gboolean kms_sdp_media_handler_set_parent (KmsSdpMediaHandler *handler, KmsSdpAgent * parent, GError **error); G_END_DECLS #endif /* __KMS_SDP_AGENT_H__ */
bjxagu/kms-core
src/gst-plugins/commons/kmstreebin.c
/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include "kmstreebin.h" #include "kmsutils.h" #define GST_DEFAULT_NAME "treebin" #define GST_CAT_DEFAULT kms_tree_bin_debug GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define kms_tree_bin_parent_class parent_class G_DEFINE_TYPE (KmsTreeBin, kms_tree_bin, GST_TYPE_BIN); #define KMS_TREE_BIN_GET_PRIVATE(obj) ( \ G_TYPE_INSTANCE_GET_PRIVATE ( \ (obj), \ KMS_TYPE_TREE_BIN, \ KmsTreeBinPrivate \ ) \ ) struct _KmsTreeBinPrivate { GstElement *input_element, *output_tee; GstCaps *input_caps; }; GstElement * kms_tree_bin_get_input_element (KmsTreeBin * self) { return self->priv->input_element; } void kms_tree_bin_set_input_element (KmsTreeBin * self, GstElement * input_element) { self->priv->input_element = input_element; } GstElement * kms_tree_bin_get_output_tee (KmsTreeBin * self) { return self->priv->output_tee; } void kms_tree_bin_unlink_input_element_from_tee (KmsTreeBin * self) { GstPad *queue_sink, *peer, *tee_src; GstElement *tee; queue_sink = gst_element_get_static_pad (self->priv->input_element, "sink"); peer = gst_pad_get_peer (queue_sink); if (GST_IS_PROXY_PAD (peer)) { GstProxyPad *ghost; ghost = gst_proxy_pad_get_internal (GST_PROXY_PAD (peer)); tee_src = gst_pad_get_peer (GST_PAD (ghost)); g_object_unref (peer); g_object_unref (ghost); } else { tee_src = peer; } gst_pad_unlink (tee_src, queue_sink); tee = gst_pad_get_parent_element (tee_src); if (tee != NULL) { gst_element_release_request_pad (tee, tee_src); g_object_unref (tee); } g_object_unref (tee_src); g_object_unref (queue_sink); } GstCaps * kms_tree_bin_get_input_caps (KmsTreeBin * self) { return self->priv->input_caps; } static void kms_tree_bin_set_input_caps (KmsTreeBin * self, GstCaps * caps) { if (self->priv->input_caps) { gst_caps_unref (self->priv->input_caps); self->priv->input_caps = NULL; } self->priv->input_caps = gst_caps_ref (caps); } static gboolean tee_query_function (GstPad * pad, GstObject * parent, GstQuery * query) { if (GST_QUERY_TYPE (query) == GST_QUERY_ACCEPT_CAPS) { GstCaps *caps; KmsTreeBin *self = KMS_TREE_BIN (GST_OBJECT_PARENT (parent)); gst_query_parse_accept_caps (query, &caps); kms_tree_bin_set_input_caps (self, caps); } return gst_pad_query_default (pad, parent, query); } static gboolean tee_event_function (GstPad * pad, GstObject * parent, GstEvent * event) { if (GST_EVENT_TYPE (event) == GST_EVENT_CAPS) { GstCaps *caps; KmsTreeBin *self = KMS_TREE_BIN (GST_OBJECT_PARENT (parent)); gst_event_parse_caps (event, &caps); kms_tree_bin_set_input_caps (self, caps); } gst_event_unref (event); /* Return TRUE so that next handler chained can manage this stuff too */ return TRUE; } static void kms_tree_bin_finalize (GObject * object) { KmsTreeBin *self = KMS_TREE_BIN_CAST (object); if (self->priv->input_caps) { gst_caps_unref (self->priv->input_caps); self->priv->input_caps = NULL; } /* chain up */ G_OBJECT_CLASS (kms_tree_bin_parent_class)->finalize (object); } static void kms_tree_bin_init (KmsTreeBin * self) { GstElement *fakesink; GstPad *sink; self->priv = KMS_TREE_BIN_GET_PRIVATE (self); self->priv->output_tee = gst_element_factory_make ("tee", NULL); fakesink = gst_element_factory_make ("fakesink", NULL); g_object_set (fakesink, "async", FALSE, "sync", FALSE, NULL); sink = gst_element_get_static_pad (self->priv->output_tee, "sink"); if (sink) { gst_pad_set_query_function (sink, tee_query_function); kms_utils_set_pad_event_function_full (sink, tee_event_function, NULL, NULL, TRUE); g_object_unref (sink); } gst_bin_add_many (GST_BIN (self), self->priv->output_tee, fakesink, NULL); gst_element_link (self->priv->output_tee, fakesink); } static void kms_tree_bin_class_init (KmsTreeBinClass * klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass); gst_element_class_set_details_simple (gstelement_class, "TreeBin", "Generic", "Base bin to manage elements for media distribution.", "<NAME> <<EMAIL>>"); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); gobject_class->finalize = kms_tree_bin_finalize; g_type_class_add_private (klass, sizeof (KmsTreeBinPrivate)); }
bjxagu/kms-core
src/gst-plugins/kmsfilterelement.c
/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gst/gst.h> #include "kmselement.h" #include "kmsfilterelement.h" #include "kmsagnosticcaps.h" #include "kmsutils.h" #include "kms-core-enumtypes.h" #include "kmsfiltertype.h" #define PLUGIN_NAME "filterelement" #define DEFAULT_FILTER_TYPE KMS_FILTER_TYPE_AUTODETECT GST_DEBUG_CATEGORY_STATIC (kms_filter_element_debug_category); #define GST_CAT_DEFAULT kms_filter_element_debug_category #define KMS_FILTER_ELEMENT_GET_PRIVATE(obj) ( \ G_TYPE_INSTANCE_GET_PRIVATE ( \ (obj), \ KMS_TYPE_FILTER_ELEMENT, \ KmsFilterElementPrivate \ ) \ ) #define KMS_FILTER_ELEMENT_LOCK(obj) ( \ g_rec_mutex_lock(&KMS_FILTER_ELEMENT(obj)->priv->mutex) \ ) #define KMS_FILTER_ELEMENT_UNLOCK(obj) ( \ g_rec_mutex_unlock(&KMS_FILTER_ELEMENT(obj)->priv->mutex) \ ) struct _KmsFilterElementPrivate { GRecMutex mutex; gchar *filter_factory; GstElement *filter; KmsFilterType filter_type; }; /* properties */ enum { PROP_0, PROP_FILTER_FACTORY, PROP_FILTER, PROP_FILTER_TYPE }; /* pad templates */ /* class initialization */ G_DEFINE_TYPE_WITH_CODE (KmsFilterElement, kms_filter_element, KMS_TYPE_ELEMENT, GST_DEBUG_CATEGORY_INIT (kms_filter_element_debug_category, PLUGIN_NAME, 0, "debug category for filterelement element")); static void kms_filter_element_connect_filter (KmsFilterElement * self, KmsElementPadType type, GstElement * filter, GstPad * target, GstElement * agnosticbin) { gst_bin_add (GST_BIN (self), filter); self->priv->filter = filter; gst_element_link (filter, agnosticbin); gst_element_sync_state_with_parent (filter); kms_element_connect_sink_target (KMS_ELEMENT (self), target, type); } static void kms_filter_element_connect_passthrough (KmsFilterElement * self, KmsElementPadType type, GstElement * element) { GstPad *target = gst_element_get_static_pad (element, "sink"); kms_element_connect_sink_target (KMS_ELEMENT (self), target, type); g_object_unref (target); } static void kms_filter_element_set_filter (KmsFilterElement * self, GstElement * filter) { GstPad *sink = NULL, *src = NULL; GstCaps *audio_caps = NULL, *video_caps = NULL; GstCaps *sink_caps = NULL, *src_caps = NULL; if (self->priv->filter != NULL) { GST_WARNING_OBJECT (self, "Factory changes are not currently allowed"); g_object_unref (filter); return; } if (filter == NULL) { filter = gst_element_factory_make (self->priv->filter_factory, NULL); } else { GstElementFactory *factory = gst_element_get_factory (filter); if (factory == NULL) { GST_WARNING_OBJECT (self, "Cannot get filter factory from given filter %" GST_PTR_FORMAT, filter); return; } self->priv->filter_factory = g_strdup (GST_OBJECT_NAME (factory)); } if (filter == NULL) { GST_ERROR_OBJECT (self, "Invalid factory \"%s\", element cannot be created", self->priv->filter_factory); return; } sink = gst_element_get_static_pad (filter, "sink"); src = gst_element_get_static_pad (filter, "src"); if (sink == NULL || src == NULL) { GST_ERROR_OBJECT (self, "Invalid factory \"%s\", unexpected pad templates", self->priv->filter_factory); g_object_unref (filter); goto end; } audio_caps = gst_caps_from_string (KMS_AGNOSTIC_AUDIO_CAPS); video_caps = gst_caps_from_string (KMS_AGNOSTIC_VIDEO_CAPS); sink_caps = gst_pad_query_caps (sink, NULL); src_caps = gst_pad_query_caps (src, NULL); KMS_FILTER_ELEMENT_LOCK (self); if (self->priv->filter_type == KMS_FILTER_TYPE_AUTODETECT) { if (gst_caps_can_intersect (audio_caps, sink_caps) && gst_caps_can_intersect (audio_caps, src_caps)) { GST_DEBUG_OBJECT (self, "Connecting filter to audio"); self->priv->filter_type = KMS_FILTER_TYPE_AUDIO; } else if (gst_caps_can_intersect (video_caps, sink_caps) && gst_caps_can_intersect (video_caps, src_caps)) { GST_DEBUG_OBJECT (self, "Connecting filter to video"); self->priv->filter_type = KMS_FILTER_TYPE_VIDEO; } else { g_object_unref (filter); GST_ERROR_OBJECT (self, "Filter element cannot be connected"); KMS_FILTER_ELEMENT_UNLOCK (self); goto end; } } if (self->priv->filter_type == KMS_FILTER_TYPE_VIDEO) { kms_filter_element_connect_filter (self, KMS_ELEMENT_PAD_TYPE_VIDEO, filter, sink, kms_element_get_video_agnosticbin (KMS_ELEMENT (self))); kms_filter_element_connect_passthrough (self, KMS_ELEMENT_PAD_TYPE_AUDIO, kms_element_get_audio_agnosticbin (KMS_ELEMENT (self))); } else if (self->priv->filter_type == KMS_FILTER_TYPE_AUDIO) { kms_filter_element_connect_filter (self, KMS_ELEMENT_PAD_TYPE_AUDIO, filter, sink, kms_element_get_audio_agnosticbin (KMS_ELEMENT (self))); kms_filter_element_connect_passthrough (self, KMS_ELEMENT_PAD_TYPE_VIDEO, kms_element_get_video_agnosticbin (KMS_ELEMENT (self))); } else { GST_WARNING_OBJECT (self, "No filter configured, working in passthrogh"); kms_filter_element_connect_passthrough (self, KMS_ELEMENT_PAD_TYPE_VIDEO, kms_element_get_video_agnosticbin (KMS_ELEMENT (self))); kms_filter_element_connect_passthrough (self, KMS_ELEMENT_PAD_TYPE_AUDIO, kms_element_get_audio_agnosticbin (KMS_ELEMENT (self))); } /* Enable data pads */ kms_filter_element_connect_passthrough (self, KMS_ELEMENT_PAD_TYPE_DATA, kms_element_get_data_tee (KMS_ELEMENT (self))); KMS_FILTER_ELEMENT_UNLOCK (self); end: if (sink_caps != NULL) gst_caps_unref (sink_caps); if (src_caps != NULL) gst_caps_unref (src_caps); if (audio_caps != NULL) gst_caps_unref (audio_caps); if (video_caps != NULL) gst_caps_unref (video_caps); if (sink != NULL) g_object_unref (sink); if (src != NULL) g_object_unref (src); } static void kms_filter_element_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { KmsFilterElement *self = KMS_FILTER_ELEMENT (object); GST_DEBUG_OBJECT (self, "get_property"); KMS_FILTER_ELEMENT_LOCK (object); switch (prop_id) { case PROP_FILTER: g_value_set_object (value, self->priv->filter); break; case PROP_FILTER_FACTORY: g_value_set_string (value, self->priv->filter_factory); break; case PROP_FILTER_TYPE: g_value_set_enum (value, self->priv->filter_type); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } KMS_FILTER_ELEMENT_UNLOCK (object); } static void kms_filter_element_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { KmsFilterElement *self = KMS_FILTER_ELEMENT (object); GST_DEBUG_OBJECT (self, "set_property"); KMS_FILTER_ELEMENT_LOCK (object); switch (prop_id) { case PROP_FILTER_FACTORY: if (self->priv->filter_factory != NULL) { GST_WARNING_OBJECT (object, "Factory changes are not currently allowed"); } else { self->priv->filter_factory = g_value_dup_string (value); if (self->priv->filter_factory == NULL) GST_WARNING_OBJECT (object, "Invalid factory name NULL"); else kms_filter_element_set_filter (self, NULL); } break; case PROP_FILTER: if (self->priv->filter != NULL) { GST_WARNING_OBJECT (object, "Filter changes are not currently allowed"); } else { GstElement *filter = g_value_dup_object (value); if (filter != NULL) { kms_filter_element_set_filter (self, filter); } else { GST_WARNING_OBJECT (object, "Invalid filter NULL"); } } break; case PROP_FILTER_TYPE: self->priv->filter_type = g_value_get_enum (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } KMS_FILTER_ELEMENT_UNLOCK (object); } void kms_filter_element_dispose (GObject * object) { KmsFilterElement *filter_element = KMS_FILTER_ELEMENT (object); GST_DEBUG_OBJECT (filter_element, "dispose"); /* clean up as possible. may be called multiple times */ /* No need to release as bin is owning the reference */ filter_element->priv->filter = NULL; G_OBJECT_CLASS (kms_filter_element_parent_class)->dispose (object); } void kms_filter_element_finalize (GObject * object) { KmsFilterElement *filter_element = KMS_FILTER_ELEMENT (object); GST_DEBUG_OBJECT (filter_element, "finalize"); /* clean up object here */ if (filter_element->priv->filter_factory != NULL) { g_free (filter_element->priv->filter_factory); filter_element->priv->filter_factory = NULL; } g_rec_mutex_clear (&filter_element->priv->mutex); G_OBJECT_CLASS (kms_filter_element_parent_class)->finalize (object); } static void kms_filter_element_class_init (KmsFilterElementClass * klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); gst_element_class_set_static_metadata (GST_ELEMENT_CLASS (klass), "FilterElement", "Generic/Filter", "Kurento filter_element", "<NAME> <<EMAIL>>"); gobject_class->dispose = kms_filter_element_dispose; gobject_class->finalize = kms_filter_element_finalize; gobject_class->set_property = kms_filter_element_set_property; gobject_class->get_property = kms_filter_element_get_property; /* define properties */ g_object_class_install_property (gobject_class, PROP_FILTER_FACTORY, g_param_spec_string ("filter-factory", "filter-factory", "Factory name of the filter", NULL, G_PARAM_READWRITE | GST_PARAM_MUTABLE_READY)); g_object_class_install_property (gobject_class, PROP_FILTER, g_param_spec_object ("filter", "filter", "Filter currently used", GST_TYPE_ELEMENT, G_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_FILTER_TYPE, g_param_spec_enum ("type", "Filter element type", "type of the filter", KMS_TYPE_FILTER_TYPE, DEFAULT_FILTER_TYPE, G_PARAM_READWRITE)); /* Registers a private structure for the instantiatable type */ g_type_class_add_private (klass, sizeof (KmsFilterElementPrivate)); } static void kms_filter_element_init (KmsFilterElement * self) { self->priv = KMS_FILTER_ELEMENT_GET_PRIVATE (self); g_rec_mutex_init (&self->priv->mutex); self->priv->filter = NULL; self->priv->filter_factory = NULL; } gboolean kms_filter_element_plugin_init (GstPlugin * plugin) { return gst_element_register (plugin, PLUGIN_NAME, GST_RANK_NONE, KMS_TYPE_FILTER_ELEMENT); }
bjxagu/kms-core
src/gst-plugins/commons/sdpagent/kmssdppayloadmanager.c
/* * (C) Copyright 2015 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "kmssdpagent.h" #include "kmssdppayloadmanager.h" #include "kmsisdppayloadmanager.h" #define OBJECT_NAME "sdppayloadmanager" GST_DEBUG_CATEGORY_STATIC (kms_sdp_payload_manager_debug_category); #define GST_CAT_DEFAULT kms_sdp_payload_manager_debug_category #define parent_class kms_sdp_payload_manager_parent_class static void kms_i_sdp_playload_manager_iface_init (KmsISdpPayloadManagerInterface * iface); G_DEFINE_TYPE_WITH_CODE (KmsSdpPayloadManager, kms_sdp_payload_manager, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE (KMS_TYPE_I_SDP_PAYLOAD_MANAGER, kms_i_sdp_playload_manager_iface_init); GST_DEBUG_CATEGORY_INIT (kms_sdp_payload_manager_debug_category, OBJECT_NAME, 0, "debug category for sdp rtp savpf media_handler")); #define MIN_DYNAMIC_PAYLOAD 96 #define MAX_DYNAMIC_PAYLOAD 127 #define KMS_SDP_PAYLOAD_MANAGER_GET_PRIVATE(obj) ( \ G_TYPE_INSTANCE_GET_PRIVATE ( \ (obj), \ KMS_TYPE_SDP_PAYLOAD_MANAGER, \ KmsSdpPayloadManagerPrivate \ ) \ ) struct _KmsSdpPayloadManagerPrivate { guint counter; /* atomic */ }; static void kms_sdp_payload_manager_class_init (KmsSdpPayloadManagerClass * klass) { g_type_class_add_private (klass, sizeof (KmsSdpPayloadManagerPrivate)); } static void kms_sdp_payload_manager_init (KmsSdpPayloadManager * self) { self->priv = KMS_SDP_PAYLOAD_MANAGER_GET_PRIVATE (self); self->priv->counter = MIN_DYNAMIC_PAYLOAD; } KmsSdpPayloadManager * kms_sdp_payload_manager_new () { KmsSdpPayloadManager *obj; obj = KMS_SDP_PAYLOAD_MANAGER (g_object_new (KMS_TYPE_SDP_PAYLOAD_MANAGER, NULL)); return obj; } gint kms_sdp_payload_manager_get_dynamic_pt (KmsISdpPayloadManager * obj, GError ** error) { KmsSdpPayloadManager *self = KMS_SDP_PAYLOAD_MANAGER (obj); gint val; val = g_atomic_int_add (&self->priv->counter, 1); if (val <= MAX_DYNAMIC_PAYLOAD) { return val; } g_set_error_literal (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_INVALID_PARAMETER, "Not more dynamic payload types available"); return -1; } static void kms_i_sdp_playload_manager_iface_init (KmsISdpPayloadManagerInterface * iface) { iface->get_dynamic_pt = kms_sdp_payload_manager_get_dynamic_pt; }
bjxagu/kms-core
src/gst-plugins/commons/sdp_utils.h
/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef __SDP_H__ #define __SDP_H__ #include <gst/sdp/gstsdpmessage.h> #include "gstsdpdirection.h" #define SENDONLY_STR "sendonly" #define RECVONLY_STR "recvonly" #define SENDRECV_STR "sendrecv" #define INACTIVE_STR "inactive" #define RTCP_FB "rtcp-fb" #define RTCP_FB_FIR "ccm fir" #define RTCP_FB_NACK "nack" #define RTCP_FB_PLI "nack pli" #define RTCP_FB_REMB "goog-remb" #define EXT_MAP "extmap" typedef gboolean (*GstSDPMediaFunc) (const GstSDPMedia *media, gpointer user_data); typedef gboolean (*GstSDPIntersectMediaFunc) (const GstSDPAttribute *attr, gpointer user_data); gboolean sdp_utils_is_attribute_in_media (const GstSDPMedia * media, const GstSDPAttribute * attr); gboolean sdp_utils_attribute_is_direction (const GstSDPAttribute * attr, GstSDPDirection * direction); guint sdp_utils_media_get_ssrc (const GstSDPMedia * media); guint sdp_utils_media_get_fid_ssrc (const GstSDPMedia * media, guint pos); GstSDPDirection sdp_utils_media_config_get_direction (const GstSDPMedia * media); gboolean sdp_utils_media_config_set_direction (GstSDPMedia * media, GstSDPDirection direction); const gchar *sdp_utils_sdp_media_get_rtpmap (const GstSDPMedia * media, const gchar * format); const gchar * sdp_utils_sdp_media_get_fmtp (const GstSDPMedia * media, const gchar * format); gboolean sdp_utils_intersect_session_attributes (const GstSDPMessage * msg, GstSDPIntersectMediaFunc func, gpointer user_data); gboolean sdp_utils_intersect_media_attributes (const GstSDPMedia * offer, GstSDPIntersectMediaFunc func, gpointer user_data); const gchar *sdp_utils_get_attr_map_value (const GstSDPMedia * media, const gchar *name, const gchar * fmt); gboolean sdp_utils_for_each_media (const GstSDPMessage * msg, GstSDPMediaFunc func, gpointer user_data); gboolean sdp_utils_media_is_active (const GstSDPMedia * media, gboolean offerer); gboolean sdp_utils_rtcp_fb_attr_check_type (const gchar * attr, const gchar * pt, const gchar * type); gboolean sdp_utils_media_has_remb (const GstSDPMedia * media); gboolean sdp_utils_media_has_rtcp_nack (const GstSDPMedia * media); gboolean sdp_utils_equal_medias (const GstSDPMedia * m1, const GstSDPMedia * m2); gboolean sdp_utils_equal_messages (const GstSDPMessage * msg1, const GstSDPMessage * msg2); gboolean sdp_utils_get_data_from_rtpmap (const gchar * rtpmap, gchar ** codec_name, gint * clock_rate); gboolean sdp_utils_get_data_from_rtpmap_codec (const GstSDPMedia * media, const gchar * codec, gint *pt, gint * clock_rate); gboolean sdp_utils_is_pt_in_fmts (const GstSDPMedia * media, gint pt); gint sdp_utils_get_pt_for_codec_name (const GstSDPMedia *media, const gchar *codec_name); #endif /* __SDP_H__ */
bjxagu/kms-core
src/gst-plugins/commons/kmshubport.h
/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _KMS_HUB_PORT_H_ #define _KMS_HUB_PORT_H_ #include "kmselement.h" #define HUB_AUDIO_SINK_PAD "hub_audio_sink" #define HUB_VIDEO_SINK_PAD "hub_video_sink" #define HUB_AUDIO_SRC_PAD "hub_audio_src" #define HUB_VIDEO_SRC_PAD "hub_video_src" G_BEGIN_DECLS #define KMS_TYPE_HUB_PORT kms_hub_port_get_type() #define KMS_HUB_PORT(obj) ( \ G_TYPE_CHECK_INSTANCE_CAST( \ (obj), \ KMS_TYPE_HUB_PORT, \ KmsHubPort \ ) \ ) #define KMS_HUB_PORT_CLASS(klass) ( \ G_TYPE_CHECK_CLASS_CAST ( \ (klass), \ KMS_TYPE_HUB_PORT, \ KmsHubPortClass \ ) \ ) #define KMS_IS_HUB_PORT(obj) ( \ G_TYPE_CHECK_INSTANCE_TYPE ( \ (obj), \ KMS_TYPE_HUB_PORT \ ) \ ) #define KMS_IS_HUB_PORT_CLASS(klass) ( \ G_TYPE_CHECK_CLASS_TYPE((klass), \ KMS_TYPE_HUB_PORT) \ ) typedef struct _KmsHubPort KmsHubPort; typedef struct _KmsHubPortClass KmsHubPortClass; typedef struct _KmsHubPortPrivate KmsHubPortPrivate; struct _KmsHubPort { KmsElement parent; /*< private > */ KmsHubPortPrivate *priv; }; struct _KmsHubPortClass { KmsElementClass parent_class; }; GType kms_hub_port_get_type (void); gboolean kms_hub_port_plugin_init (GstPlugin * plugin); void kms_hub_port_unhandled (KmsHubPort * self); G_END_DECLS #endif /* _KMS_HUB_PORT_H_ */
bjxagu/kms-core
src/gst-plugins/commons/kmsremb.c
<reponame>bjxagu/kms-core<gh_stars>1-10 /* * (C) Copyright 2014 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "kmsremb.h" #include "kmsrtcp.h" #include "constants.h" #define GST_CAT_DEFAULT kmsutils GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "kmsremb" #define REMB_MIN 30000 /* bps */ #define REMB_MAX 2000000 /* bps */ #define KMS_REMB_REMOTE "kms-remb-remote" G_DEFINE_QUARK (KMS_REMB_REMOTE, kms_remb_remote); #define KMS_REMB_LOCAL "kms-remb-local" G_DEFINE_QUARK (KMS_REMB_LOCAL, kms_remb_local); #define DEFAULT_REMB_PACKETS_RECV_INTERVAL_TOP 100 #define DEFAULT_REMB_EXPONENTIAL_FACTOR 0.04 #define DEFAULT_REMB_LINEAL_FACTOR_MIN 50 /* bps */ #define DEFAULT_REMB_LINEAL_FACTOR_GRADE ((60 * RTCP_MIN_INTERVAL)/ 1000) /* Reach last top bitrate in 60secs aprox. */ #define DEFAULT_REMB_DECREMENT_FACTOR 0.5 #define DEFAULT_REMB_THRESHOLD_FACTOR 0.8 #define DEFAULT_REMB_UP_LOSSES 12 /* 4% losses */ #define REMB_MAX_FACTOR_INPUT_BR 2 static void kms_remb_base_destroy (KmsRembBase * rb) { g_signal_handler_disconnect (rb->rtpsess, rb->signal_id); rb->signal_id = 0; g_object_set_qdata (rb->rtpsess, kms_remb_local_quark (), NULL); g_object_set_qdata (rb->rtpsess, kms_remb_remote_quark (), NULL); g_clear_object (&rb->rtpsess); g_rec_mutex_clear (&rb->mutex); g_hash_table_unref (rb->remb_stats); } static void kms_remb_base_create (KmsRembBase * rb, GObject * rtpsess) { rb->rtpsess = g_object_ref (rtpsess); g_rec_mutex_init (&rb->mutex); rb->remb_stats = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, (GDestroyNotify) kms_utils_destroy_guint); } static void kms_remb_base_update_stats (KmsRembBase * rb, guint ssrc, guint bitrate) { guint *value; KMS_REMB_BASE_LOCK (rb); if (g_hash_table_contains (rb->remb_stats, GUINT_TO_POINTER (ssrc))) { value = (guint *) g_hash_table_lookup (rb->remb_stats, GUINT_TO_POINTER (ssrc)); } else { value = g_slice_new0 (guint); g_hash_table_insert (rb->remb_stats, GUINT_TO_POINTER (ssrc), value); } *value = bitrate; KMS_REMB_BASE_UNLOCK (rb); } /* KmsRembLocal begin */ typedef struct _KmsRlRemoteSession { GObject *rtpsess; guint ssrc; guint64 last_packets_received_expected; } KmsRlRemoteSession; static KmsRlRemoteSession * kms_rl_remote_session_create (GObject * rtpsess, guint ssrc) { KmsRlRemoteSession *rlrs = g_slice_new0 (KmsRlRemoteSession); rlrs->rtpsess = g_object_ref (rtpsess); rlrs->ssrc = ssrc; return rlrs; } static void kms_rl_remote_session_create_destroy (KmsRlRemoteSession * rlrs) { g_clear_object (&rlrs->rtpsess); g_slice_free (KmsRlRemoteSession, rlrs); } typedef struct _GetRtpSessionsInfo { guint count; guint64 bitrate; guint fraction_lost_accumulative; /* the sum of all sessions, it should be normalized */ guint64 packets_received_expected_interval_accumulative; guint64 octets_received; guint64 packets_received; } GetRtpSessionsInfo; static void get_sessions_info (KmsRlRemoteSession * rlrs, GetRtpSessionsInfo * data) { GValueArray *arr = NULL; GValue *val; guint i; g_object_get (rlrs->rtpsess, "sources", &arr, NULL); if (arr == NULL) { GST_WARNING_OBJECT (rlrs->rtpsess, "Sources array not found"); return; } for (i = 0; i < arr->n_values; i++) { GObject *source; guint ssrc; val = g_value_array_get_nth (arr, i); source = g_value_get_object (val); g_object_get (source, "ssrc", &ssrc, NULL); GST_TRACE_OBJECT (source, "source ssrc: %u", ssrc); if (ssrc == rlrs->ssrc) { GstStructure *s; guint64 bitrate, octets_received, packets_received; gint packets_lost; guint fraction_lost; guint64 packets_received_expected, packets_received_expected_interval; g_object_get (source, "stats", &s, NULL); GST_TRACE_OBJECT (source, "stats: %" GST_PTR_FORMAT, s); if (!gst_structure_get_uint64 (s, "bitrate", &bitrate) || !gst_structure_get_uint64 (s, "octets-received", &octets_received) || !gst_structure_get_uint (s, "sent-rb-fractionlost", &fraction_lost) || !gst_structure_get_uint64 (s, "packets-received", &packets_received) || !gst_structure_get_int (s, "packets-lost", &packets_lost)) { gst_structure_free (s); break; } gst_structure_free (s); packets_received_expected = packets_received + packets_lost; packets_received_expected_interval = packets_received_expected - rlrs->last_packets_received_expected; rlrs->last_packets_received_expected = packets_received_expected; data->bitrate += bitrate; data->fraction_lost_accumulative += fraction_lost * packets_received_expected_interval; data->packets_received_expected_interval_accumulative += packets_received_expected_interval; data->octets_received += octets_received; data->packets_received += packets_received; data->count++; GST_TRACE_OBJECT (source, "packets_received: %" G_GUINT64_FORMAT ", packets_lost: %" G_GUINT32_FORMAT ", packets_received_expected_interval: %" G_GUINT64_FORMAT ", packets_received_expected_interval_accumulative: %" G_GUINT64_FORMAT, packets_received, packets_lost, packets_received_expected_interval, data->packets_received_expected_interval_accumulative); break; } } g_value_array_free (arr); } static gboolean get_video_recv_info (KmsRembLocal * rl, guint64 * bitrate, guint * fraction_lost, guint64 * packets_rcv_interval) { GetRtpSessionsInfo data; GstClockTime current_time; if (!KMS_REMB_BASE (rl)->rtpsess) { GST_WARNING ("Session object does not exist"); return FALSE; } data.count = 0; data.bitrate = 0; data.fraction_lost_accumulative = 0; data.packets_received_expected_interval_accumulative = 0; data.octets_received = 0; data.packets_received = 0; g_slist_foreach (rl->remote_sessions, (GFunc) get_sessions_info, &data); if (data.count == 0 || data.packets_received_expected_interval_accumulative == 0) { GST_DEBUG ("Any data updated"); return FALSE; } current_time = kms_utils_get_time_nsecs (); /* Normalize fraction_lost */ *fraction_lost = data.fraction_lost_accumulative / data.packets_received_expected_interval_accumulative; *bitrate = data.bitrate; if (rl->last_time != 0) { GstClockTime elapsed = current_time - rl->last_time; guint64 bytes_handled = data.octets_received - rl->last_octets_received; *bitrate = gst_util_uint64_scale (bytes_handled, 8 * GST_SECOND, elapsed); GST_TRACE_OBJECT (KMS_REMB_BASE (rl)->rtpsess, "Elapsed %" G_GUINT64_FORMAT " bytes %" G_GUINT64_FORMAT ", rate %" G_GUINT64_FORMAT, elapsed, bytes_handled, *bitrate); } rl->last_time = current_time; rl->last_octets_received = data.octets_received; *packets_rcv_interval = data.packets_received - rl->last_packets_received; rl->last_packets_received = data.packets_received; return TRUE; } static gboolean kms_remb_local_update (KmsRembLocal * rl) { guint64 bitrate, packets_rcv_interval; guint fraction_lost, packets_rcv_interval_top; if (!get_video_recv_info (rl, &bitrate, &fraction_lost, &packets_rcv_interval)) { return FALSE; } if (!rl->probed) { if (bitrate == 0) { return FALSE; } rl->remb = bitrate; rl->probed = TRUE; } packets_rcv_interval_top = MAX (rl->packets_recv_interval_top, packets_rcv_interval); rl->fraction_lost_record = (rl->fraction_lost_record * (packets_rcv_interval_top - packets_rcv_interval) + fraction_lost * packets_rcv_interval) / packets_rcv_interval_top; rl->max_br = MAX (rl->max_br, bitrate); if (rl->avg_br == 0) { rl->avg_br = bitrate; } else { rl->avg_br = (rl->avg_br * 7 + bitrate) / 8; } GST_TRACE_OBJECT (KMS_REMB_BASE (rl)->rtpsess, "packets_rcv_interval: %" G_GUINT64_FORMAT ", fraction_lost: %" G_GUINT32_FORMAT ", fraction_lost_record: %" G_GUINT64_FORMAT, packets_rcv_interval, fraction_lost, rl->fraction_lost_record); if (rl->fraction_lost_record == 0) { gint remb_base, remb_new; remb_base = MAX (rl->remb, rl->max_br); if (remb_base < rl->threshold) { GST_TRACE_OBJECT (KMS_REMB_BASE (rl)->rtpsess, "A.1) Exponential (%f)", rl->exponential_factor); remb_new = remb_base * (1 + rl->exponential_factor); } else { GST_TRACE_OBJECT (KMS_REMB_BASE (rl)->rtpsess, "A.2) Lineal (%" G_GUINT32_FORMAT ")", rl->lineal_factor); remb_new = remb_base + rl->lineal_factor; } rl->remb = MAX (rl->remb, remb_new); } else { gint remb_base, lineal_factor_new; remb_base = MAX (rl->remb, rl->avg_br); rl->threshold = remb_base * rl->threshold_factor; lineal_factor_new = (remb_base - rl->threshold) / rl->lineal_factor_grade; rl->lineal_factor = MAX (rl->lineal_factor_min, lineal_factor_new); if (rl->fraction_lost_record < rl->up_losses) { GST_TRACE_OBJECT (KMS_REMB_BASE (rl)->rtpsess, "B) Assumable losses"); rl->remb = MIN (rl->remb, rl->max_br); } else { GST_TRACE_OBJECT (KMS_REMB_BASE (rl)->rtpsess, "C) Too losses"); rl->remb = remb_base * rl->decrement_factor; rl->fraction_lost_record = 0; rl->max_br = 0; rl->avg_br = 0; } } rl->remb = MIN (rl->remb, rl->max_br * REMB_MAX_FACTOR_INPUT_BR); if (rl->max_bw > 0) { rl->remb = MIN (rl->remb, rl->max_bw * 1000); } GST_TRACE_OBJECT (KMS_REMB_BASE (rl)->rtpsess, "REMB: %" G_GUINT32_FORMAT ", TH: %" G_GUINT32_FORMAT ", fraction_lost: %d, fraction_lost_record: %" G_GUINT64_FORMAT ", bitrate: %" G_GUINT64_FORMAT "," " max_br: %" G_GUINT32_FORMAT ", avg_br: %" G_GUINT32_FORMAT, rl->remb, rl->threshold, fraction_lost, rl->fraction_lost_record, bitrate, rl->max_br, rl->avg_br); return TRUE; } typedef struct _AddSsrcsData { KmsRembLocal *rl; KmsRTCPPSFBAFBREMBPacket *remb_packet; } AddSsrcsData; static void add_ssrcs (KmsRlRemoteSession * rlrs, AddSsrcsData * data) { KmsRembBase *rb = KMS_REMB_BASE (data->rl); data->remb_packet->ssrcs[data->remb_packet->n_ssrcs] = rlrs->ssrc; data->remb_packet->n_ssrcs++; GST_TRACE_OBJECT (rb->rtpsess, "Sending REMB (bitrate: %" G_GUINT32_FORMAT ", ssrc: %" G_GUINT32_FORMAT ")", data->remb_packet->bitrate, rlrs->ssrc); kms_remb_base_update_stats (rb, rlrs->ssrc, data->remb_packet->bitrate); } static void on_sending_rtcp (GObject * sess, GstBuffer * buffer, gboolean is_early, gboolean * do_not_supress) { KmsRembLocal *rl; GstClockTime current_time, elapsed; KmsRTCPPSFBAFBREMBPacket remb_packet; GstRTCPBuffer rtcp = { NULL, }; GstRTCPPacket packet; guint packet_ssrc; AddSsrcsData data; rl = g_object_get_qdata (sess, kms_remb_local_quark ()); if (!rl) { GST_WARNING ("Invalid RembLocal"); return; } current_time = kms_utils_get_time_nsecs (); elapsed = current_time - rl->last_sent_time; if (rl->last_sent_time != 0 && (elapsed < REMB_MAX_INTERVAL * GST_MSECOND)) { GST_TRACE_OBJECT (sess, "Not sending, interval < %u ms", REMB_MAX_INTERVAL); return; } if (!gst_rtcp_buffer_map (buffer, GST_MAP_READWRITE, &rtcp)) { GST_WARNING_OBJECT (sess, "Cannot map buffer to RTCP"); return; } if (!gst_rtcp_buffer_add_packet (&rtcp, GST_RTCP_TYPE_PSFB, &packet)) { GST_WARNING_OBJECT (sess, "Cannot add RTCP packet"); goto end; } if (!kms_remb_local_update (rl)) { goto end; } remb_packet.bitrate = rl->remb; if (rl->event_manager != NULL) { guint remb_local_max; remb_local_max = kms_utils_remb_event_manager_get_min (rl->event_manager); if (remb_local_max > 0) { GST_TRACE_OBJECT (sess, "REMB local max: %" G_GUINT32_FORMAT, remb_local_max); remb_packet.bitrate = MIN (remb_local_max, rl->remb); } } if (rl->min_bw > 0) { remb_packet.bitrate = MAX (remb_packet.bitrate, rl->min_bw * 1000); } else { remb_packet.bitrate = MAX (remb_packet.bitrate, REMB_MIN); } remb_packet.n_ssrcs = 0; data.rl = rl; data.remb_packet = &remb_packet; g_slist_foreach (rl->remote_sessions, (GFunc) add_ssrcs, &data); g_object_get (sess, "internal-ssrc", &packet_ssrc, NULL); if (!kms_rtcp_psfb_afb_remb_marshall_packet (&packet, &remb_packet, packet_ssrc)) { gst_rtcp_packet_remove (&packet); } rl->last_sent_time = current_time; end: gst_rtcp_buffer_unmap (&rtcp); } void kms_remb_local_destroy (KmsRembLocal * rl) { if (rl == NULL) { return; } if (rl->event_manager != NULL) { kms_utils_remb_event_manager_destroy (rl->event_manager); } g_slist_free_full (rl->remote_sessions, (GDestroyNotify) kms_rl_remote_session_create_destroy); kms_remb_base_destroy (KMS_REMB_BASE (rl)); g_slice_free (KmsRembLocal, rl); } KmsRembLocal * kms_remb_local_create (GObject * rtpsess, guint min_bw, guint max_bw) { KmsRembLocal *rl = g_slice_new0 (KmsRembLocal); g_object_set_qdata (rtpsess, kms_remb_local_quark (), rl); rl->base.signal_id = g_signal_connect (rtpsess, "on-sending-rtcp", G_CALLBACK (on_sending_rtcp), NULL); kms_remb_base_create (KMS_REMB_BASE (rl), rtpsess); rl->min_bw = min_bw; rl->max_bw = max_bw; rl->probed = FALSE; rl->remb = REMB_MAX; rl->threshold = REMB_MAX; rl->lineal_factor = DEFAULT_REMB_LINEAL_FACTOR_MIN; rl->packets_recv_interval_top = DEFAULT_REMB_PACKETS_RECV_INTERVAL_TOP; rl->exponential_factor = DEFAULT_REMB_EXPONENTIAL_FACTOR; rl->lineal_factor_min = DEFAULT_REMB_LINEAL_FACTOR_MIN; rl->lineal_factor_grade = DEFAULT_REMB_LINEAL_FACTOR_GRADE; rl->decrement_factor = DEFAULT_REMB_DECREMENT_FACTOR; rl->threshold_factor = DEFAULT_REMB_THRESHOLD_FACTOR; rl->up_losses = DEFAULT_REMB_UP_LOSSES; return rl; } void kms_remb_local_add_remote_session (KmsRembLocal * rl, GObject * rtpsess, guint ssrc) { KmsRlRemoteSession *rlrs = kms_rl_remote_session_create (rtpsess, ssrc); rl->remote_sessions = g_slist_append (rl->remote_sessions, rlrs); } void kms_remb_local_set_params (KmsRembLocal * rl, GstStructure * params) { gfloat auxf; gint auxi; gboolean is_set; is_set = gst_structure_get (params, "packets-recv-interval-top", G_TYPE_INT, &auxi, NULL); if (is_set) { if (auxi <= 0) { GST_WARNING ("'packets-recv-interval-top' must be greater than 0. Setting to 1."); auxi = 1; } rl->packets_recv_interval_top = auxi; } is_set = gst_structure_get (params, "exponential-factor", G_TYPE_FLOAT, &auxf, NULL); if (is_set) { rl->exponential_factor = auxf; } is_set = gst_structure_get (params, "lineal-factor-min", G_TYPE_INT, &auxi, NULL); if (is_set) { rl->lineal_factor_min = auxi; } is_set = gst_structure_get (params, "lineal-factor-grade", G_TYPE_INT, &auxi, NULL); if (is_set) { rl->lineal_factor_grade = auxi; } is_set = gst_structure_get (params, "decrement-factor", G_TYPE_FLOAT, &auxf, NULL); if (is_set) { rl->decrement_factor = auxf; } is_set = gst_structure_get (params, "threshold-factor", G_TYPE_FLOAT, &auxf, NULL); if (is_set) { rl->threshold_factor = auxf; } is_set = gst_structure_get (params, "up-losses", G_TYPE_INT, &auxi, NULL); if (is_set) { rl->up_losses = auxi; } } void kms_remb_local_get_params (KmsRembLocal * rl, GstStructure ** params) { gst_structure_set (*params, "packets-recv-interval-top", G_TYPE_INT, rl->packets_recv_interval_top, "exponential-factor", G_TYPE_FLOAT, rl->exponential_factor, "lineal-factor-min", G_TYPE_INT, rl->lineal_factor_min, "lineal-factor-grade", G_TYPE_FLOAT, rl->lineal_factor_grade, "decrement-factor", G_TYPE_FLOAT, rl->decrement_factor, "threshold-factor", G_TYPE_FLOAT, rl->threshold_factor, "up-losses", G_TYPE_INT, rl->up_losses, NULL); } /* KmsRembLocal end */ /* KmsRembRemote begin */ #define DEFAULT_REMB_ON_CONNECT 300000 /* bps */ static void send_remb_event (KmsRembRemote * rm, guint bitrate, guint ssrc) { GstEvent *event; guint br, min = 0, max = 0; /* TODO: use g_atomic */ if (rm->pad_event == NULL) { return; } br = bitrate; if (rm->min_bw > 0) { min = rm->min_bw * 1000; br = MAX (br, min); } if (rm->max_bw > 0) { max = rm->max_bw * 1000; br = MIN (br, max); } GST_TRACE_OBJECT (KMS_REMB_BASE (rm)->rtpsess, "bitrate: %" G_GUINT32_FORMAT ", ssrc: %" G_GUINT32_FORMAT ", range [%" G_GUINT32_FORMAT ", %" G_GUINT32_FORMAT "], event bitrate: %" G_GUINT32_FORMAT, bitrate, ssrc, min, max, br); event = kms_utils_remb_event_upstream_new (br, ssrc); gst_pad_push_event (rm->pad_event, event); } static GstPadProbeReturn send_remb_event_probe (GstPad * pad, GstPadProbeInfo * info, gpointer user_data) { KmsRembRemote *rm = user_data; GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info); if (GST_EVENT_TYPE (event) != GST_EVENT_CAPS) { return GST_PAD_PROBE_OK; }; send_remb_event (rm, rm->remb_on_connect, rm->local_ssrc); return GST_PAD_PROBE_REMOVE; } static void kms_remb_remote_update (KmsRembRemote * rm, KmsRTCPPSFBAFBREMBPacket * remb_packet) { guint32 br_send; if (remb_packet->n_ssrcs == 0) { GST_WARNING_OBJECT (KMS_REMB_BASE (rm)->rtpsess, "REMB packet without any SSRC"); return; } else if (remb_packet->n_ssrcs > 1) { GST_FIXME_OBJECT (KMS_REMB_BASE (rm)->rtpsess, "REMB packet with %" G_GUINT32_FORMAT " SSRCs." " A inconsistent management could take place", remb_packet->n_ssrcs); } br_send = remb_packet->bitrate; if (!rm->probed) { if ((remb_packet->bitrate < rm->remb_on_connect) && (remb_packet->bitrate >= rm->remb)) { GST_DEBUG_OBJECT (KMS_REMB_BASE (rm)->rtpsess, "Not probed: sending remb_on_connect value"); br_send = rm->remb_on_connect; rm->remb = remb_packet->bitrate; } else { rm->probed = TRUE; } } send_remb_event (rm, br_send, remb_packet->ssrcs[0]); rm->remb = remb_packet->bitrate; } static void kms_remb_remote_update_target_ssrcs_stats (KmsRembRemote * rm, KmsRTCPPSFBAFBREMBPacket * remb_packet) { guint i; for (i = 0; i < remb_packet->n_ssrcs; i++) { kms_remb_base_update_stats (KMS_REMB_BASE (rm), remb_packet->ssrcs[i], remb_packet->bitrate); } } static void process_psfb_afb (GObject * sess, guint ssrc, GstBuffer * fci_buffer) { KmsRembRemote *rm; KmsRTCPPSFBAFBBuffer afb_buffer = { NULL, }; KmsRTCPPSFBAFBPacket afb_packet; KmsRTCPPSFBAFBREMBPacket remb_packet; KmsRTCPPSFBAFBType type; if (!G_IS_OBJECT (sess)) { GST_WARNING ("Invalid session object"); return; } rm = g_object_get_qdata (sess, kms_remb_remote_quark ()); if (!rm) { GST_WARNING ("Invalid RembRemote"); return; } if (!kms_rtcp_psfb_afb_buffer_map (fci_buffer, GST_MAP_READ, &afb_buffer)) { GST_WARNING_OBJECT (fci_buffer, "Buffer cannot be mapped"); return; } if (!kms_rtcp_psfb_afb_get_packet (&afb_buffer, &afb_packet)) { GST_WARNING_OBJECT (fci_buffer, "Cannot get RTCP PSFB AFB packet"); goto end; } type = kms_rtcp_psfb_afb_packet_get_type (&afb_packet); switch (type) { case KMS_RTCP_PSFB_AFB_TYPE_REMB: kms_rtcp_psfb_afb_remb_get_packet (&afb_packet, &remb_packet); kms_remb_remote_update (rm, &remb_packet); kms_remb_remote_update_target_ssrcs_stats (rm, &remb_packet); break; default: break; } end: kms_rtcp_psfb_afb_buffer_unmap (&afb_buffer); } static void on_feedback_rtcp (GObject * sess, guint type, guint fbtype, guint sender_ssrc, guint media_ssrc, GstBuffer * fci) { switch (type) { case GST_RTCP_TYPE_RTPFB: break; case GST_RTCP_TYPE_PSFB: switch (fbtype) { case GST_RTCP_PSFB_TYPE_AFB: process_psfb_afb (sess, sender_ssrc, fci); break; default: break; } break; default: break; } } void kms_remb_remote_destroy (KmsRembRemote * rm) { if (rm == NULL) { return; } if (rm->pad_event != NULL) { g_object_unref (rm->pad_event); } kms_remb_base_destroy (KMS_REMB_BASE (rm)); g_slice_free (KmsRembRemote, rm); } KmsRembRemote * kms_remb_remote_create (GObject * rtpsess, guint local_ssrc, guint min_bw, guint max_bw, GstPad * pad) { KmsRembRemote *rm = g_slice_new0 (KmsRembRemote); g_object_set_qdata (rtpsess, kms_remb_remote_quark (), rm); rm->base.signal_id = g_signal_connect (rtpsess, "on-feedback-rtcp", G_CALLBACK (on_feedback_rtcp), NULL); kms_remb_base_create (KMS_REMB_BASE (rm), rtpsess); rm->local_ssrc = local_ssrc; rm->min_bw = min_bw; rm->max_bw = max_bw; rm->remb_on_connect = DEFAULT_REMB_ON_CONNECT; rm->pad_event = g_object_ref (pad); gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM, send_remb_event_probe, rm, NULL); return rm; } void kms_remb_remote_set_params (KmsRembRemote * rm, GstStructure * params) { gint auxi; gboolean is_set; is_set = gst_structure_get (params, "remb-on-connect", G_TYPE_INT, &auxi, NULL); if (is_set) { rm->remb_on_connect = auxi; } } void kms_remb_remote_get_params (KmsRembRemote * rm, GstStructure ** params) { gst_structure_set (*params, "remb-on-connect", G_TYPE_INT, rm->remb_on_connect, NULL); } /* KmsRembRemote end */ static void init_debug (void) __attribute__ ((constructor)); static void init_debug (void) { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); }
bjxagu/kms-core
src/gst-plugins/commons/sdpagent/kmssdpcontext.h
<reponame>bjxagu/kms-core /* * (C) Copyright 2015 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _KMS_SDP_CONTEXT_H_ #define _KMS_SDP_CONTEXT_H_ #include <gst/sdp/gstsdpmessage.h> typedef enum { IPV4, IPV6 } SdpIPv; typedef struct _SdpMediaGroup SdpMediaGroup; typedef struct _SdpMediaConfig SdpMediaConfig; typedef struct _SdpMessageContext SdpMessageContext; typedef enum { KMS_SDP_UNDEFINED, KMS_SDP_OFFER, KMS_SDP_ANSWER } KmsSdpMessageType; const gchar * kms_sdp_message_context_ipv2str (SdpIPv ipv); SdpMessageContext *kms_sdp_message_context_new (GError **error); gboolean kms_sdp_message_context_set_origin(SdpMessageContext *ctx, const GstSDPOrigin *origin, GError **error); SdpMessageContext * kms_sdp_message_context_ref (SdpMessageContext *ctx); void kms_sdp_message_context_unref (SdpMessageContext *ctx); SdpMessageContext *kms_sdp_message_context_new_from_sdp (GstSDPMessage *sdp, GError **error); gboolean kms_sdp_message_context_set_common_session_attributes (SdpMessageContext *ctx, const GstSDPMessage *msg, GError **error); SdpMediaConfig * kms_sdp_message_context_add_media (SdpMessageContext *ctx, GstSDPMedia *media, GError **error); gint kms_sdp_media_config_get_id (SdpMediaConfig * mconf); const gchar* kms_sdp_media_config_get_mid (SdpMediaConfig * mconf); gboolean kms_sdp_media_config_is_rtcp_mux (SdpMediaConfig * mconf); SdpMediaGroup * kms_sdp_media_config_get_group (SdpMediaConfig * mconf); GstSDPMedia * kms_sdp_media_config_get_sdp_media (SdpMediaConfig * mconf); gboolean kms_sdp_media_config_is_inactive (SdpMediaConfig * mconf); gint kms_sdp_media_config_get_abs_send_time_id (SdpMediaConfig * mconf); GstSDPMessage * kms_sdp_message_context_pack (SdpMessageContext *ctx, GError **error); SdpMediaGroup * kms_sdp_message_context_create_group (SdpMessageContext *ctx, guint gid); gboolean kms_sdp_message_context_has_groups (SdpMessageContext *ctx); gint kms_sdp_media_group_get_id (SdpMediaGroup *group); SdpMediaGroup * kms_sdp_message_context_get_group (SdpMessageContext *ctx, guint gid); gboolean kms_sdp_message_context_add_media_to_group (SdpMediaGroup *group, SdpMediaConfig *media, GError **error); gboolean kms_sdp_message_context_remove_media_from_group (SdpMediaGroup *group, guint id, GError **error); gboolean kms_sdp_message_context_parse_groups_from_offer (SdpMessageContext *ctx, const GstSDPMessage *offer, GError **error); GstSDPMessage * kms_sdp_message_context_get_sdp_message (SdpMessageContext *ctx); GSList * kms_sdp_message_context_get_medias (SdpMessageContext *ctx); SdpMediaConfig *kms_sdp_message_context_get_media (SdpMessageContext * ctx, guint idx); void kms_sdp_message_context_set_type (SdpMessageContext *ctx, KmsSdpMessageType type); KmsSdpMessageType kms_sdp_message_context_get_type (SdpMessageContext *ctx); #endif /* _KMS_SDP_CONTEXT_ */
bjxagu/kms-core
src/gst-plugins/commons/kmsutils.h
<filename>src/gst-plugins/commons/kmsutils.h /* * (C) Copyright 2013 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef __KMS_UTILS_H__ #define __KMS_UTILS_H__ #include "gst/gst.h" #include "kmsmediatype.h" #include "kmselementpadtype.h" #include "sdpagent/kmssdpcontext.h" G_BEGIN_DECLS typedef void (*KmsPadIterationAction) (GstPad * pad, gpointer data); typedef void (*KmsPadCallback) (GstPad * pad, gpointer data); void kms_element_for_each_src_pad (GstElement * element, KmsPadCallback action, gpointer data); gboolean kms_element_for_each_sink_pad (GstElement * element, KmsPadCallback action, gpointer data); void kms_utils_debug_graph_delay (GstBin * bin, guint interval); gboolean kms_is_valid_uri (const gchar * url); gboolean gst_element_sync_state_with_parent_target_state (GstElement * element); /* Caps */ gboolean kms_utils_caps_are_audio (const GstCaps * caps); gboolean kms_utils_caps_are_video (const GstCaps * caps); gboolean kms_utils_caps_are_rtp (const GstCaps * caps); gboolean kms_utils_caps_are_raw (const GstCaps * caps); GstElement * kms_utils_create_convert_for_caps (const GstCaps * caps); GstElement * kms_utils_create_mediator_element (const GstCaps * caps); GstElement * kms_utils_create_rate_for_caps (const GstCaps * caps); const gchar * kms_utils_get_caps_codec_name_from_sdp (const gchar * codec_name); KmsElementPadType kms_utils_convert_media_type (KmsMediaType media_type); KmsMediaType kms_utils_convert_element_pad_type (KmsElementPadType pad_type); /* key frame management */ void kms_utils_drop_until_keyframe (GstPad *pad, gboolean all_headers); void kms_utils_manage_gaps (GstPad *pad); void kms_utils_control_key_frames_request_duplicates (GstPad *pad); /* Pad blocked action */ void kms_utils_execute_with_pad_blocked (GstPad * pad, gboolean drop, KmsPadCallback func, gpointer userData); /* REMB event */ GstEvent * kms_utils_remb_event_upstream_new (guint bitrate, guint ssrc); gboolean kms_utils_is_remb_event_upstream (GstEvent * event); gboolean kms_utils_remb_event_upstream_parse (GstEvent *event, guint *bitrate, guint *ssrc); typedef struct _RembEventManager RembEventManager; typedef void (*RembBitrateUpdatedCallback) (RembEventManager * manager, guint bitrate, gpointer user_data); RembEventManager * kms_utils_remb_event_manager_create (GstPad *pad); void kms_utils_remb_event_manager_destroy (RembEventManager * manager); void kms_utils_remb_event_manager_pointer_destroy (gpointer manager); guint kms_utils_remb_event_manager_get_min (RembEventManager * manager); void kms_utils_remb_event_manager_set_callback (RembEventManager * manager, RembBitrateUpdatedCallback cb, gpointer data, GDestroyNotify destroy_notify); void kms_utils_remb_event_manager_set_clear_interval (RembEventManager * manager, GstClockTime interval); GstClockTime kms_utils_remb_event_manager_get_clear_interval (RembEventManager * manager); /* time */ GstClockTime kms_utils_get_time_nsecs (); /* RTP connection */ gchar * kms_utils_create_connection_name_from_media_config (SdpMediaConfig * mconf); gboolean kms_utils_contains_proto (const gchar *search_term, const gchar *proto); const GstStructure * kms_utils_get_structure_by_name (const GstStructure *str, const gchar *name); gchar * kms_utils_generate_uuid (); void kms_utils_set_uuid (GObject *obj); const gchar * kms_utils_get_uuid (GObject *obj); const char * kms_utils_media_type_to_str (KmsMediaType type); gchar * kms_utils_generate_fingerprint_from_pem (const gchar * pem); /* Set event function for this pad. This function variant allows to keep */ /* previous callbacks enabled if chain callbacks is TRUE */ void kms_utils_set_pad_event_function_full (GstPad *pad, GstPadEventFunction event, gpointer user_data, GDestroyNotify notify, gboolean chain_callbacks); /* Set query function for this pad. This function variant allows to keep */ /* previous callbacks enabled if chain callbacks is TRUE */ void kms_utils_set_pad_query_function_full (GstPad *pad, GstPadQueryFunction query, gpointer user_data, GDestroyNotify notify, gboolean chain_callbacks); /* Type destroying */ #define KMS_UTILS_DESTROY_H(type) void kms_utils_destroy_##type (type * data); KMS_UTILS_DESTROY_H (guint64) KMS_UTILS_DESTROY_H (gsize) KMS_UTILS_DESTROY_H (GstClockTime) KMS_UTILS_DESTROY_H (gfloat) KMS_UTILS_DESTROY_H (guint) G_END_DECLS #endif /* __KMS_UTILS_H__ */
bjxagu/kms-core
src/gst-plugins/commons/kmshubport.c
/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "kmshubport.h" #include "kmsagnosticcaps.h" #include "kmsutils.h" #define PLUGIN_NAME "hubport" #define KEY_ELEM_DATA "kms-hub-elem-data" G_DEFINE_QUARK (KEY_ELEM_DATA, key_elem_data); #define KEY_TYPE_DATA "kms-hub-type-data" G_DEFINE_QUARK (KEY_TYPE_DATA, key_type_data); #define KEY_PAD_DATA "kms-hub-pad-data" G_DEFINE_QUARK (KEY_PAD_DATA, key_pad_data); GST_DEBUG_CATEGORY_STATIC (kms_hub_port_debug_category); #define GST_CAT_DEFAULT kms_hub_port_debug_category #define KMS_HUB_PORT_GET_PRIVATE(obj) ( \ G_TYPE_INSTANCE_GET_PRIVATE ( \ (obj), \ KMS_TYPE_HUB_PORT, \ KmsHubPortPrivate \ ) \ ) struct _KmsHubPortPrivate { GstPad *audio_internal; GstPad *vieo_internal; }; /* Pad templates */ static GstStaticPadTemplate hub_audio_sink_factory = GST_STATIC_PAD_TEMPLATE (HUB_AUDIO_SINK_PAD, GST_PAD_SINK, GST_PAD_REQUEST, GST_STATIC_CAPS (KMS_AGNOSTIC_AUDIO_CAPS) ); static GstStaticPadTemplate hub_video_sink_factory = GST_STATIC_PAD_TEMPLATE (HUB_VIDEO_SINK_PAD, GST_PAD_SINK, GST_PAD_REQUEST, GST_STATIC_CAPS (KMS_AGNOSTIC_VIDEO_CAPS) ); static GstStaticPadTemplate hub_audio_src_factory = GST_STATIC_PAD_TEMPLATE (HUB_AUDIO_SRC_PAD, GST_PAD_SRC, GST_PAD_SOMETIMES, GST_STATIC_CAPS (KMS_AGNOSTIC_AUDIO_CAPS) ); static GstStaticPadTemplate hub_video_src_factory = GST_STATIC_PAD_TEMPLATE (HUB_VIDEO_SRC_PAD, GST_PAD_SRC, GST_PAD_SOMETIMES, GST_STATIC_CAPS (KMS_AGNOSTIC_VIDEO_CAPS) ); /* class initialization */ G_DEFINE_TYPE_WITH_CODE (KmsHubPort, kms_hub_port, KMS_TYPE_ELEMENT, GST_DEBUG_CATEGORY_INIT (kms_hub_port_debug_category, PLUGIN_NAME, 0, "debug category for hubport element")); static GstPad * kms_hub_port_generate_sink_pad (GstElement * element, GstPadTemplate * templ, const gchar * name, const GstCaps * caps, GstElement * agnosticbin) { GstPad *agnostic_pad, *pad; agnostic_pad = gst_element_get_static_pad (agnosticbin, "sink"); pad = gst_ghost_pad_new_from_template (name, agnostic_pad, templ); g_object_unref (agnostic_pad); if (GST_STATE (element) >= GST_STATE_PAUSED || GST_STATE_PENDING (element) >= GST_STATE_PAUSED || GST_STATE_TARGET (element) >= GST_STATE_PAUSED) { gst_pad_set_active (pad, TRUE); } if (gst_element_add_pad (element, pad)) return pad; GST_ERROR_OBJECT (element, "Cannot add pad %" GST_PTR_FORMAT, pad); g_object_unref (pad); return NULL; } static GstPad * kms_hub_port_request_new_pad (GstElement * element, GstPadTemplate * templ, const gchar * name, const GstCaps * caps) { GstElement *agnosticbin = NULL; if (templ == gst_element_class_get_pad_template (GST_ELEMENT_CLASS (G_OBJECT_GET_CLASS (element)), HUB_AUDIO_SINK_PAD)) { if (g_strcmp0 (name, HUB_AUDIO_SINK_PAD) != 0) { GST_ERROR_OBJECT (element, "Invalid pad name %s for template %" GST_PTR_FORMAT, name, templ); return NULL; } agnosticbin = kms_element_get_audio_agnosticbin (KMS_ELEMENT (element)); } else if (templ == gst_element_class_get_pad_template (GST_ELEMENT_CLASS (G_OBJECT_GET_CLASS (element)), HUB_VIDEO_SINK_PAD)) { if (g_strcmp0 (name, HUB_VIDEO_SINK_PAD) != 0) { GST_ERROR_OBJECT (element, "Invalid pad name %s for template %" GST_PTR_FORMAT, name, templ); return NULL; } agnosticbin = kms_element_get_video_agnosticbin (KMS_ELEMENT (element)); } if (agnosticbin == NULL) { GST_WARNING_OBJECT (element, "No agnosticbin got for template %" GST_PTR_FORMAT, templ); return NULL; } else { return kms_hub_port_generate_sink_pad (element, templ, name, caps, agnosticbin); } } static void kms_hub_port_internal_src_unhandled (KmsHubPort * self, GstPad * pad) { GstPad *sink = g_object_get_qdata (G_OBJECT (pad), key_pad_data_quark ()); g_return_if_fail (sink); kms_element_remove_sink (KMS_ELEMENT (self), sink); g_object_set_qdata (G_OBJECT (pad), key_pad_data_quark (), NULL); } void kms_hub_port_unhandled (KmsHubPort * self) { GstPad *video_src, *audio_src; g_return_if_fail (self); video_src = gst_element_get_static_pad (GST_ELEMENT (self), HUB_VIDEO_SRC_PAD); kms_hub_port_internal_src_unhandled (self, video_src); g_object_unref (video_src); audio_src = gst_element_get_static_pad (GST_ELEMENT (self), HUB_AUDIO_SRC_PAD); kms_hub_port_internal_src_unhandled (self, audio_src); g_object_unref (audio_src); } static void kms_hub_port_internal_src_pad_linked (GstPad * pad, GstPad * peer, gpointer data) { GstPad *target, *new_pad; GstElement *capsfilter; KmsElement *self; KmsElementPadType type; capsfilter = g_object_get_qdata (G_OBJECT (pad), key_elem_data_quark ()); g_return_if_fail (capsfilter); self = KMS_ELEMENT (gst_object_get_parent (GST_OBJECT (capsfilter))); g_return_if_fail (self); target = gst_element_get_static_pad (capsfilter, "sink"); if (!target) { goto end; } type = GPOINTER_TO_INT (g_object_get_qdata (G_OBJECT (pad), key_type_data_quark ())); new_pad = kms_element_connect_sink_target (self, target, type); g_object_unref (target); g_object_set_qdata_full (G_OBJECT (pad), key_pad_data_quark (), g_object_ref (new_pad), g_object_unref); end: g_object_unref (self); } static void kms_hub_port_start_media_type (KmsElement * self, KmsElementPadType type, GstPadTemplate * templ, const gchar * pad_name) { GstElement *capsfilter = gst_element_factory_make ("capsfilter", NULL); GstPad *src = gst_element_get_static_pad (capsfilter, "src"); GstPad *internal_src; gst_bin_add (GST_BIN (self), capsfilter); gst_element_sync_state_with_parent (capsfilter); internal_src = gst_ghost_pad_new_from_template (pad_name, src, templ); g_object_set_qdata_full (G_OBJECT (internal_src), key_elem_data_quark (), g_object_ref (capsfilter), g_object_unref); g_object_set_qdata (G_OBJECT (internal_src), key_type_data_quark (), GINT_TO_POINTER (type)); g_signal_connect (internal_src, "linked", G_CALLBACK (kms_hub_port_internal_src_pad_linked), NULL); if (GST_STATE (self) >= GST_STATE_PAUSED || GST_STATE_PENDING (self) >= GST_STATE_PAUSED || GST_STATE_TARGET (self) >= GST_STATE_PAUSED) { gst_pad_set_active (internal_src, TRUE); } gst_element_add_pad (GST_ELEMENT (self), internal_src); g_object_unref (src); } static void kms_hub_port_dispose (GObject * object) { G_OBJECT_CLASS (kms_hub_port_parent_class)->dispose (object); } static void kms_hub_port_finalize (GObject * object) { G_OBJECT_CLASS (kms_hub_port_parent_class)->finalize (object); } static void kms_hub_port_class_init (KmsHubPortClass * klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass); gst_element_class_set_static_metadata (GST_ELEMENT_CLASS (klass), "HubPort", "Generic", "Kurento plugin for mixer connection", "<NAME> <<EMAIL>>"); gobject_class->dispose = kms_hub_port_dispose; gobject_class->finalize = kms_hub_port_finalize; gstelement_class->request_new_pad = GST_DEBUG_FUNCPTR (kms_hub_port_request_new_pad); gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&hub_audio_src_factory)); gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&hub_video_src_factory)); gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&hub_audio_sink_factory)); gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&hub_video_sink_factory)); /* Registers a private structure for the instantiatable type */ g_type_class_add_private (klass, sizeof (KmsHubPortPrivate)); } static void kms_hub_port_init (KmsHubPort * self) { KmsElement *kmselement; GstPadTemplate *templ; self->priv = KMS_HUB_PORT_GET_PRIVATE (self); kmselement = KMS_ELEMENT (self); templ = gst_static_pad_template_get (&hub_video_src_factory); kms_hub_port_start_media_type (kmselement, KMS_ELEMENT_PAD_TYPE_VIDEO, templ, HUB_VIDEO_SRC_PAD); g_object_unref (templ); templ = gst_static_pad_template_get (&hub_audio_src_factory); kms_hub_port_start_media_type (kmselement, KMS_ELEMENT_PAD_TYPE_AUDIO, templ, HUB_AUDIO_SRC_PAD); g_object_unref (templ); } gboolean kms_hub_port_plugin_init (GstPlugin * plugin) { return gst_element_register (plugin, PLUGIN_NAME, GST_RANK_NONE, KMS_TYPE_HUB_PORT); }
atcg/cPWP
cPWP/calcCOVARchunks.h
<reponame>atcg/cPWP // // calcCOVARchunks.h // // // Created by <NAME>-Melstad on 2/13/15. // // #ifndef ____calcCOVARchunks__ #define ____calcCOVARchunks__ #include <iostream> #include <vector> int calcCOVARfromBinaryFile (std::string binaryFile, long long int numLoci, const int numIndividuals, std::string outFile, int lociChunkSize, std::string samplesampleNamesFile, const int numThreads); int calcCOVARforRange (long long int startingLocus, long long int endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long long int>>& weightSumProducts, std::vector<std::vector<long long int>>& weightSumFirst, std::vector<std::vector<long long int>>& threadWeightings); #endif /* defined(____calcCOVARchunks__) */
atcg/cPWP
cPWP/calcPWPchunks.h
<filename>cPWP/calcPWPchunks.h // // calcPWP.h // // // Created by <NAME>-Melstad on 1/10/15. // // #ifndef ____calcPWP__ #define ____calcPWP__ #include <vector> #include <string> int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int lociChunkSize, std::string sampleNamesFile, int numThreads); int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings); #endif /* defined(____calcPWP__) */
rengeln/nyx
src/Matrix.h
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_MATRIX_H__ #define __NYX_MATRIX_H__ template <typename T, size_t M, size_t N> class Matrix { static_assert(N > 1 && N <= 4, "Requires 1 < N <= 4"); static_assert(M > 1 && M <= 4, "Requires 1 < M <= 4"); public: Vector<T, N> rows[M]; // // Constructor. // Matrix(); // // Construct from an arbitrarily-sized matrix. // template <typename U, size_t O, size_t P> Matrix(const Matrix<U, O, P>& cpy); // // Assignment from an arbitrarily-sized matrix. // template <typename U, size_t O, size_t P> Matrix<T, M, N>& operator=(const Matrix<U, O, P>& rhs); // // Array index operator. // Vector<T, N>& operator[](size_t i); Vector<T, N> operator[](size_t i) const; // // Multiplication operator. // template <typename U, size_t O, size_t P> friend Matrix<T, M, P> operator*(const Matrix<T, M, N>& lhs, const Matrix<U, O, P>& rhs); // // Transform a vector by a matrix. // template <size_t O> friend Vector<T, O> operator*(const Matrix<T, M, N>& lhs, const Vector<T, O>& rhs); // // Returns an identity matrix. // static Matrix<T, M, N> Identity(); // // Returns a rotation matrix from a quaternion. // static Matrix<T, M, N> Rotation(const Vector<T, 4>& q); // // Returns an affine translation matrix from a vector. // template <size_t O> static Matrix<T, M, N> Translation(const Vector<T, O>& v); // // Returns a left-handed perspective projection matrix. // // Parameters: // [in] fov // Field of view angle (in degrees.) // [in] aspect // Aspect ratio. // [in] nearZ // Near clipping plane. // [in] farZ // Far clipping plane. // static Matrix<T, M, N> PerspectiveProjection(const T& fov, const T& aspect, const T& nearZ, const T& farZ); }; template <typename T, size_t M, size_t N> inline Matrix<T, M, N>::Matrix() { } template <typename T, size_t M, size_t N> template <typename U, size_t O, size_t P> inline Matrix<T, M, N>::Matrix(const Matrix<U, O, P>& cpy) { *this = cpy; } template <typename T, size_t M, size_t N> template <typename U, size_t O, size_t P> inline Matrix<T, M, N>& Matrix<T, M, N>::operator=(const Matrix<U, O, P>& rhs) { for (size_t i = 0; i < M; i++) { if (i < O) { for (size_t j = 0; j < N; j++) { if (j < P) { (*this)[i][j] = rhs[i][j]; } else { (*this)[i][j] = static_cast<T>((i == j) ? 1 : 0); } } } else { for (size_t j = 0; j < N; j++) { (*this)[i][j] = static_cast<T>((i == j) ? 1 : 0); } } } } template <typename T, size_t M, size_t N> inline Vector<T, N>& Matrix<T, M, N>::operator[](size_t i) { assert(i < M); return rows[i]; } template <typename T, size_t M, size_t N> inline Vector<T, N> Matrix<T, M, N>::operator[](size_t i) const { assert(i < M); return rows[i]; } template <typename T, size_t M, size_t N, typename U, size_t O, size_t P> inline Matrix<T, M, P> operator*(const Matrix<T, M, N>& lhs, const Matrix<U, O, P>& rhs) { static_assert(N == O, "Requires N == 0"); Matrix<T, M, P> result; for (size_t i = 0; i < M; i++) { for (size_t j = 0; j < P; j++) { T value = 0; for (size_t k = 0; k < N; k++) { value += lhs[i][k] * rhs[k][j]; } result[i][j] = value; } } return result; } template <typename T, size_t M, size_t N, size_t O> inline Vector<T, O> operator*(const Matrix<T, M, N>& lhs, const Vector<T, O>& rhs) { static_assert(O == N || O + 1 == N, "Requires O == N or O + 1 == N"); Vector<T, N> result, v(rhs); if (O < N) { v[N - 1] = static_cast<T>(1); } for (size_t i = 0; i < N; i++) { T value = 0; for (size_t j = 0; j < M; j++) { value += v[j] * lhs[i][j]; } result[i] = value; } return Vector<T, O>(result); } template <typename T, size_t M, size_t N> inline Matrix<T, M, N> Matrix<T, M, N>::Identity() { Matrix<T, M, N> result; for (size_t i = 0; i < M; i++) { for (size_t j = 0; j < N; j++) { result[i][j] = static_cast<T>((i == j) ? 1 : 0); } } return result; } template <typename T, size_t M, size_t N> inline Matrix<T, M, N> Matrix<T, M, N>::Rotation(const Vector<T, 4>& q) { static_assert(boost::is_float<T>::value, "Requires is_float<T>"); static_assert(M >= 3 && N >= 3, "Requires M >= 3 and N >= 3"); Matrix<float, 4, 4> result; XMStoreFloat4x4(reinterpret_cast<XMFLOAT4X4*>(&result), XMMatrixRotationQuaternion(XMLoadFloat4(reinterpret_cast<const XMFLOAT4*>(&q)))); return Matrix<T, M, N>(result); } template <typename T, size_t M, size_t N> template <size_t O> inline Matrix<T, M, N> Matrix<T, M, N>::Translation(const Vector<T, O>& v) { static_assert(boost::is_float<T>::value, "Requires is_float<T>"); static_assert(M == 4, "Requires M == 4"); static_assert(N >= O, "Requires N >= O"); Matrix<T, M, N> result = Matrix<T, M, N>::Identity(); for (size_t i = 0; i < N; i++) { if (i < O) { result[3][i] = v[i]; } else { result[3][i] = static_cast<T>((i == M - 1) ? 1 : 0); } } return result; } template <typename T, size_t M, size_t N> inline Matrix<T, M, N> Matrix<T, M, N>::PerspectiveProjection(const T& fov, const T& aspect, const T& nearZ, const T& farZ) { static_assert(boost::is_float<T>::value, "Requires is_float<T>"); static_assert(M == 4 && N == 4, "Requires 4x4 matrix"); Matrix<float, M, N> result; XMStoreFloat4x4(reinterpret_cast<XMFLOAT4X4*>(&result), XMMatrixPerspectiveFovLH(fov, aspect, nearZ, farZ)); return Matrix<T, M, N>(result); } typedef Matrix<float, 2, 2> float2x2; typedef Matrix<float, 2, 3> float2x3; typedef Matrix<float, 2, 4> float2x4; typedef Matrix<float, 3, 2> float3x2; typedef Matrix<float, 3, 3> float3x3; typedef Matrix<float, 3, 4> float3x4; typedef Matrix<float, 4, 2> float4x2; typedef Matrix<float, 4, 3> float4x3; typedef Matrix<float, 4, 4> float4x4; typedef Matrix<double, 2, 2> double2x2; typedef Matrix<double, 2, 3> double2x3; typedef Matrix<double, 2, 4> double2x4; typedef Matrix<double, 3, 2> double3x2; typedef Matrix<double, 3, 3> double3x3; typedef Matrix<double, 3, 4> double3x4; typedef Matrix<double, 4, 2> double4x2; typedef Matrix<double, 4, 3> double4x3; typedef Matrix<double, 4, 4> double4x4; #endif // __NYX_MATRIX_H__
rengeln/nyx
src/Camera.h
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_CAMERA_H__ #define __NYX_CAMERA_H__ #include "Frustum.h" class Camera { public: // // Constructor. // Camera(); // // Destructor. // ~Camera(); // // Sets the projection matrix. // void SetProjectionMatrix(const float4x4& matrix); // // Sets the camera's position in worldspace. // void SetPosition(const float3& pos); // // Sets the camera's rotation in worldspace. // void SetRotation(const float4& rot); // // Returns the camera's projection matrix. // const float4x4& GetProjectionMatrix() const; // // Returns the camera's view matrix. // const float4x4& GetViewMatrix() const; // // Returns the combined projection-view matrix. // const float4x4& GetCombinedMatrix() const; // // Returns the camera's position. // const float3& GetPosition() const; // // Returns the camera's forward vector. // const float3& GetForwardVector() const; // // Returns the camera's up vector. // const float3& GetUpVector() const; // // Returns the camera's right vector. // const float3& GetRightVector() const; // // Returns the camera's frustum. // const Frustum& GetFrustum() const; private: // // Updates the derived members if dirty. // void Update() const; // // Properties. // float4x4 m_projectionMatrix; float3 m_position; float4 m_rotation; mutable float4x4 m_viewMatrix; mutable float4x4 m_combinedMatrix; mutable float3 m_forwardVector; mutable float3 m_upVector; mutable float3 m_rightVector; mutable Frustum m_frustum; mutable bool m_dirty; }; inline const float3& Camera::GetPosition() const { return m_position; } #endif // __NYX_CAMERA_H__
rengeln/nyx
src/Profiler.h
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_PROFILER_H__ #define __NYX_PROFILER_H__ class Profiler { public: // // Constructor. // // Parameters: // [in] name // Name of the event to be profiled. // Profiler(const char* name); // // Destructor. // ~Profiler(); // // Begins a sequence. // void Begin(); // // Ends a sequence. // void End(); private: // // Properties. // std::string m_name; uint64_t m_startTime; size_t m_sequenceCount; double m_totalTime; double m_shortestTime; double m_longestTime; }; #endif // __NYX_PROFILER_H__
rengeln/nyx
assets/shaders/voxel_mesh.h
<reponame>rengeln/nyx<gh_stars>1-10 /////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// cbuffer SceneConstants { row_major float4x4 ProjectionViewMatrix; row_major float4x4 WorldMatrix; float Transparency; float4 ClipPlane; }; sampler MaterialSampler; texture2D MaterialTextures[8]; static const float3 LightDirection = {0.5f, -0.5, 0.5f}; static const float3 LightColor = {0.8f, 0.6f, 0.4f}; static const float3 AmbientColor = {0.0f, 0.2f, 0.2f}; // // Mapping of material IDs to textures in the X, Y, and Z projections. // static const uint3 MaterialToTexture[8] = { {3, 3, 3}, // DIRT {4, 1, 4}, // GRASS (dark) {4, 2, 4}, // GRASS (light) {4, 3, 4}, // ROCK (dark) {5, 3, 5}, // ROCK (light) {0, 6, 0}, // SAND {0, 0, 0}, {0, 0, 0} };
rengeln/nyx
src/VoxelMesh.h
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_VOXELMESH_H__ #define __NYX_VOXELMESH_H__ // // Forward declarations. // class GraphicsDevice; class VoxelMesh : public boost::noncopyable { public: // // Vertex format. // struct Vertex { XMFLOAT3 position; int32_t normal; uint64_t material; }; // // Constructor. // // Parameters: // [in] graphicsDevice // Parent GraphicsDevice instance. // VoxelMesh(GraphicsDevice& graphicsDevice); // // Destructor. // ~VoxelMesh(); // // Resizes the vertex and index buffers. // // Parameters: // [in] vertexCount // New size for the vertex buffer. // [in] indexCount // New size for the index buffer. // void Resize(size_t vertexCount, size_t indexCount); // // Returns the number of items in the vertex buffer. // size_t GetVertexCount() const; // // Returns the number of items in the index buffer. // size_t GetIndexCount() const; // // Returns a pointer to the vertex buffer, or null if there is no vertex data. // ID3D11Buffer* GetVertexBuffer() const; // // Returns a pointer to the index buffer, or null if there is no index data. // ID3D11Buffer* GetIndexBuffer() const; // // Checks if the geometry is ready. // bool IsReady() const; // // Toggles the ready flag. // void SetReady(bool ready); private: // // Properties. // GraphicsDevice& m_graphicsDevice; boost::intrusive_ptr<ID3D11Buffer> m_vertexBuffer; boost::intrusive_ptr<ID3D11Buffer> m_indexBuffer; size_t m_vertexCount; size_t m_indexCount; bool m_ready; }; inline size_t VoxelMesh::GetVertexCount() const { return m_vertexCount; } inline size_t VoxelMesh::GetIndexCount() const { return m_indexCount; } inline ID3D11Buffer* VoxelMesh::GetVertexBuffer() const { return m_vertexBuffer.get(); } inline ID3D11Buffer* VoxelMesh::GetIndexBuffer() const { return m_indexBuffer.get(); } inline bool VoxelMesh::IsReady() const { return m_ready; } #endif // __NYX_VOXELMESH_H__
rengeln/nyx
src/Prefix.h
<reponame>rengeln/nyx /////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_PREFIX_H__ #define __NYX_PREFIX_H__ #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <tchar.h> #include <d3d11.h> #include <D3DX11.h> #include <DXGI.h> #include <DxErr.h> #include <xnamath.h> #include <algorithm> #include <array> #include <cassert> #include <cmath> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <exception> #include <stack> #include <stdexcept> #include <string> #include <utility> #include <vector> #include <boost/exception/all.hpp> #include <boost/format.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/utility.hpp> #include <ft2build.h> #include FT_FREETYPE_H #include <freetype/fterrors.h> typedef unsigned int uint; #include "Vector.h" #include "Matrix.h" // // Generic exception class. // class Exception : public virtual std::exception, public virtual boost::exception { public: // // Constructor. // // Parameters: // [in] msg // Error message. // Exception(const std::string& msg); Exception(const boost::format& msg); // // Appends a string to the error message. // Exception& operator<<(const std::string& str); Exception& operator<<(const boost::format& str); // // Returns the error message. // virtual const char* what() const throw(); private: // // Properties. // std::string m_message; }; inline Exception::Exception(const std::string& msg) : m_message(msg) { } inline Exception::Exception(const boost::format& msg) : m_message(msg.str()) { } inline Exception& Exception::operator<<(const std::string& str) { m_message.append(str); return *this; } inline Exception& Exception::operator<<(const boost::format& str) { m_message.append(str.str()); return *this; } inline const char* Exception::what() const throw() { return m_message.c_str(); } // // Template class for specializing exception types. // // Parameters: // [template] T // Tag type for specializing the exception; unused. // [template] Base // Type to inherit from. // template <typename T, typename Base = Exception> class Error : public Base { public: // // Constructor. // // Parameters: // [in] msg // Error message. // Error(const std::string& msg); Error(const boost::format& msg); }; template <typename T, typename Base> Error<T, Base>::Error(const std::string& msg) : Base(msg) { } template <typename T, typename Base> Error<T, Base>::Error(const boost::format& msg) : Base(msg.str()) { } // // Generic base for system errors. // typedef Error<struct _SystemError> SystemError; // // Specialized exception type for Win32 errors. // typedef Error<struct _Win32Error> Win32Error; // // Specialized exception type for Direct3D errors. // typedef Error<struct _Direct3DError, SystemError> Direct3DError; // // Specialized exception type for Freetype errors. // typedef Error<struct _FreetypeError, SystemError> FreetypeError; // // Enable Win32 error info to be attached to an exception. // typedef boost::error_info<struct _Win32ErrorInfo, HRESULT> Win32ErrorInfo; inline Win32ErrorInfo GetLastErrorInfo() { return Win32ErrorInfo(GetLastError()); } inline std::string to_string(const Win32ErrorInfo& err) { return (boost::format("[0x%08X] %s: %s") % err.value() % DXGetErrorStringA(err.value()) % DXGetErrorDescriptionA(err.value())).str(); } // // Enable DirectX error info to be attached to an exception. // typedef boost::error_info<struct _DirectXErrorInfo, HRESULT> DirectXErrorInfo; inline std::string to_string(const DirectXErrorInfo& err) { return (boost::format("[0x%08X] %s: %s") % err.value() % DXGetErrorStringA(err.value()) % DXGetErrorDescriptionA(err.value())).str(); } // // Exception throwing macro. // #define THROW(x) BOOST_THROW_EXCEPTION((x)) #define CHECK(e, x) do { if (!(x)) THROW(e("Assert failed: " #x)); } while(0) #define D3DCHECK(x) do { HRESULT hr; hr = (x); if (FAILED(hr)) THROW(Direct3DError("Assert failed: " #x) << DirectXErrorInfo(hr)); } while(0) #define WINCHECK(x) do { if (!(x)) THROW(Win32Error("Assert failed: " #x) << GetLastErrorInfo()); } while(0) #define FTCHECK(x) do { FT_Error err; err = (x); if (err != 0) THROW(FreetypeError("Assert failed: " #x) << (boost::format(" - Error code %d") % err)); } while(0) // // Enable intrusive_ptr to work with COM objects. // inline void intrusive_ptr_add_ref(IUnknown* ptr) { ptr->AddRef(); } inline void intrusive_ptr_release(IUnknown* ptr) { ptr->Release(); } // // Enable intrusive_ptr objects to be passed as parameters to functions expecting // a pointer-to-pointer which will be initialized by the function. // template <typename T> class IntrusivePtrWrapper { public: // // Constructor. // // Parameters: // [in] ref // Intrusive_ptr object to wrap. // [in] addRef // If true then the ptr's refcount will be incremented on acquisition. // IntrusivePtrWrapper(boost::intrusive_ptr<T>& ref, bool addRef); // // Destructor. // ~IntrusivePtrWrapper(); // // Implicit conversion to T**. // operator T**(); // // Implicit conversion to void**. // operator void**(); private: // // Properties. // boost::intrusive_ptr<T>& m_ref; T* m_ptr; bool m_addRef; }; template <typename T> inline IntrusivePtrWrapper<T>::IntrusivePtrWrapper(boost::intrusive_ptr<T>& ref, bool addRef) : m_ref(ref), m_addRef(addRef), m_ptr(nullptr) { } template <typename T> inline IntrusivePtrWrapper<T>::~IntrusivePtrWrapper() { m_ref = boost::intrusive_ptr<T>(m_ptr, m_addRef); } template <typename T> inline IntrusivePtrWrapper<T>::operator T**() { return &m_ptr; } template <typename T> inline IntrusivePtrWrapper<T>::operator void**() { return reinterpret_cast<void**>(&m_ptr); } // // Helper function for constructing an IntrusivePtrWrapper. // // Parameters: // [in] ref // Intrusive_ptr object to wrap. // [in] addRef // If true then the ptr's refcount will be incremented on acquisition. // Default is false, which matches the behavior of COM functions. // template <typename T> inline IntrusivePtrWrapper<T> AttachPtr(boost::intrusive_ptr<T>& ref, bool addRef = false) { return IntrusivePtrWrapper<T>(ref, addRef); } #endif // __NYX_PREFIX_H__
rengeln/nyx
src/GraphicsDevice.h
<reponame>rengeln/nyx /////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_GRAPHICSDEVICE_H__ #define __NYX_GRAPHICSDEVICE_H__ // // Forward declarations. // class RenderContext; // // Encapsulates the graphics engine. // class GraphicsDevice : public boost::noncopyable { public: // // Constructor. // // Parameters: // [in] hwnd // Render window. // GraphicsDevice(HWND hwnd); // // Destructor. // ~GraphicsDevice(); // // Begins per-frame rendering operations. // void Begin(); // // Ends per-frame rendering operations. // void End(); // // Returns the Direct3D device. // ID3D11Device& GetD3DDevice(); // // Returns the Direct3D immediate context. // ID3D11DeviceContext& GetD3DContext(); // // Returns the D3DInclude implementation. // ID3D10Include& GetD3DInclude(); // // Returns the primary RenderContext. // RenderContext& GetRenderContext(); private: // // Properties. // boost::intrusive_ptr<IDXGIFactory> m_factory; boost::intrusive_ptr<IDXGIAdapter> m_adapter; boost::intrusive_ptr<ID3D11Device> m_device; boost::intrusive_ptr<ID3D11DeviceContext> m_context; boost::intrusive_ptr<IDXGISwapChain> m_swapChain; boost::intrusive_ptr<ID3D11RenderTargetView> m_renderTargetView; boost::intrusive_ptr<ID3D11DepthStencilView> m_depthStencilView; D3D_FEATURE_LEVEL m_featureLevel; std::unique_ptr<RenderContext> m_renderContext; }; inline ID3D11Device& GraphicsDevice::GetD3DDevice() { assert(m_device); return *m_device; } inline ID3D11DeviceContext& GraphicsDevice::GetD3DContext() { assert(m_context); return *m_context; } inline RenderContext& GraphicsDevice::GetRenderContext() { assert(m_renderContext); return *m_renderContext; } #endif // __NYX_GRAPHICSDEVICE_H__
rengeln/nyx
src/Noise.h
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_NOISE_H__ #define __NYX_NOISE_H__ // // Simplex noise implementation. // // Based on http://webstaff.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf // class Noise : public boost::noncopyable { public: // // Constructor. // Noise(); // // Destructor. // ~Noise(); // // Samples noise in 3D space. // float Sample(float x, float y, float z); // // Samples noise in 3D space and normalizes the result to a given range. // float SampleRange(float x, float y, float z, float a, float b); // // Fills a 3D grid with noise. // // Parameters: // [in] ptr // Pointer to the destination grid. // [in] x, y, z // Grid dimensions. // [in] xf, yf, zf // Frequency to sample in each direction. // void Fill(float* ptr, size_t x, size_t y, size_t z, float xf, float yf, float zf); private: // // Properties. // static const XMFLOAT3 GradiantVectors[]; static const int Permutations[]; int m_permutationTable[512]; }; #endif // __NYX_NOISE_H__
rengeln/nyx
src/VoxelProcessor.h
<reponame>rengeln/nyx<filename>src/VoxelProcessor.h /////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_VOXELPROCESSOR_H__ #define __NYX_VOXELPROCESSOR_H__ // // Forward declarations. // class GraphicsDevice; class VoxelManager; class VoxelMesh; class VoxelProcessor : public boost::noncopyable { public: // // Constructor. // // Parameters: // [in] graphicsDevice // Parent GraphicsDevice instance. // VoxelProcessor(GraphicsDevice& graphicsDevice); // // Destructor. // ~VoxelProcessor(); // // Processes a node. // // Parameters: // [out] geometry // Geometry to process. // [in] position // Position of the chunk. // [in] size // Size of the chunk. // void Process(std::shared_ptr<VoxelMesh> geometry, float3 position, float3 size, size_t depth); // // Updates the processor. // void Update(); // // Checks if the processor is ready to accept another chunk. // bool IsReady(); private: // // Updates the constant buffer. // void UpdateConstantBuffer(); // // Runs the gen_voxels pass. // void GenerateVoxels(); // // Runs the list_cells pass. // void ListCells(); // // Runs the list_vertices pass. // void ListVertices(); // // Runs the gen_vertices pass. // void GenerateVertices(); // // Runs the splat vertices pass. // void SplatVertices(); // // Runs the gen_indices pass. // void GenerateIndices(); // // Resources shared among all VoxelProcessor instances. // struct SharedProperties { boost::intrusive_ptr<ID3D11InputLayout> genVoxelsLayout; boost::intrusive_ptr<ID3D11VertexShader> genVoxelsVS; boost::intrusive_ptr<ID3D11GeometryShader> genVoxelsGS; boost::intrusive_ptr<ID3D11PixelShader> genVoxelsPS; boost::intrusive_ptr<ID3D11InputLayout> listCellsLayout; boost::intrusive_ptr<ID3D11VertexShader> listCellsVS; boost::intrusive_ptr<ID3D11GeometryShader> listCellsGS; boost::intrusive_ptr<ID3D11InputLayout> listVerticesLayout; boost::intrusive_ptr<ID3D11VertexShader> listVerticesVS; boost::intrusive_ptr<ID3D11GeometryShader> listVerticesGS; boost::intrusive_ptr<ID3D11InputLayout> genVerticesLayout; boost::intrusive_ptr<ID3D11VertexShader> genVerticesVS; boost::intrusive_ptr<ID3D11GeometryShader> genVerticesGS; boost::intrusive_ptr<ID3D11InputLayout> splatVerticesLayout; boost::intrusive_ptr<ID3D11VertexShader> splatVerticesVS; boost::intrusive_ptr<ID3D11GeometryShader> splatVerticesGS; boost::intrusive_ptr<ID3D11PixelShader> splatVerticesPS; boost::intrusive_ptr<ID3D11InputLayout> genIndicesLayout; boost::intrusive_ptr<ID3D11VertexShader> genIndicesVS; boost::intrusive_ptr<ID3D11GeometryShader> genIndicesGS; boost::intrusive_ptr<ID3D11Buffer> cellBuffer; boost::intrusive_ptr<ID3D11ShaderResourceView> triTableView; boost::intrusive_ptr<ID3D11SamplerState> densitySampler; boost::intrusive_ptr<ID3D11DepthStencilState> depthStencilState; boost::intrusive_ptr<ID3D11RasterizerState> rasterizerState; boost::intrusive_ptr<ID3D11ShaderResourceView> permutationsView; boost::intrusive_ptr<ID3D11ShaderResourceView> gradientsView; }; // // Shader constants for the marching cubes geometry shader. // struct ShaderConstants { XMFLOAT4 chunkPosition; float3 chunkDimensions; uint chunkDepth; size_t cellCount[4]; XMFLOAT4 voxelFieldSize; XMFLOAT4 voxelFieldSubSize; XMFLOAT4 voxelFieldOffset; XMFLOAT4 voxelIDMapSize; size_t edgeCellOffsets[12][4]; size_t EdgeXOffsets[12][4]; }; // // Properties. // static const int EdgeTable[256]; static const int TriTable[256][16]; static std::weak_ptr<SharedProperties> m_sharedWeakPtr; static const uint3 CellDimensions; size_t m_width; size_t m_height; size_t m_depth; GraphicsDevice& m_graphicsDevice; std::shared_ptr<SharedProperties> m_shared; ShaderConstants m_shaderConstants; size_t m_vertexCount; size_t m_indexCount; bool m_verticesAreReady; bool m_indicesAreReady; std::shared_ptr<VoxelMesh> m_geometryPtr; boost::intrusive_ptr<ID3D11Buffer> m_cellMarkerBuffer; boost::intrusive_ptr<ID3D11Buffer> m_vertexMarkerBuffer; boost::intrusive_ptr<ID3D11Buffer> m_vertexBuffer; boost::intrusive_ptr<ID3D11Buffer> m_indexBuffer; boost::intrusive_ptr<ID3D11Texture2D> m_vertexMap; boost::intrusive_ptr<ID3D11RenderTargetView> m_vertexMapRTV; boost::intrusive_ptr<ID3D11ShaderResourceView> m_vertexMapSRV; boost::intrusive_ptr<ID3D11Buffer> m_constantBuffer; boost::intrusive_ptr<ID3D11Query> m_vertexQuery; boost::intrusive_ptr<ID3D11Query> m_indexQuery; boost::intrusive_ptr<ID3D11Texture3D> m_voxelTexture; boost::intrusive_ptr<ID3D11ShaderResourceView> m_voxelSRV; boost::intrusive_ptr<ID3D11RenderTargetView> m_voxelRTV; boost::intrusive_ptr<ID3D11Texture3D> m_materialTexture; boost::intrusive_ptr<ID3D11ShaderResourceView> m_materialSRV; boost::intrusive_ptr<ID3D11RenderTargetView> m_materialRTV; boost::intrusive_ptr<ID3D11Texture3D> m_stagingTexture; }; #endif // __NYX_VOXELPROCESSOR_H__
rengeln/nyx
src/RenderContext.h
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_RENDERCONTEXT_H__ #define __NYX_RENDERCONTEXT_H__ class GraphicsDevice; // // Encapsulates a Direct3D rendering context, implementing push and pop // behavior for setting rendering state. // class RenderContext : public boost::noncopyable { public: // // Constructor. // // Parameters: // [in] graphicsDevice // Parent GraphicsDevice instance. // [in] context // Direct3D context to encapsulate. // RenderContext(GraphicsDevice& graphicsDevice, boost::intrusive_ptr<ID3D11DeviceContext> context); // // Destructor. // ~RenderContext(); // // Returns the Direct3D device context. // ID3D11DeviceContext& GetD3DContext(); // // Reapplies all of the objects at the top of the stack. // // This lets RenderContext play nice with legacy code which isn't using it. // void Apply(); // // Pushes a rasterizer state and activates it. // void PushRasterizerState(boost::intrusive_ptr<ID3D11RasterizerState> rs); // // Pops the rasterizer state. // void PopRasterizerState(); // // Pushes a depth/stencil state and activates it. // void PushDepthStencilState(boost::intrusive_ptr<ID3D11DepthStencilState> ds); // // Pops the depth/stencil state. // void PopDepthStencilState(); // // Pushes a blend state and activates it. // void PushBlendState(boost::intrusive_ptr<ID3D11BlendState> bs); // // Pops the blend state. // void PopBlendState(); // // Pushes a render target view (with an optional depth/stencil buffer) and activates it. // void PushRenderTarget(boost::intrusive_ptr<ID3D11RenderTargetView> rtv, boost::intrusive_ptr<ID3D11DepthStencilView> dsv = nullptr); // // Pops the render target. // void PopRenderTarget(); // // Pushes a viewport and activates it. // void PushViewport(D3D11_VIEWPORT vp); // // Pops the viewport. // void PopViewport(); private: // // Properties. // GraphicsDevice& m_graphicsDevice; boost::intrusive_ptr<ID3D11DeviceContext> m_d3dContext; std::stack<boost::intrusive_ptr<ID3D11RasterizerState>> m_rasterizerStateStack; std::stack<boost::intrusive_ptr<ID3D11DepthStencilState>> m_depthStencilStateStack; std::stack<boost::intrusive_ptr<ID3D11BlendState>> m_blendStateStack; std::stack<std::pair<boost::intrusive_ptr<ID3D11RenderTargetView>, boost::intrusive_ptr<ID3D11DepthStencilView>>> m_renderTargetStack; std::stack<D3D11_VIEWPORT> m_viewportStack; }; inline ID3D11DeviceContext& RenderContext::GetD3DContext() { assert(m_d3dContext); return *m_d3dContext; } #endif // __NYX_RENDERCONTEXT_H__
rengeln/nyx
src/SkyRenderer.h
<gh_stars>1-10 /////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_SKYRENDERER_H__ #define __NYX_SKYRENDERER_H__ // // Forward declarations. // class Camera; class GraphicsDevice; class SceneConstants; // // Renders the skybox. // class SkyRenderer : public boost::noncopyable { public: // // Constructor. // // Parameters: // [in] graphicsDevice // Parent GraphicsDevice instance. // SkyRenderer(GraphicsDevice& graphicsDevice); // // Destructor. // ~SkyRenderer(); // // Draws the skybox. // // Parameters: // [in] renderContext // Render context. // [in] sceneContants // Scene constants. // void Draw(RenderContext& renderContext, const SceneConstants& sceneConstants); private: // // Properties. // struct SharedProperties { boost::intrusive_ptr<ID3D11VertexShader> vertexShader; boost::intrusive_ptr<ID3D11PixelShader> pixelShader; boost::intrusive_ptr<ID3D11InputLayout> inputLayout; boost::intrusive_ptr<ID3D11Buffer> vertexBuffer; boost::intrusive_ptr<ID3D11Buffer> indexBuffer; boost::intrusive_ptr<ID3D11RasterizerState> rasterizerState; boost::intrusive_ptr<ID3D11DepthStencilState> depthStencilState; boost::intrusive_ptr<ID3D11ShaderResourceView> skyTextureView; boost::intrusive_ptr<ID3D11SamplerState> samplerState; }; struct ShaderConstants { float4x4 viewMatrix; float4x4 projectionMatrix; }; struct Vertex { float xyz[3]; float uv[2]; }; static const Vertex SkyboxVertices[24]; static const uint16_t SkyboxIndices[36]; static std::weak_ptr<SharedProperties> m_sharedWeakPtr; std::shared_ptr<SharedProperties> m_shared; GraphicsDevice& m_graphicsDevice; ShaderConstants m_constants; boost::intrusive_ptr<ID3D11Buffer> m_constantBuffer; }; #endif // __NYX_SKYRENDERER_H__
rengeln/nyx
assets/shaders/water.h
<gh_stars>1-10 /////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// cbuffer SceneConstants { row_major float4x4 ViewMatrix; row_major float4x4 ProjectionMatrix; float4 CameraPos; }; texture2D NormalTexture; texture2D ReflectionTexture; sampler LinearSampler; static const float3 LightDirection = {0.5f, -0.5, 0.5f}; static const float3 LightColor = {0.8f, 0.6f, 0.4f}; static const float3 AmbientColor = {0.0f, 0.2f, 0.2f};
rengeln/nyx
src/WaterManager.h
<reponame>rengeln/nyx<gh_stars>1-10 /////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_WATERMANAGER_H__ #define __NYX_WATERMANAGER_H__ class SceneManager; class WaterRenderer; class WaterManager : public boost::noncopyable { public: // // Constructor. // // Parameters: // [in] sceneManager // Parent SceneManager instance. // WaterManager(SceneManager& sceneManager); // // Destructor. // ~WaterManager(); // // Updates the water simulation. // void Update(); // // Draws the water. // void Draw(RenderContext& renderContext, const SceneConstants& sceneConstants); // // Performs pre-drawing tasks, such as generating the reflection map. // void PreDraw(RenderContext& renderContext, const Camera& camera); private: // // Properties. // SceneManager& m_sceneManager; boost::intrusive_ptr<ID3D11RenderTargetView> m_reflectionRTV; boost::intrusive_ptr<ID3D11ShaderResourceView> m_reflectionSRV; boost::intrusive_ptr<ID3D11DepthStencilView> m_reflectionDSV; boost::intrusive_ptr<ID3D11RasterizerState> m_reflectionRS; std::unique_ptr<WaterRenderer> m_waterRenderer; bool m_preventDrawing; }; #endif // __NYX_WATERMANAGER_H__
rengeln/nyx
src/Frustum.h
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_FRUSTUM_H__ #define __NYX_FRUSTUM_H__ enum FrustumPlane { FrustumPlane_Left, FrustumPlane_Bottom, FrustumPlane_Near, FrustumPlane_Right, FrustumPlane_Top, FrustumPlane_Far, FrustumPlane_Max }; class Frustum { public: // // Default constructor. // Frustum(); // // Construct from a view-projection matrix. // Frustum(const float4x4& m); // // Returns one of the frustum planes. // float4 GetPlane(FrustumPlane p); // // Extract from a view-projection matrix. // Frustum& operator=(const float4x4& m); // // Intersection test with an axis-aligned box. // bool Intersects(const box3f& box) const; private: // // Extract from a matrix. // void Extract(const float4x4& m); // // Properties. // float4 m_planes[FrustumPlane_Max]; }; inline Frustum::Frustum() { } inline Frustum::Frustum(const float4x4& m) { Extract(m); } inline Frustum& Frustum::operator=(const float4x4& m) { Extract(m); return *this; } inline float4 Frustum::GetPlane(FrustumPlane p) { assert(p < FrustumPlane_Max); return m_planes[p]; } inline bool Frustum::Intersects(const box3f& box) const { for (size_t i = 0; i < FrustumPlane_Max; ++i) { XMFLOAT3 v; v.x = m_planes[i].x >= 0 ? box.second.x : box.first.x; v.y = m_planes[i].y >= 0 ? box.second.y : box.first.y; v.z = m_planes[i].z >= 0 ? box.second.z : box.first.z; XMVECTOR _v = XMLoadFloat3(reinterpret_cast<const XMFLOAT3*>(&v)), _p = XMLoadFloat4(reinterpret_cast<const XMFLOAT4*>(&m_planes[i])); if (XMVectorGetX(XMPlaneDotCoord(_p, _v)) < 0.0f) { return false; } } return true; } #endif // __NYX_FRUSTUM_H__
rengeln/nyx
assets/shaders/simplex_noise.h
<reponame>rengeln/nyx /////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// Buffer<float3> GradientVectors; Buffer<uint> Permutations; // // 3D simplex noise implementation. // float simplex_noise(float3 pos) { const float F3 = 1.0f / 3.0f, G3 = 1.0f / 6.0f; float x = pos.x; float y = pos.y; float z = pos.z; float n0, n1, n2, n3; float s = (x + y + z) * F3; int i = (int)floor(x + s); int j = (int)floor(y + s); int k = (int)floor(z + s); float t = (float)(i + j + k) * G3; float X0 = (float)i - t; float Y0 = (float)j - t; float Z0 = (float)k - t; float x0 = x - X0; float y0 = y - Y0; float z0 = z - Z0; int i1, j1, k1, i2, j2, k2; if (x0 >= y0) { if (y0 >= z0) { i1=1; j1=0; k1=0; i2=1; j2=1; k2=0; // X Y Z order } else if (x0 >= z0) { i1=1; j1=0; k1=0; i2=1; j2=0; k2=1; // X Z Y order } else { i1=0; j1=0; k1=1; i2=1; j2=0; k2=1; // Z X Y order } } else { // x0<y0 if (y0 < z0) { i1=0; j1=0; k1=1; i2=0; j2=1; k2=1; // Z Y X order } else if (x0 < z0) { i1=0; j1=1; k1=0; i2=0; j2=1; k2=1; // Y Z X order } else { i1=0; j1=1; k1=0; i2=1; j2=1; k2=0; // Y X Z order } } // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z), // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where // c = 1/6. float x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords float y1 = y0 - j1 + G3; float z1 = z0 - k1 + G3; float x2 = x0 - i2 + 2.0f * G3; // Offsets for third corner in (x,y,z) coords float y2 = y0 - j2 + 2.0f * G3; float z2 = z0 - k2 + 2.0f * G3; float x3 = x0 - 1.0f + 3.0f * G3; // Offsets for last corner in (x,y,z) coords float y3 = y0 - 1.0f + 3.0f * G3; float z3 = z0 - 1.0f + 3.0f * G3; // Work out the hashed gradient indices of the four simplex corners int ii = i & 255; int jj = j & 255; int kk = k & 255; int gi0 = Permutations[ii+Permutations[jj+Permutations[kk]]] % 12; int gi1 = Permutations[ii+i1+Permutations[jj+j1+Permutations[kk+k1]]] % 12; int gi2 = Permutations[ii+i2+Permutations[jj+j2+Permutations[kk+k2]]] % 12; int gi3 = Permutations[ii+1+Permutations[jj+1+Permutations[kk+1]]] % 12; // Calculate the contribution from the four corners float t0 = 0.6f - x0 * x0 - y0 * y0 - z0 * z0; if (t0 < 0) { n0 = 0.0; } else { t0 *= t0; n0 = t0 * t0 * (GradientVectors[gi0].x * x0 + GradientVectors[gi0].y * y0 + GradientVectors[gi0].z * z0); } float t1 = 0.6f - x1 * x1 - y1 * y1 - z1 * z1; if (t1 < 0) { n1 = 0.0; } else { t1 *= t1; n1 = t1 * t1 * (GradientVectors[gi1].x * x1 + GradientVectors[gi1].y * y1 + GradientVectors[gi1].z * z1); } float t2 = 0.6f - x2 * x2 - y2 * y2 - z2 * z2; if (t2 < 0) { n2 = 0.0; } else { t2 *= t2; n2 = t2 * t2 * (GradientVectors[gi2].x * x2 + GradientVectors[gi2].y * y2 + GradientVectors[gi2].z * z2); } float t3 = 0.6f - x3 * x3 - y3 * y3 - z3 * z3; if (t3 < 0) { n3 = 0.0; } else { t3 *= t3; n3 = t3 * t3 * (GradientVectors[gi3].x * x3 + GradientVectors[gi3].y * y3 + GradientVectors[gi3].z * z3); } float r = 32.0f * (n0 + n1 + n2 + n3); return r; } // // Returns a noise value scaled to the range [a..b] // float simplex_noise_range(float3 xyz, float a, float b) { return a + ((1.0f + simplex_noise(xyz)) / 2.0f) * (b - a); }
rengeln/nyx
assets/shaders/marching_cubes.h
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// // // Shader constants. // cbuffer Constants { float3 ChunkPosition; float3 ChunkDimensions; uint ChunkDepth; int3 CellCount; float3 VoxelFieldTotalSize; float3 VoxelFieldSubSize; float3 VoxelFieldOffset; float3 VoxelIDMapSize; uint4 EdgeCellOffsets[12]; uint4 EdgeXOffsets[12]; }; Buffer<int> TriTable; Texture3D<float> VoxelField; Texture3D<uint2> MaterialField; Texture2D<uint> VertexIDMap; SamplerState VoxelSampler; // // Bilinear interpolation. // // Parameters: // [in] a, b, c, d // Corner values, starting from top-left and going clockwise. // [in] s, t // Blending factors in the X and Y axes. // float4 Bilerp(float4 a, float4 b, float4 c, float4 d, float s, float t) { float4 _1 = (a * (1 - s) + b * s) * (1 - t); float4 _2 = (d * (1 - s) + c * s) * t; float4 _3 = _1 + _2; return _3; } // // Trilinear interpolation. // // Parameters: // [in] a, b, c, d, e, f, g, h // Corner values, starting from near-top-left and going clockwise, // then far-top-left and going clockwise again. // [in] s, t, u // Blending factors in the X, Y and Z axes. // float4 Trilerp(float4 a, float4 b, float4 c, float4 d, float4 e, float4 f, float4 g, float4 h, float s, float t, float u) { float4 _1 = Bilerp(a, b, c, d, s, t); float4 _2 = Bilerp(e, f, g, h, s, t); float4 _3 = lerp(_1, _2, u); return _3; } // // Returns the density of the voxel field at the given voxel-space coordinates. // float Density(float3 v) { v /= CellCount - 1; v *= VoxelFieldSubSize / VoxelFieldTotalSize; v += VoxelFieldOffset / VoxelFieldTotalSize; return VoxelField.SampleLevel(VoxelSampler, v, 0).r; } // // Returns the material weights of the voxel field at the given voxel-space coordinates. // // Up to eight material weights are packed into 8-bit components. // uint2 Material(float3 f) { f -= 0.5f; // Account for the fact that nearest-neighbor sampling does not // use a half-pixel offset, whereas SampleLevel() does. f /= CellCount - 1; f *= VoxelFieldSubSize / VoxelFieldTotalSize; f += VoxelFieldOffset / VoxelFieldTotalSize; uint4 v = uint4(uint3(f * VoxelFieldTotalSize), 0); // Retrive the material weights from the voxel field using nearest-neighbor sampling uint2 packed[8] = { MaterialField.Load(v), MaterialField.Load(v + uint4(1, 0, 0, 0)), MaterialField.Load(v + uint4(1, 1, 0, 0)), MaterialField.Load(v + uint4(0, 1, 0, 0)), MaterialField.Load(v + uint4(0, 0, 1, 0)), MaterialField.Load(v + uint4(1, 0, 1, 0)), MaterialField.Load(v + uint4(1, 1, 1, 0)), MaterialField.Load(v + uint4(0, 1, 1, 0)) }; // Unpack the weights into floats so they can be filtered float4 weights1[8], weights2[8]; [unroll] for (uint i = 0; i < 8; i++) { weights1[i] = float4(float((packed[i].x >> 24) & 0xFF) / 255.0f, float((packed[i].x >> 16) & 0xFF) / 255.0f, float((packed[i].x >> 8) & 0xFF) / 255.0f, float((packed[i].x >> 0) & 0xFF) / 255.0f); weights2[i] = float4(float((packed[i].y >> 24) & 0xFF) / 255.0f, float((packed[i].y >> 16) & 0xFF) / 255.0f, float((packed[i].y >> 8) & 0xFF) / 255.0f, float((packed[i].y >> 0) & 0xFF) / 255.0f); } // Calculate the interpolation weights float3 mu = float3(f - floor(f)); // Filter the results float4 r1 = Trilerp(weights1[0], weights1[1], weights1[2], weights1[3], weights1[4], weights1[5], weights1[6], weights1[7], mu.x, mu.y, mu.z); float4 r2 = Trilerp(weights2[0], weights2[1], weights2[2], weights2[3], weights2[4], weights2[5], weights2[6], weights2[7], mu.x, mu.y, mu.z); // Pack the results uint2 r; r.x = (uint(r1.x * 255.0f) << 24) + (uint(r1.y * 255.0f) << 16) + (uint(r1.z * 255.0f) << 8) + (uint(r1.w * 255.0f) << 0); r.y = (uint(r2.x * 255.0f) << 24) + (uint(r2.y * 255.0f) << 16) + (uint(r2.z * 255.0f) << 8) + (uint(r2.w * 255.0f) << 0); return r; }
rengeln/nyx
src/Font.h
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_FONT_H__ #define __NYX_FONT_H__ class GraphicsDevice; class Font : public boost::noncopyable { public: // // Constructor. // // Parameters: // [in] graphicsDevice // Parent GraphicsDevice instance. // [in] font // Path to the font file. // [in] size // Face size. // Font(GraphicsDevice& graphicsDevice, const char* path, size_t size); // // Destructor. // ~Font(); private: struct Glyph { float2 uv; float2 size; }; struct Bin { uint2 xy; uint2 size; }; // // Loads a glyph. // Glyph& LoadGlyph(uint32_t c); // // Updates the texture. // void Update(); // // Properties. // struct SharedProperties { FT_Library freetype; }; static std::weak_ptr<SharedProperties> m_sharedWeakPtr; static const size_t BufferWidth = 2048, BufferHeight = 1024; std::shared_ptr<SharedProperties> m_shared; GraphicsDevice& m_graphicsDevice; FT_Face m_face; std::vector<uint8_t> m_glyphBuffer; boost::intrusive_ptr<ID3D11Texture2D> m_texture; std::vector<Bin> m_bins; std::map<uint32_t, Glyph> m_glyphMap; bool m_dirty; }; #endif // __NYX_FONT_H__
rengeln/nyx
src/LineRenderer.h
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_LINERENDERER_H__ #define __NYX_LINERENDERER_H__ // // Forward declarations. // class Camera; class GraphicsDevice; class RenderContext; class SceneConstants; class LineRenderer : public boost::noncopyable { public: // // Constructor. // // Parameters: // [in] graphicsDevice // Parent GraphicsDevice instance. // LineRenderer(GraphicsDevice& graphicsDevice); // // Destructor. // ~LineRenderer(); // // Draws a line segment. // // Parameters: // [in] p0 // First point. // [in] p1 // Second point. // [in] color // Line color. // void DrawLine(float3 p0, float3 p1, float4 color); // // Draws an axis-aligned box. // // Parameters: // [in] p0 // Minimum corner. // [in] p1 // Maximum corner. // [in] color // Line color. // void DrawBox(box3f, float4 color); // // Flushes all queued drawing operations. // // Parameters: // [in] renderContext // Render context. // [in] sceneConstants // Scene constants. // void Flush(RenderContext& renderContext, const SceneConstants& sceneConstants); private: // // Vertex type. // struct Vertex { float3 position; ubyte4 color; }; // // Properties. // struct SharedProperties { boost::intrusive_ptr<ID3D11InputLayout> inputLayout; boost::intrusive_ptr<ID3D11VertexShader> vertexShader; boost::intrusive_ptr<ID3D11PixelShader> pixelShader; boost::intrusive_ptr<ID3D11Buffer> constantBuffer; boost::intrusive_ptr<ID3D11RasterizerState> rasterizerState; boost::intrusive_ptr<ID3D11DepthStencilState> depthStencilState; boost::intrusive_ptr<ID3D11Buffer> vertexBuffer; }; struct ShaderConstants { float4x4 projectionViewMatrix; }; static std::weak_ptr<SharedProperties> m_sharedWeakPtr; GraphicsDevice& m_graphicsDevice; std::shared_ptr<SharedProperties> m_shared; boost::intrusive_ptr<ID3D11Buffer> m_vertexBuffer; std::vector<Vertex> m_vertices; uint m_vertexBufferSize; ShaderConstants m_constants; }; #endif // __NYX_LINERENDERER_H__
rengeln/nyx
src/WaterRenderer.h
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_WATERRENDERER_H__ #define __NYX_WATERRENDERER_H__ class SceneConstants; // // Renders the water plane. // class WaterRenderer : public boost::noncopyable { public: // // Constructor. // WaterRenderer(GraphicsDevice& graphicsDevice); // // Destructor. // ~WaterRenderer(); // // Draws the water plane. // // Parameters: // [in] renderContext // Render context. // [in] sceneConstants // Scene constants. // [in] reflectionSrv // SRV for the reflection texture. // void Draw(RenderContext& renderContext, const SceneConstants& sceneConstants, ID3D11ShaderResourceView& reflectionSrv); private: struct Vertex { float3 xyz; }; // // Generates the radial grid mesh. // // Parameters: // [out] vertices // Vector which will hold the generated vertices. // [out] indices // Vector which will hold the generated indices. // static void GenerateRadialGrid(std::vector<struct Vertex>& vertices, std::vector<uint16_t>& indices); // // Properties. // struct SharedProperties { boost::intrusive_ptr<ID3D11VertexShader> vertexShader; boost::intrusive_ptr<ID3D11PixelShader> pixelShader; boost::intrusive_ptr<ID3D11InputLayout> inputLayout; boost::intrusive_ptr<ID3D11Buffer> vertexBuffer; boost::intrusive_ptr<ID3D11Buffer> indexBuffer; boost::intrusive_ptr<ID3D11RasterizerState> rasterizerState; boost::intrusive_ptr<ID3D11DepthStencilState> depthStencilState; boost::intrusive_ptr<ID3D11SamplerState> samplerState; boost::intrusive_ptr<ID3D11BlendState> blendState; boost::intrusive_ptr<ID3D11ShaderResourceView> noiseTextureView; boost::intrusive_ptr<ID3D11SamplerState> noiseSampler; boost::intrusive_ptr<ID3D11SamplerState> reflectionSampler; uint32_t indexCount; }; struct ShaderConstants { float4x4 viewMatrix; float4x4 projectionMatrix; float4 cameraPos; }; static std::weak_ptr<SharedProperties> m_sharedWeakPtr; std::shared_ptr<SharedProperties> m_shared; GraphicsDevice& m_graphicsDevice; ShaderConstants m_shaderConstants; boost::intrusive_ptr<ID3D11Buffer> m_constantBuffer; float m_time; }; #endif // __NYX_WATERRENDERER_H__
rengeln/nyx
src/VoxelRenderer.h
<filename>src/VoxelRenderer.h /////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_VOXELRENDERER_H__ #define __NYX_VOXELRENDERER_H__ // // Forward declarations. // class Camera; class GraphicsDevice; class RenderContext; class SceneConstants; class VoxelMesh; // // Implements the voxel mesh renderer. // class VoxelRenderer : public boost::noncopyable { public: // // Constructor. // // Parameters: // [in] graphicsDevice // Parent GraphicsDevice instance. // VoxelRenderer(GraphicsDevice& graphicsDevice); // // Destructor. // ~VoxelRenderer(); // // Draws a voxel mesh. // // In reality these functions enqueue the meshes for drawing, which occurs // when Flush() is called. // void Draw(const VoxelMesh& geometry, float3 position); void DrawTransparent(const VoxelMesh& geometry, float3 position, float alpha); void DrawGapFiller(const VoxelMesh& geometry, float3 position); // // Flushes queued render ops. // // Parameters: // [in] renderContext // Render context. // [in] sceneConstants // Scene constants. // void Flush(RenderContext& renderContext, const SceneConstants& sceneConstants); private: struct RenderOp { const VoxelMesh* geometry; float3 position; float distance2; float alpha; bool gapFiller; }; // // Implements the actual drawing of voxel meshes. // void Draw(const RenderOp& renderOp); // // Properties. // struct SharedProperties { boost::intrusive_ptr<ID3D11VertexShader> vertexShader; boost::intrusive_ptr<ID3D11PixelShader> pixelShader; boost::intrusive_ptr<ID3D11InputLayout> inputLayout; boost::intrusive_ptr<ID3D11DepthStencilState> depthStencilState; boost::intrusive_ptr<ID3D11BlendState> blendState; std::array<boost::intrusive_ptr<ID3D11ShaderResourceView>, 8> textureViews; boost::intrusive_ptr<ID3D11SamplerState> samplerState; boost::intrusive_ptr<ID3D11DepthStencilState> transparentDepthStencilState; boost::intrusive_ptr<ID3D11DepthStencilState> fillGapsDepthStencilState; }; struct ShaderConstants { float4x4 projectionViewMatrix; float4x4 worldMatrix; float4 alpha; float4 clipPlane; }; static std::weak_ptr<SharedProperties> m_sharedWeakPtr; std::shared_ptr<SharedProperties> m_shared; GraphicsDevice& m_graphicsDevice; boost::intrusive_ptr<ID3D11Buffer> m_constantBuffer; ShaderConstants m_constants; std::vector<RenderOp> m_renderOps; std::vector<RenderOp> m_transparentRenderOps; std::vector<RenderOp> m_gapFillerRenderOps; }; #endif // __NYX_VOXELRENDERER_H__
rengeln/nyx
src/VoxelManager.h
<reponame>rengeln/nyx /////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_VOXELMANAGER_H__ #define __NYX_VOXELMANAGER_H__ #include "Camera.h" // // Forward declarations. // class LineRenderer; class GraphicsDevice; class RenderContext; class SceneConstants; class VoxelProcessor; class VoxelRenderer; class VoxelMesh; class VoxelManager : public boost::noncopyable { public: // // Constructor. // // Parameters: // [in] graphicsDevice // Parent GraphicsDevice instance. // [in] treeDepth // Maximum octree depth; // [in] nodeDimensions // Worldspace dimensions of a root node in the octree. // [in] radius // Visual radius around the camera to load nodes. // VoxelManager(GraphicsDevice& graphicsDevice, size_t treeDepth, float3 nodeDimensions, float radius); // // Destructor. // ~VoxelManager(); // // Updates the simulation. // void Update(); // // Updates the voxel world based on the camera position. // void SetCamera(const Camera& camera); // // Draws the voxel world. // // Parameters: // [in] renderContext // Render context. // [in] sceneConstants // Scene constants. // void Draw(RenderContext& renderContext, const SceneConstants& sceneConstants); // // Draws the voxel bounding boxes. // // Parameters: // [in] renderContext // Render context. // [in] sceneConstants // Scene constants. // void DrawBoundingBoxes(RenderContext& renderContext, const SceneConstants& sceneConstants); // // Processes pending nodes. // void ProcessNodes(); private: // // An individual node in the tree. // struct Node { std::array<std::shared_ptr<Node>, 8> children; float3 position; float3 size; int depth; uint64_t id; float distance; std::shared_ptr<VoxelMesh> geometry; float alpha; Node* parent; bool visible; }; // // Packs a node ID. // static uint64_t MakeNodeId(int16_t baseX, int16_t baseZ, int16_t baseY, size_t depth, size_t subX, size_t subY, size_t subZ); // // Updates an individual node. // void UpdateNode(Node& node, const Camera& camera); // // Calculates a node's visibility. // void CalculateNodeVisibility(Node& node, const Frustum& frustum, bool recursive = true); // // Splits a node. // void SplitNode(Node& node); // // Unsplits a node. // void UnsplitNode(Node& node); // // Draws a node. // void DrawNode(Node& node, bool recursive); void DrawNodeBoundingBox(Node& node); // // Creates a new node. // std::shared_ptr<Node> CreateNode(uint64_t id, Node* parent); // // Enqueues a node for processing. // void ProcessNode(std::shared_ptr<Node> node); // // Compares two nodes to determine processing priority. // static bool CompareNodePriority(const Node& lhs, const Node& rhs); // // Properties. // static const size_t MaxTreeDepth = 8; GraphicsDevice& m_graphicsDevice; std::unique_ptr<VoxelRenderer> m_voxelRenderer; std::unique_ptr<LineRenderer> m_lineRenderer; Camera m_oldCamera; uint3 m_cellsPerNode; size_t m_treeDepth; float m_radius; std::array<float3, MaxTreeDepth> m_nodeDimensions; std::array<float, MaxTreeDepth + 1> m_splitDistances; std::array<float, MaxTreeDepth + 1> m_unsplitDistances; std::array<float, MaxTreeDepth + 1> m_fadeOutStartDistances; std::array<float, MaxTreeDepth + 1> m_fadeOutEndDistances; std::array<std::unique_ptr<VoxelProcessor>, 4> m_voxelProcessorArray; std::map<uint64_t, std::shared_ptr<Node>> m_nodeMap; std::vector<std::shared_ptr<Node>> m_pendingNodes; bool m_mustSortNodes; }; inline uint64_t VoxelManager::MakeNodeId(int16_t baseX, int16_t baseZ, int16_t baseY, size_t depth, size_t subX, size_t subY, size_t subZ) { uint64_t baseX64 = *reinterpret_cast<uint16_t*>(&baseX), baseZ64 = *reinterpret_cast<uint16_t*>(&baseZ), baseY64 = *reinterpret_cast<uint16_t*>(&baseY); return (baseX64 << 48) | (baseZ64 << 32) | (baseY64 << 16) | ((depth & 0x0F) << 12) | ((subX & 0x0F) << 8) | ((subY & 0x0F) << 4) | ((subZ & 0x0F) << 0); } inline bool VoxelManager::CompareNodePriority(const Node& lhs, const Node& rhs) { if (lhs.visible != rhs.visible) { return lhs.visible > rhs.visible; } if (lhs.depth != rhs.depth) { return lhs.depth < rhs.depth; } else { return lhs.distance < rhs.distance; } } #endif // __NYX_VOXELMANAGER_H__
rengeln/nyx
src/Vector.h
<reponame>rengeln/nyx /////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_VECTOR_H__ #define __NYX_VECTOR_H__ inline float Lerp(float a, float b, float t) { return a + ((b - a) * t); } template <typename T> inline bool Equals(const T& a, const T& b) { return a == b; } inline bool Equals(float a, float b) { return std::fabs(a - b) < 0.0001f; } inline bool Equals(double a, double b) { return std::fabs(a - b) < 0.0001f; } template <typename T, size_t N> class VectorBase { public: }; template <typename T> class VectorBase<T, 2> { public: T x, y; }; template <typename T> class VectorBase<T, 3> { public: T x, y, z; }; template <typename T> class VectorBase<T, 4> { public: T x, y, z, w; }; template <typename T, size_t N> class Vector : public VectorBase<T, N> { static_assert(N >= 2 && N <= 4, "N must be between 2 and 4"); public: // // Default constructor. // Vector(); // // Construct from an arbitrary vector. // template <typename U, size_t M> Vector(const Vector<U, M>& cpy); // // Construct from an arbitrary vector with one additional component value. // template <typename U, size_t M> Vector(const Vector<U, M>& cpy, const T& a); // // Construct from an arbitrary vector with two additional component values. // template <typename U, size_t M> Vector(const Vector<U, M>& cpy, const T& a, const T& b); // // Construct from component values. // Vector(const T& a, const T& b); Vector(const T& a, const T& b, const T& c); Vector(const T& a, const T& b, const T& c, const T& d); // // Assignment from an arbitrary vector. // template <typename U, size_t M> Vector<T, N>& operator=(const Vector<U, M>& rhs); // // Memberwise arithmatic with assignment operators. // Vector<T, N>& operator+=(const Vector<T, N>& rhs); Vector<T, N>& operator-=(const Vector<T, N>& rhs); Vector<T, N>& operator*=(const Vector<T, N>& rhs); Vector<T, N>& operator/=(const Vector<T, N>& rhs); // // Scalar arithmetic with assignment operators. // Vector<T, N>& operator+=(const T& rhs); Vector<T, N>& operator-=(const T& rhs); Vector<T, N>& operator*=(const T& rhs); Vector<T, N>& operator/=(const T& rhs); // // Array index operator. // T& operator[](size_t n); T operator[](size_t n) const; // // Length and squared length operators. // friend T Length(const Vector<T, N>& lhs); friend T Length2(const Vector<T, N>& lhs); // // Comparison operator. // template <typename U, size_t O> friend bool operator==(const Vector<U, O>& lhs, const Vector<U, O>& rhs); // // Negation operator. // template <typename U, size_t O> friend Vector<U, O> operator-(const Vector<U, O>& lhs); // // Memberwise arithmatic operators. // template <typename U, size_t O> friend Vector<U, O> operator+(const Vector<U, O>& lhs, const Vector<U, O>& rhs); template <typename U, size_t O> friend Vector<U, O> operator-(const Vector<U, O>& lhs, const Vector<U, O>& rhs); template <typename U, size_t O> friend Vector<U, O> operator*(const Vector<U, O>& lhs, const Vector<U, O>& rhs); template <typename U, size_t O> friend Vector<U, O> operator/(const Vector<U, O>& lhs, const Vector<U, O>& rhs); // // Scalar arithmetic operators. // template <typename U, size_t O> friend Vector<U, O> operator+(const Vector<U, O>& lhs, const U& rhs); template <typename U, size_t O> friend Vector<U, O> operator-(const Vector<U, O>& lhs, const U& rhs); template <typename U, size_t O> friend Vector<U, O> operator*(const Vector<U, O>& lhs, const U& rhs); template <typename U, size_t O> friend Vector<U, O> operator/(const Vector<U, O>& lhs, const U& rhs); // // Dot product. // template <typename U, size_t O> friend U Dot(const Vector<U, O>& lhs, const Vector<U, O>& rhs); // // Cross product (3D vectors only) // template <typename U, size_t O> friend Vector<U, 3> Cross(const Vector<U, 3>& lhs, const Vector<U, 3>& rhs); // // Linear interpolation between vectors. // template <typename U, size_t O, typename V> friend Vector<U, O> Lerp(const Vector<U, O>& lhs, const Vector<U, O>& rhs, const V& t); // // Returns the normalized form of a vector. // template <typename U, size_t O> friend Vector<U, O> Normalize(const Vector<U, O>& lhs); // // Returns the result of concatenating two quaternions. // template <typename U> friend Vector<U, 4> QuaternionConcatenate(const Vector<U, 4>& lhs, const Vector<U, 4>& rhs); // // Returns the result of slerping between two quaternions. // template <typename U> friend Vector<U, 4> QuaternionSlerp(const Vector<U, 4>& lhs, const Vector<U, 4>& rhs, const U& t); // // Returns the inverse of a quaternion. // template <typename U> friend Vector<U, 4> QuaternionInverse(const Vector<U, 4>& lhs); // // Returns a zero vector. // static Vector<T, N> Zero(); // // Returns a vector with a value replicated in every component. // static Vector<T, N> Replicate(const T& v); // // Returns an identity quaternion. // static Vector<T, N> IdentityQuaternion(); // // Returns a quaternion based on roll, pitch, and yaw angles. // static Vector<T, N> RotationQuaternion(const T& roll, const T& pitch, const T& yaw); // // Returns a quaternion based on an arbitrary axis of rotation. // static Vector<T, N> RotationQuaternion(const Vector<T, 3>& axis, const T& angle); }; template <typename T, size_t N> inline Vector<T, N>::Vector() { } template <typename T, size_t N> template <typename U, size_t M> inline Vector<T, N>::Vector(const Vector<U, M>& cpy) { *this = cpy; } template <typename T, size_t N> template <typename U, size_t M> inline Vector<T, N>::Vector(const Vector<U, M>& cpy, const T& a) { static_assert(N == M + 1, "Requires N == M + 1"); *this = cpy; (*this)[N - 1] = a; } template <typename T, size_t N> template <typename U, size_t M> inline Vector<T, N>::Vector(const Vector<U, M>& cpy, const T& a, const T& b) { static_assert(N == M + 2, "Requires N == M + 2"); *this = cpy; (*this)[N - 2] = a; (*this)[N - 1] = b; } template <typename T, size_t N> inline Vector<T, N>::Vector(const T& a, const T& b) { static_assert(N == 2, "Requires N == 2"); x = a; y = b; } template <typename T, size_t N> inline Vector<T, N>::Vector(const T& a, const T& b, const T& c) { static_assert(N == 3, "Requires N == 3"); x = a; y = b; z = c; } template <typename T, size_t N> inline Vector<T, N>::Vector(const T& a, const T& b, const T& c, const T& d) { static_assert(N == 4, "Requires N == 4"); x = a; y = b; z = c; w = d; } template <typename T, size_t N> template <typename U, size_t M> inline Vector<T, N>& Vector<T, N>::operator=(const Vector<U, M>& rhs) { for (size_t i = 0; i < min(N, M); i++) { (*this)[i] = static_cast<T>(rhs[i]); } if (N > M) { for (size_t i = M; i < N; i++) { (*this)[i] = static_cast<T>(0); } } return *this; } template <typename T, size_t N> inline Vector<T, N>& Vector<T, N>::operator+=(const Vector<T, N>& rhs) { return *this = *this + rhs; } template <typename T, size_t N> inline Vector<T, N>& Vector<T, N>::operator-=(const Vector<T, N>& rhs) { return *this = *this - rhs; } template <typename T, size_t N> inline Vector<T, N>& Vector<T, N>::operator*=(const Vector<T, N>& rhs) { return *this = *this * rhs; } template <typename T, size_t N> inline Vector<T, N>& Vector<T, N>::operator/=(const Vector<T, N>& rhs) { return *this = *this / rhs; } template <typename T, size_t N> inline Vector<T, N>& Vector<T, N>::operator+=(const T& rhs) { return *this = *this + rhs; } template <typename T, size_t N> inline Vector<T, N>& Vector<T, N>::operator-=(const T& rhs) { return *this = *this - rhs; } template <typename T, size_t N> inline Vector<T, N>& Vector<T, N>::operator*=(const T& rhs) { return *this = *this * rhs; } template <typename T, size_t N> inline Vector<T, N>& Vector<T, N>::operator/=(const T& rhs) { return *this = *this / rhs; } template <typename T, size_t N> inline T& Vector<T, N>::operator[](size_t i) { assert(i < N); return reinterpret_cast<T*>(this)[i]; } template <typename T, size_t N> inline T Vector<T, N>::operator[](size_t i) const { assert(i < N); return reinterpret_cast<const T*>(this)[i]; } template <typename T, size_t N> inline T Length(const Vector<T, N>& lhs) { static_assert(boost::is_float<T>::value, "Requires is_float<T>"); return sqrt(Length2(lhs)); } template <typename T, size_t N> inline T Length2(const Vector<T, N>& lhs) { return Dot(lhs, lhs); } template <typename T, size_t N> inline bool operator==(const Vector<T, N>& lhs, const Vector<T, N>& rhs) { for (size_t i = 0; i < N; i++) { if (!Equals(lhs[i], rhs[i])) { return false; } } return true; } template <typename T, size_t N> inline Vector<T, N> operator-(const Vector<T, N>& lhs) { Vector<T, N> result; for (size_t i = 0; i < N; i++) { result[i] = -lhs[i]; } return result; } template <typename T, size_t N> inline Vector<T, N> operator+(const Vector<T, N>& lhs, const Vector<T, N>& rhs) { Vector<T, N> result; for (size_t i = 0; i < N; i++) { result[i] = lhs[i] + rhs[i]; } return result; } template <typename T, size_t N> inline Vector<T, N> operator-(const Vector<T, N>& lhs, const Vector<T, N>& rhs) { Vector<T, N> result; for (size_t i = 0; i < N; i++) { result[i] = lhs[i] - rhs[i]; } return result; } template <typename T, size_t N> inline Vector<T, N> operator*(const Vector<T, N>& lhs, const Vector<T, N>& rhs) { Vector<T, N> result; for (size_t i = 0; i < N; i++) { result[i] = lhs[i] * rhs[i]; } return result; } template <typename T, size_t N> inline Vector<T, N> operator/(const Vector<T, N>& lhs, const Vector<T, N>& rhs) { Vector<T, N> result; for (size_t i = 0; i < N; i++) { result[i] = lhs[i] / rhs[i]; } return result; } template <typename T, size_t N> inline Vector<T, N> operator+(const Vector<T, N>& lhs, const T& rhs) { Vector<T, N> result; for (size_t i = 0; i < N; i++) { result[i] = lhs[i] + rhs; } return result; } template <typename T, size_t N> inline Vector<T, N> operator-(const Vector<T, N>& lhs, const T& rhs) { Vector<T, N> result; for (size_t i = 0; i < N; i++) { result[i] = lhs[i] - rhs; } return result; } template <typename T, size_t N> inline Vector<T, N> operator*(const Vector<T, N>& lhs, const T& rhs) { Vector<T, N> result; for (size_t i = 0; i < N; i++) { result[i] = lhs[i] * rhs; } return result; } template <typename T, size_t N> inline Vector<T, N> operator/(const Vector<T, N>& lhs, const T& rhs) { Vector<T, N> result; for (size_t i = 0; i < N; i++) { result[i] = lhs[i] / rhs; } return result; } template <typename T, size_t N> inline T Dot(const Vector<T, N>& lhs, const Vector<T, N>& rhs) { T result = 0; for (size_t i = 0; i < N; i++) { result += lhs[i] * rhs[i]; } return result; } template <typename T> inline Vector<T, 3> Cross(const Vector<T, 3>& lhs, const Vector<T, 3>& rhs) { return Vector<T, 3>(lhs.y * rhs.z - lhs.z * rhs.y, lhs.z * rhs.x - lhs.x * rhs.z, lhs.x * rhs.y - lhs.y * rhs.x); } template <typename T, size_t N, typename U> inline Vector<T, N> Lerp(const Vector<T, N>& lhs, const Vector<T, N>& rhs, const U& t) { static_assert(boost::is_float<U>::value, "Requires is_float<U>"); Vector<T, N> result; for (size_t i = 0; i < N; i++) { result[i] = lhs[i] + static_cast<T>(static_cast<U>(rhs[i] - lhs[i]) * t); } return result; } template <typename T, size_t N> inline Vector<T, N> Normalize(const Vector<T, N>& lhs) { return lhs / lhs.Length(); } template <typename T, size_t N> inline Vector<T, N> Vector<T, N>::Zero() { Vector<T, N> result; for (size_t i = 0; i < N; i++) { result[i] = 0; } return result; } template <typename T, size_t N> inline Vector<T, N> Vector<T, N>::Replicate(const T& v) { Vector<T, N> result; for (size_t i = 0; i < N; i++) { result[i] = v; } return result; } template <typename T, size_t N> inline Vector<T, N> Vector<T, N>::IdentityQuaternion() { static_assert(boost::is_float<T>::value, "Requires is_float<T>"); static_assert(N == 4, "Requires N == 4"); return Vector<T, N>(static_cast<T>(0), static_cast<T>(0), static_cast<T>(0), static_cast<T>(1)); } template <typename T, size_t N> inline Vector<T, N> Vector<T, N>::RotationQuaternion(const T& pitch, const T& yaw, const T& roll) { static_assert(boost::is_float<T>::value, "Requires is_float<T>"); static_assert(N == 4, "Requires N == 4"); Vector<float, N> result; XMStoreFloat4(reinterpret_cast<XMFLOAT4*>(&result), XMQuaternionRotationRollPitchYaw(pitch, yaw, roll)); return Vector<T, N>(result); } template <typename T, size_t N> inline Vector<T, N> Vector<T, N>::RotationQuaternion(const Vector<T, 3>& axis, const T& angle) { static_assert(boost::is_float<T>::value, "Requires is_float<T>"); static_assert(N == 4, "Requires N == 4"); Vector<float, N> result; Vector<float, 3> xyz(axis); XMStoreFloat4(reinterpret_cast<XMFLOAT4*>(result), XMQuaternionRotationAxis(XMLoadFloat3(reinterpret_cast<const XMFLOAT3*>(&xyz)), angle)); return Vector<T, N>(result); } template <typename T> Vector<T, 4> QuaternionConcatenate(const Vector<T, 4>& lhs, const Vector<T, 4>& rhs) { static_assert(boost::is_float<T>::value, "Requires is_float<T>"); Vector<float, 4> result, a(lhs), b(rhs); XMStoreFloat4(reinterpret_cast<XMFLOAT4*>(result), XMQuaternionMultiply(XMLoadFloat4(reinterpret_cast<const XMFLOAT4*>(&a)), XMLoadFloat4(reinterpret_cast<const XMFLOAT4*>(&b)))); return Vector<T, 4>(result); } template <typename T> Vector<T, 4> QuaternionSlerp(const Vector<T, 4>& lhs, const Vector<T, 4>& rhs, const T& t) { static_assert(boost::is_float<T>::value, "Requires is_float<T>"); Vector<float, 4> result, a(lhs), b(rhs); XMStoreFloat4(reinterpret_cast<XMFLOAT4*>(result), XMQuaternionSlerp(XMLoadFloat4(reinterpret_cast<const XMFLOAT4*>(&a)), XMLoadFloat4(reinterpret_cast<const XMFLOAT4*>(&b)), static_cast<T>(t))); return Vector<T, 4>(result); } template <typename T> Vector<T, 4> QuaternionInverse(const Vector<T, 4>& lhs) { static_assert(boost::is_float<T>::value, "Requires is_float<T>"); Vector<float, 4> result, a(lhs); XMStoreFloat4(reinterpret_cast<XMFLOAT4*>(&result), XMQuaternionInverse(XMLoadFloat4(reinterpret_cast<const XMFLOAT4*>(&a)))); return Vector<T, 4>(result); } typedef Vector<float, 2> float2; typedef Vector<float, 3> float3; typedef Vector<float, 4> float4; typedef Vector<double, 2> double2; typedef Vector<double, 3> double3; typedef Vector<double, 4> double4; typedef Vector<int, 2> int2; typedef Vector<int, 3> int3; typedef Vector<int, 4> int4; typedef Vector<unsigned int, 2> uint2; typedef Vector<unsigned int, 3> uint3; typedef Vector<unsigned int, 4> uint4; typedef Vector<char, 2> byte2; typedef Vector<char, 3> byte3; typedef Vector<char, 4> byte4; typedef Vector<unsigned char, 2> ubyte2; typedef Vector<unsigned char, 3> ubyte3; typedef Vector<unsigned char, 4> ubyte4; typedef Vector<short, 2> short2; typedef Vector<short, 3> short3; typedef Vector<short, 4> short4; typedef Vector<unsigned short, 2> ushort2; typedef Vector<unsigned short, 3> ushort3; typedef Vector<unsigned short, 4> ushort4; typedef std::pair<float2, float2> box2f; typedef std::pair<float3, float3> box3f; typedef std::pair<float4, float4> box4f; typedef std::pair<double2, double2> box2d; typedef std::pair<double3, double3> box3d; typedef std::pair<double4, double4> box4d; typedef std::pair<int2, int2> box2i; typedef std::pair<int3, int3> box3i; typedef std::pair<int4, int4> box4i; typedef std::pair<uint2, uint2> box2u; typedef std::pair<uint3, uint3> box3u; typedef std::pair<uint4, uint4> box4u; #endif // __NYX_VECTOR_H__
rengeln/nyx
src/SceneManager.h
/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2011 <NAME> (<EMAIL>) All rights reserved. // See accompanying LICENSE file for full license information. /////////////////////////////////////////////////////////////////////////////// #ifndef __NYX_SCENEMANAGER_H__ #define __NYX_SCENEMANAGER_H__ #include "Camera.h" #include "Frustum.h" // // Forward declarations. // class GraphicsDevice; class SkyRenderer; class RenderContext; class VoxelManager; class WaterManager; // // Global rendering constants. // class SceneConstants { public: float4x4 viewMatrix; float4x4 projectionMatrix; Frustum frustum; float4 clipPlane; float3 cameraPos; bool lowDetail; }; class SceneManager : public boost::noncopyable { public: // // Constructor. // // Parameters: // [in] graphicsDevice // GraphicsDevice instance. // SceneManager(GraphicsDevice& graphicsDevice); // // Destructor. // ~SceneManager(); // // Sets the camera position. // void SetCamera(const Camera& camera); // // Updates the simulation. // void Update(); // // Draws the scene. // void Draw(); // // Draws the scene for an individual render stage. // void DrawStage(RenderContext& renderContext, const SceneConstants& sceneConstants); // // Returns the GraphicsDevice instance. // GraphicsDevice& GetGraphicsDevice(); private: // // Properties. // GraphicsDevice& m_graphicsDevice; std::unique_ptr<VoxelManager> m_voxelManager; std::unique_ptr<SkyRenderer> m_skyRenderer; std::unique_ptr<WaterManager> m_waterManager; Camera m_camera; }; inline GraphicsDevice& SceneManager::GetGraphicsDevice() { return m_graphicsDevice; } #endif // __NYX_SCENEMANGER_H__
lancewalk87/CLSL-TcpIp-Client
src/CLNetworkingClient.h
#ifndef _CLNETWORKINGCLIENT_H #define _CLNETWORKINGCLIENT_H #include <cstlib> #include <iostream> #endif
YueShuai798/scaleView
ScaleView/ScaleView/YSScaleView.h
<reponame>YueShuai798/scaleView<gh_stars>1-10 // // IDScaleView.h // kvo // // Created by 悦帅 on 2018/4/27. // Copyright © 2018年 悦帅. All rights reserved. // #import <UIKit/UIKit.h> @class YSShowView; typedef enum { YSPanAtTopLeftCorner,//左上角 YSPanAtTopRightCorner,//右上角 YSPanAtBottomLeftCorner,//左下角 YSPanAtBottomRightCorner,//右下角 YSPanAtTopBorder,//上中 YSPanAtBottomBorder,//下中 YSPanAtLeftBorder,//左中 YSPanAtRightBorder,//右中 YSPanAtCenter,//正中 YSPanAtNone } YSPanPosition; @protocol YSScaleViewDelegate<NSObject> @optional /** 开始拖动 @param showView 窗体控件 @param frame 窗体的大小 */ - (void)showViewDidBeginDraging:(YSShowView *)showView withShowFrame:(CGRect)frame; /** 正在拖动 @param showView 窗体控件 @param frame 窗体的大小 */ - (void)showViewDidDraging:(YSShowView *)showView withShowFrame:(CGRect)frame; /** 拖动完毕 @param showView 窗体控件 @param frame 窗体的大小 */ - (void)showViewDidEndDraging:(YSShowView *)showView withShowFrame:(CGRect)frame; @end @interface YSShowView:UIView @end @interface YSScaleView : UIView @property (weak, nonatomic)id<YSScaleViewDelegate>delegate; /** 默认灰色的背景颜色 */ @property (strong, nonatomic)UIColor *backColor; /** 透视窗口的边角的颜色 */ @property (strong, nonatomic)UIColor *cornerColor; /** 边角宽 */ @property (assign, nonatomic)CGFloat cornerWidth; /** 边角线宽 */ @property (assign, nonatomic)CGFloat cornerLineWidth; /** 透视窗体的大小 */ @property (assign, nonatomic)CGRect showFrame; /** 初始化的方法 @param scaleFrame 背景的view的大小 @param showFrame 透视窗口的大小 @return 返回实例化对象 */ + (instancetype)scaleViewWithScaleFrame:(CGRect)scaleFrame showFrame:(CGRect)showFrame; @end
cpgribble78/owl
owl/Buffer.h
<gh_stars>0 // ======================================================================== // // Copyright 2019-2020 <NAME> // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #pragma once #include "RegisteredObject.h" #include "Texture.h" namespace owl { /*! base class for any sort of buffer type - pinned, device, managed, ... */ struct Buffer : public RegisteredObject { typedef std::shared_ptr<Buffer> SP; /*! any device-specific data, such as optix handles, cuda device pointers, etc */ struct DeviceData : public RegisteredObject::DeviceData { typedef std::shared_ptr<DeviceData> SP; /*! constructor */ DeviceData(const DeviceContext::SP &device); /*! device-side pointer - depending on buffer type this may or may not be accessible on the host */ void *d_pointer { 0 }; }; /*! construct a new buffer of given type - actual implementation of 'construct' done in derives class */ Buffer(Context *const context, OWLDataType type); /*! destructor - free device data, de-regsiter, and destruct */ virtual ~Buffer(); /*! pretty-printer, for printf-debugging */ std::string toString() const override; /*! get reference to given device-specific data for this object */ inline Buffer::DeviceData &getDD(const DeviceContext::SP &device) const; /*! get device pointer for given buffer */ inline const void *getPointer(const DeviceContext::SP &device) const; /*! return *number* of elements - number of bytes will depend on data type */ inline size_t getElementCount() const; /*! return the number of *bytes* in this buffer (coiuted in size of device types) */ inline size_t sizeInBytes() const { return elementCount * sizeOf(type); } /*! resize buffer to new num elements */ virtual void resize(size_t newElementCount) = 0; /*! upload data from host, using as many bytes as required by elemnetCount and dataSize */ virtual void upload(const void *hostPtr) = 0; /*! upload data from host, to only given device ID */ virtual void upload(const int deviceID, const void *hostPtr) = 0; /*! creates the device-specific data for this group */ RegisteredObject::DeviceData::SP createOn(const DeviceContext::SP &device) override; /*! destroy whatever resouces this buffer may own on the device, but do NOT destroy this class itself. baiscally that's a resize(0), but that buffer can not - and shoult not - be used any more after that */ void destroy(); /*! data type of elements contained in this buffer */ const OWLDataType type; /*! number of elements */ size_t elementCount { 0 }; }; /*! a device-side buffer that has its own cuda-malloc'ed memory on each device. DeviceBuffers are fastest to access on the device, *BUT* are not visible on the host, and are replicated in the sense that changing to a device buffer on one GPU will not be visible on other GPUs */ struct DeviceBuffer : public Buffer { typedef std::shared_ptr<DeviceBuffer> SP; /*! any device-specific data, such as optix handles, cuda device pointers, etc. this is a virtual base class whose derived classes will do the actual work */ struct DeviceData : public Buffer::DeviceData { typedef std::shared_ptr<DeviceData> SP; /*! any device-specific data, such as optix handles, cuda device pointers, etc */ DeviceData(DeviceBuffer *parent, const DeviceContext::SP &device); /*! destructor that releases any still-alloced memory */ virtual ~DeviceData(); /*! executes the resize on the given device, including freeing old memory, and allocating required elemnts in device format, as required */ virtual void executeResize() = 0; /*! create an async upload for data from the given host data pointer, using the given device's cuda stream, and doing any required translation from host-side data (eg, a texture object handle) to device-side data (ie, the cudaTextreObject_t for that device). this will *not* wait for the upload to complete, so an explicit cuda sync has to be done to ensure no race conditiosn will occur */ virtual void uploadAsync(const void *hostDataPtr) = 0; // DeviceContext::SP const device; DeviceBuffer *const parent; }; /*! device-data for a device buffer like other device buffers, but containing texture objects - ie, these are Texture::SP on the host, but get translated to cudaTextureObject_t's upon upload */ struct DeviceDataForTextures : public DeviceData { DeviceDataForTextures(DeviceBuffer *parent, const DeviceContext::SP &device) : DeviceData(parent,device) {} void executeResize() override; void uploadAsync(const void *hostDataPtr) override; /*! this is used only for buffers over object types (bufers of textures, or buffers of buffers). For those buffers, we use this vector to store host-side handles of the objects in this buffer, to ensure proper recounting */ std::vector<Texture::SP> hostHandles; }; /*! device-data for a device buffer like other device buffers, but containing buffers - ie, these are Buffer::SP on the host, but get translated to buffer descriptors upon upload */ struct DeviceDataForBuffers : public DeviceData { DeviceDataForBuffers(DeviceBuffer *parent, const DeviceContext::SP &device) : DeviceData(parent,device) {} void executeResize() override; void uploadAsync(const void *hostDataPtr) override; /*! this is used only for buffers over object types (bufers of textures, or buffers of buffers). For those buffers, we use this vector to store host-side handles of the objects in this buffer, to ensure proper recounting */ std::vector<Buffer::SP> hostHandles; }; /*! device-data for a device buffer that contains raw, copyable data (float, vec3f, etc) */ struct DeviceDataForCopyableData : public DeviceData { DeviceDataForCopyableData(DeviceBuffer *parent, const DeviceContext::SP &device) : DeviceData(parent,device) {} void executeResize() override; void uploadAsync(const void *hostDataPtr) override; }; /*! contructor - creates the right device data type based on content type */ DeviceBuffer(Context *const context, OWLDataType type); /*! pretty-printer, for debugging */ std::string toString() const override; /*! get reference to given device-specific data for this object */ inline DeviceData &getDD(const DeviceContext::SP &device) const; /*! resize this buffer - actual work will get done in DeviceData */ void resize(size_t newElementCount) override; /*! upload to device data(s) of that buffer - actual work will get done in DeviceData */ void upload(const void *hostPtr) override; /*! upload to only ONE device - only makes sense for device buffers */ void upload(const int deviceID, const void *hostPtr) override; /*! creates the device-specific data for this group */ RegisteredObject::DeviceData::SP createOn(const DeviceContext::SP &device) override; }; /*! a buffer that uses CUDA host-pinned memory. only makes sense for copyable data types */ struct HostPinnedBuffer : public Buffer { typedef std::shared_ptr<HostPinnedBuffer> SP; HostPinnedBuffer(Context *const context, OWLDataType type); /*! pretty-printer, for debugging */ std::string toString() const override; void resize(size_t newElementCount) override; void upload(const void *hostPtr) override; void upload(const int deviceID, const void *hostPtr) override; /*! pointer to the (shared) cuda pinned mem - this gets alloced once and is valid on both host and devices */ void *cudaHostPinnedMem { 0 }; }; /*! a buffer that uses CUDA 'managed' memory. only makes sense for copyable data types. Make sure to read up on how managed mem works */ struct ManagedMemoryBuffer : public Buffer { typedef std::shared_ptr<ManagedMemoryBuffer> SP; ManagedMemoryBuffer(Context *const context, OWLDataType type); void resize(size_t newElementCount) override; void upload(const void *hostPtr) override; void upload(const int deviceID, const void *hostPtr) override; /*! pretty-printer, for debugging */ std::string toString() const override; /*! pointer to the (shared) cuda managed mem - this gets alloced once and is valid on both host and devices */ void *cudaManagedMem { 0 }; }; /*! a special graphics resource buffer that, upon mapping, will map that graphics resource */ struct GraphicsBuffer : public Buffer { typedef std::shared_ptr<GraphicsBuffer> SP; GraphicsBuffer(Context* const context, OWLDataType type, cudaGraphicsResource_t resource); void map(const int deviceID=0, CUstream stream=0); void unmap(const int deviceID=0, CUstream stream=0); void resize(size_t newElementCount) override; void upload(const void *hostPtr) override; void upload(const int deviceID, const void *hostPtr) override; /*! the cuda graphics resource to map to - note that this is probably valid on only one GPU */ cudaGraphicsResource_t resource; /*! pretty-printer, for debugging */ std::string toString() const override; }; // ------------------------------------------------------------------ // implementation section // ------------------------------------------------------------------ /*! return *number* of elements - number of bytes will depend on data type */ inline size_t Buffer::getElementCount() const { return elementCount; } /*! get device pointer for given buffer */ const void *Buffer::getPointer(const DeviceContext::SP &device) const { assert(device); return getDD(device).d_pointer; } /*! get reference to given device-specific data for this object */ inline Buffer::DeviceData &Buffer::getDD(const DeviceContext::SP &device) const { assert(device && device->ID >= 0 && device->ID < deviceData.size()); return deviceData[device->ID]->as<Buffer::DeviceData>(); } /*! get reference to given device-specific data for this object */ inline DeviceBuffer::DeviceData &DeviceBuffer::getDD(const DeviceContext::SP &device) const { assert(device && device->ID >= 0 && device->ID < deviceData.size()); return deviceData[device->ID]->as<DeviceData>(); } } // ::owl
cpgribble78/owl
owl/Context.h
// ======================================================================== // // Copyright 2019-2020 <NAME> // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #pragma once #include "DeviceContext.h" #include "ObjectRegistry.h" #include "Buffer.h" #include "Texture.h" #include "Group.h" #include "RayGen.h" #include "LaunchParams.h" #include "MissProg.h" namespace owl { /*! the root 'context' that spans, and manages, all objects and all devices */ struct Context : public Object { typedef std::shared_ptr<Context> SP; /*! returns whether logging is enabled */ inline static bool logging() { #ifdef NDEBUG return false; #else return true; #endif } /*! creates a context with the given device IDs. If list of device is nullptr, and number requested devices is > 1, then the first N devices will get used; invalid device IDs in the list will automatically get dropped */ Context(int32_t *requestedDeviceIDs, int numRequestedDevices); /*! virtual destructor to cleanly wind down upon exit */ virtual ~Context(); size_t deviceCount() const { return getDevices().size(); } const std::vector<DeviceContext::SP> &getDevices() const { return devices; } DeviceContext::SP getDevice(int ID) const { assert(ID >= 0 && ID < devices.size()); return devices[ID]; } /*! part of the SBT creation - builds the hit group array */ void buildHitGroupRecordsOn(const DeviceContext::SP &device); /*! part of the SBT creation - builds the raygen array */ void buildRayGenRecordsOn(const DeviceContext::SP &device); /*! part of the SBT creation - builds the miss group array */ void buildMissProgRecordsOn(const DeviceContext::SP &device); /*! sets number of ray types to be used - should be done right after context creation, and before SBT and pipeline get built */ void setRayTypeCount(size_t rayTypeCount); /*! enables motoin blur - should be done right after context creation, and before SBT and pipeline get built */ void enableMotionBlur(); /*! sets maximum instancing depth for the given context: '0' means 'no instancing allowed, only bottom-level accels; '1' means 'at most one layer of instances' (ie, a two-level scene), where the 'root' world rays are traced against can be an instance group, but every child in that inscne group is a geometry group. 'N>1" means "up to N layers of instances are allowed. The default instancing depth is 1 (ie, a two-level scene), since this allows for most use cases of instancing and is still hardware-accelerated. Using a node graph with instancing deeper than the configured value will result in wrong results; but be aware that using any value > 1 here will come with a cost. It is recommended to, if at all possible, leave this value to one and convert the input scene to a two-level scene layout (ie, with only one level of instances) */ void setMaxInstancingDepth(int32_t maxInstanceDepth); // ------------------------------------------------------------------ // internal mechanichs/plumbling that do the actual work // ------------------------------------------------------------------ void buildSBT(OWLBuildSBTFlags flags); void buildPipeline(); void buildPrograms(); /*! clearly destroy _pptix_ handles of all active programs */ void destroyPrograms(); void buildModules(); /*! clearly destroy _optix_ handles of all active modules */ void destroyModules(); // ------------------------------------------------------------------ // factory methods to create objects within this context // ------------------------------------------------------------------ /*! creates a 2D texture object with given parameters; this will internally be mapped to a cuda texture object, and uploaded as such to the device */ Texture::SP texture2DCreate(OWLTexelFormat texelFormat, OWLTextureFilterMode filterMode, const vec2i size, uint32_t linePitchInBytes, const void *texels); /*! create a new *triangles* geometry group that will eventually create a BVH over all the trinalges in all its child geometries. only TrianglesGeoms can be added to this group. These triangle geoms can all have different types, different programs, etc, but must all be of "OWL_TRIANGLES" kind */ GeomGroup::SP trianglesGeomGroupCreate(size_t numChildren); /*! create a new *user* geometry group that will eventually create a BVH over all the user geoms / custom prims in all its child geometries. only UserGeom's can be added to this group. These user geoms can all have different types, different programs, etc, but must all be of "OWL_TRIANGLES" kind */ GeomGroup::SP userGeomGroupCreate(size_t numChildren); /*! create a new device buffer of given data type and count; if init is non-null it will be used to populoate this buffer. Note that for certain non-trivial types (OWLTexture, OWLGroup, etc) you may have to specify the content upon creation */ Buffer::SP deviceBufferCreate(OWLDataType type, size_t count, const void *init); /*! creates a buffer that uses CUDA host pinned memory; that memory is pinned on the host and accessive to all devices in the device group */ Buffer::SP hostPinnedBufferCreate(OWLDataType type, size_t count); /*! creates a buffer that uses CUDA managed memory; that memory is managed by CUDA (see CUDAs documentation on managed memory) and accessive to all devices in the deviec group */ Buffer::SP managedMemoryBufferCreate(OWLDataType type, size_t count, const void *init); /*! creates a buffer that wraps a CUDA graphics resource that can be, for instance, an OpenGL texture */ Buffer::SP graphicsBufferCreate(OWLDataType type, size_t count, cudaGraphicsResource_t resource); /*! creates new ray gen program *type* with given program name (in given module), and the given variable declarations that describe this type's variables */ RayGenType::SP createRayGenType(Module::SP module, const std::string &progName, size_t varStructSize, const std::vector<OWLVarDecl> &varDecls); /*! create new instance of a ray gen program of given type */ RayGen::SP createRayGen(const std::shared_ptr<RayGenType> &type); /*! create a new launch param type descriptor with given variables; this can then be used to create actual launch param instances (\see createLaunchParams) */ LaunchParamsType::SP createLaunchParamsType(size_t varStructSize, const std::vector<OWLVarDecl> &varDecls); /*! create new instance of a set of launch params of given type */ LaunchParams::SP createLaunchParams(const std::shared_ptr<LaunchParamsType> &type); /*! creates new miss program *type* with given program name (in given module), and the given variable declarations that describe this type's variables */ MissProgType::SP createMissProgType(Module::SP module, const std::string &progName, size_t varStructSize, const std::vector<OWLVarDecl> &varDecls); /*! create new instance of a miss program of given type */ MissProg::SP createMissProg(const std::shared_ptr<MissProgType> &type); /*! sets miss prog to use for a given ray type */ void setMissProg(int rayTypeToSet, MissProg::SP missProgToUse); /*! creates new geometry type defitiion with given variable declarations */ GeomType::SP createGeomType(OWLGeomKind kind, size_t varStructSize, const std::vector<OWLVarDecl> &varDecls); /*! creates new module with given precompiled PTX code */ Module::SP createModule(const std::string &ptxCode); // ------------------------------------------------------------------ // member variables // ------------------------------------------------------------------ /*! @{ registries for all the different object types within this context. allows for keeping track what's alive, and what has to be compiled, put into SBTs, etc */ ObjectRegistryT<Buffer> buffers; ObjectRegistryT<Texture> textures; ObjectRegistryT<Group> groups; ObjectRegistryT<RayGenType> rayGenTypes; ObjectRegistryT<RayGen> rayGens; ObjectRegistryT<MissProgType> missProgTypes; ObjectRegistryT<MissProg> missProgs; ObjectRegistryT<GeomType> geomTypes; ObjectRegistryT<Geom> geoms; ObjectRegistryT<Module> modules; ObjectRegistryT<LaunchParamsType> launchParamTypes; ObjectRegistryT<LaunchParams> launchParams; /*! @} */ /*! tracks which ID regions in the SBT have already been used - newly created groups allocate ranges of IDs in the SBT (to allow its geometries to be in successive SBT regions), and this struct keeps track of whats already used, and what is available */ RangeAllocator sbtRangeAllocator; /*! one miss prog per ray type */ std::vector<MissProg::SP> missProgPerRayType; /*! maximum depth instancing tree as specified by `setMaxInstancingDepth` */ int maxInstancingDepth = 1; /*! number of ray types - change via setRayTypeCount() */ int numRayTypes { 1 }; /*! by default motion blur is off, as it costs performacne - set via enableMotimBlur() */ bool motionBlurEnabled = false; /*! a set of dummy (ie, empty) launch params. allows us for always using the same launch code, *with* launch params, even if th user didn't specify any during launch */ LaunchParams::SP dummyLaunchParams; private: void enablePeerAccess(); std::vector<DeviceContext::SP> devices; }; } // ::owl
cpgribble78/owl
owl/include/owl/common/arrayND/array2D.h
// ======================================================================== // // Copyright 2019-2020 <NAME> // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #pragma once #include <owl/common/math/vec.h> namespace owl { namespace common { namespace array2D { inline int linear(const vec2i &ID, const vec2i &dims) { return ID.x + dims.x*ID.y; } template<typename Lambda> inline void for_each(const vec2i &dims, const Lambda &lambda) { for (int iy=0;iy<dims.y;iy++) for (int ix=0;ix<dims.x;ix++) lambda(vec2i(ix,iy)); } #if OWL_HAVE_PARALLEL_FOR template<typename Lambda> inline void parallel_for(const vec2i &dims, const Lambda &lambda) { owl::common::parallel_for(dims.x*dims.y,[&](int index){ lambda(vec2i(index%dims.x,index/dims.x)); }); } #endif template<typename Lambda> inline void serial_for(const vec2i &dims, const Lambda &lambda) { owl::common::serial_for(dims.x*dims.y,[&](int index){ lambda(vec2i(index%dims.x,index/dims.x)); }); } } // owl::common::array2D } // owl::common } // owl
husseinmaad/OmniSign
ios/build/Build/Intermediates/DocuSignReactNativeSample.build/Debug-iphonesimulator/DocuSignReactNativeSample.build/DerivedSources/DocuSignReactNativeSample_vers.c
extern const unsigned char DocuSignReactNativeSampleVersionString[]; extern const double DocuSignReactNativeSampleVersionNumber; const unsigned char DocuSignReactNativeSampleVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:DocuSignReactNativeSample PROJECT:DocuSignReactNativeSample-1" "\n"; const double DocuSignReactNativeSampleVersionNumber __attribute__ ((used)) = (double)1.;
husseinmaad/OmniSign
ios/build/Build/Products/Debug-iphonesimulator/DocuSignReactNativeSample.app/Frameworks/XCTest.framework/Headers/XCTNSNotificationExpectation.h
<filename>ios/build/Build/Products/Debug-iphonesimulator/DocuSignReactNativeSample.app/Frameworks/XCTest.framework/Headers/XCTNSNotificationExpectation.h<gh_stars>10-100 // // Copyright (c) 2016 Apple Inc. All rights reserved. // #import <XCTest/XCTestDefines.h> #import <XCTest/XCTestExpectation.h> #import <XCTest/XCTestCase+AsynchronousTesting.h> NS_ASSUME_NONNULL_BEGIN /*! * @class XCTNSNotificationExpectation * Expectation subclass for waiting on a condition defined by an NSNotification. */ @interface XCTNSNotificationExpectation : XCTestExpectation { #ifndef __OBJC2__ @private id _internal; #endif } - (instancetype)init NS_UNAVAILABLE; - (instancetype)initWithDescription:(NSString *)expectationDescription NS_UNAVAILABLE; /*! * @method -initWithName:object:notificationCenter: * * @discussion * Initializes an expectation that waits for an NSNotification to be posted by an optional object from * a given notification center. */ - (instancetype)initWithName:(NSString *)notificationName object:(nullable id)object notificationCenter:(NSNotificationCenter *)notificationCenter NS_DESIGNATED_INITIALIZER; /*! * @method -initWithName:object: * * @discussion * Convenience initializer that uses the default NSNotificationCenter. */ - (instancetype)initWithName:(NSString *)notificationName object:(id)object; /*! * @method -initWithName:object: * * @discussion * Convenience initializer that uses the default NSNotificationCenter and accepts the notification from any object. */ - (instancetype)initWithName:(NSString *)notificationName; /*! * @property notificationName * Returns the name of the notification being waited on. */ @property (readonly, copy) NSString *notificationName; /*! * @property observedObject * Returns the object that will post the notification. */ @property (nullable, readonly, strong) id observedObject; /*! * @property notificationCenter * Returns the notification center that is being used. */ @property (readonly, strong) NSNotificationCenter *notificationCenter; /*! * @property handler * Allows the caller to install a special handler to do custom evaluation of received notifications * matching the specified object and notification center. */ @property (nullable, copy) XCNotificationExpectationHandler handler; @end NS_ASSUME_NONNULL_END
husseinmaad/OmniSign
node_modules/react-native/ReactCommon/cxxreact/CxxNativeModule.h
// Copyright 2004-present Facebook. All Rights Reserved. #pragma once #include <cxxreact/CxxModule.h> #include <cxxreact/NativeModule.h> namespace facebook { namespace react { class Instance; std::function<void(folly::dynamic)> makeCallback( std::weak_ptr<Instance> instance, ExecutorToken token, const folly::dynamic& callbackId); class CxxNativeModule : public NativeModule { public: CxxNativeModule(std::weak_ptr<Instance> instance, std::unique_ptr<xplat::module::CxxModule> module); std::string getName() override; std::vector<MethodDescriptor> getMethods() override; folly::dynamic getConstants() override; bool supportsWebWorkers() override; void invoke(ExecutorToken token, unsigned int reactMethodId, folly::dynamic&& params) override; MethodCallResult callSerializableNativeHook( ExecutorToken token, unsigned int hookId, folly::dynamic&& args) override; private: std::weak_ptr<Instance> instance_; std::unique_ptr<xplat::module::CxxModule> module_; std::vector<xplat::module::CxxModule::Method> methods_; }; } }
husseinmaad/OmniSign
ios/build/Build/Products/Debug-iphonesimulator/DocuSignReactNativeSample.app/Frameworks/XCTest.framework/Headers/XCTWaiter.h
// // Copyright (c) 2016 Apple Inc. All rights reserved. // #import <XCTest/XCTestDefines.h> @class XCTestExpectation; @protocol XCTWaiterDelegate; NS_ASSUME_NONNULL_BEGIN /*! * @enum XCTWaiterResult * Values returned by a waiter when it completes, times out, or is interrupted due to another waiter * higher in the call stack timing out. */ typedef NS_ENUM(NSInteger, XCTWaiterResult) { XCTWaiterResultCompleted = 1, XCTWaiterResultTimedOut, XCTWaiterResultIncorrectOrder, XCTWaiterResultInvertedFulfillment, XCTWaiterResultInterrupted }; /*! * @class XCTWaiter * Manages waiting - pausing the current execution context - for an array XCTestExpectations. Waiters * can be used with or without a delegate to respond to events such as completion, timeout, or invalid * expectation fulfillment. XCTestCase conforms to the delegate protocol and will automatically report * timeouts and other unexpected events as test failures. * * Waiters can be used without a delegate or any association with a test case instance. This allows test * support libraries to provide convenience methods for waiting without having to pass test cases through * those APIs. */ @interface XCTWaiter : NSObject { #ifndef __OBJC2__ @private id _internalImplementation; #endif } /*! * @method -initWithDelegate: * Creates a new waiter with the specified delegate. */ - (instancetype)initWithDelegate:(nullable id<XCTWaiterDelegate>)delegate NS_DESIGNATED_INITIALIZER; /*! * @property delegate * The waiter delegate will be called with various events described in <XCTWaiterDelegate>. */ #ifdef __OBJC2__ @property (nullable, weak) id<XCTWaiterDelegate> delegate; #else @property (nullable, unsafe_unretained) id<XCTWaiterDelegate> delegate; #endif /*! * @property fulfilledExpectations * Returns an array containing the expectations that were fulfilled, in that order, up until the waiter * stopped waiting. Expectations fulfilled after the waiter stopped waiting will not be in the array. * The array will be empty until the waiter has started waiting, even if expectations have already been * fulfilled. */ @property (readonly) NSArray<XCTestExpectation *> *fulfilledExpectations; /*! * @method -waitForExpectations:timeout: * Wait on a group of expectations for up to the specified timeout. May return early based on fulfillment * of the waited on expectations. */ - (XCTWaiterResult)waitForExpectations:(NSArray<XCTestExpectation *> *)expectations timeout:(NSTimeInterval)seconds; /*! * @method -waitForExpectations:timeout:enforceOrder: * Wait on expectations and specify whether they must be fulfilled in the given order. Expectations can * only appear in the list once. */ - (XCTWaiterResult)waitForExpectations:(NSArray<XCTestExpectation *> *)expectations timeout:(NSTimeInterval)seconds enforceOrder:(BOOL)enforceOrderOfFulfillment; /*! * @method +waitForExpectations:timeout: * Convenience API that creates a waiter object which then waits on a group of expectations for up to * the specified timeout. May return early based on fulfillment of the waited on expectations. The waiter * is discarded when the wait completes. */ + (XCTWaiterResult)waitForExpectations:(NSArray<XCTestExpectation *> *)expectations timeout:(NSTimeInterval)seconds; /*! * @method +waitForExpectations:timeout:enforceOrder: * Convenience API that creates a waiter object which then waits on a group of expectations and optionally * enforces the order in which they are fulfilled. Expectations can only appear in the list once. The waiter * is discarded when the wait completes. */ + (XCTWaiterResult)waitForExpectations:(NSArray<XCTestExpectation *> *)expectations timeout:(NSTimeInterval)seconds enforceOrder:(BOOL)enforceOrderOfFulfillment; @end /*! * @protocol XCTWaiterDelegate * Events are reported to the waiter's delegate via these methods. XCTestCase conforms to the delegate * protocol and will automatically report timeouts and other unexpected events as test failures. * * @note These methods are invoked on an arbitrary queue. */ @protocol XCTWaiterDelegate <NSObject> /*! * @method -waiter:didTimeoutWithUnfulfilledExpectations: * Invoked when not all waited on expectations are fulfilled during the timeout period. If the delegate * is an XCTestCase instance, this will be reported as a test failure. */ - (void)waiter:(XCTWaiter *)waiter didTimeoutWithUnfulfilledExpectations:(NSArray<XCTestExpectation *> *)unfulfilledExpectations; /*! * @method -waiter:fulfillmentDidViolateOrderingConstraintsForExpectation:requiredExpectation: * Invoked when the -wait call has specified that fulfillment order should be enforced and an expectation * has been fulfilled in the wrong order. If the delegate is an XCTestCase instance, this will be reported * as a test failure. */ - (void)waiter:(XCTWaiter *)waiter fulfillmentDidViolateOrderingConstraintsForExpectation:(XCTestExpectation *)expectation requiredExpectation:(XCTestExpectation *)requiredExpectation; /*! * @method -waiter:didFulfillInvertedExpectation: * Invoked when an expectation marked as inverted (/see inverted) is fulfilled. If the delegate is an * XCTestCase instance, this will be reported as a test failure. */ - (void)waiter:(XCTWaiter *)waiter didFulfillInvertedExpectation:(XCTestExpectation *)expectation; /*! * @method -nestedWaiter:wasInterruptedByTimedOutWaiter: * Invoked when the waiter is interrupted prior to its expectations being fulfilled or timing out. * This occurs when an "outer" waiter times out, resulting in any waiters nested inside it being * interrupted to allow the call stack to quickly unwind. */ - (void)nestedWaiter:(XCTWaiter *)waiter wasInterruptedByTimedOutWaiter:(XCTWaiter *)outerWaiter; @end NS_ASSUME_NONNULL_END
husseinmaad/OmniSign
ios/build/Build/Products/Debug-iphonesimulator/DocuSignReactNativeSample.app/Frameworks/XCTest.framework/Headers/XCUISiriService.h
<reponame>husseinmaad/OmniSign // // Copyright © 2017 Apple Inc. All rights reserved. // #import <XCTest/XCUIElementTypeQueryProvider.h> NS_ASSUME_NONNULL_BEGIN #if XCT_UI_TESTING_AVAILABLE && TARGET_OS_IOS /*! * @class XCUISiriService * Represents a device's Siri interface and allows issuing textual queries * and producing element queries for UI shown by Siri. */ NS_CLASS_AVAILABLE_IOS(10_3) @interface XCUISiriService : NSObject + (instancetype)new NS_UNAVAILABLE; - (instancetype)init NS_UNAVAILABLE; /*! * Provides debugging information about the element representing the root of the Siri UI. * @seealso XCUIElement */ @property (readonly, copy) NSString *debugDescription; /*! * Presents the Siri UI, if it is not currently active, and accepts a string * which is then processed as if it were recognized speech. * * @param text The string to pass to Siri for processing. */ - (void)activateWithVoiceRecognitionText:(NSString *)text NS_SWIFT_NAME(activate(voiceRecognitionText:)); @end @interface XCUISiriService (XCUIElementTypeQueryProvider) <XCUIElementTypeQueryProvider> @end #endif NS_ASSUME_NONNULL_END
thiefsheep/fizzbuzz
c/fizzbuzz.c
/****************************************************************************** Hacktoberfest 2018 Write a program to do the Fizz Buzz Algorithm Multiple of three == Fizz Multiple of five == Buzz Multiple of three and five == FizzBuzz *******************************************************************************/ #include <stdio.h> int main(void) { int i; for (i = 1; i < 101; i++) { if (i % 3 == 0) printf("Fizz"); if (i % 5 == 0) printf("Buzz"); if (i % 3 && i % 5) printf("%d", i); printf("\n"); } return 0; }
JMDMobileSolutions/vr6dof-ios
CubeHunt/CubeProgram.h
<reponame>JMDMobileSolutions/vr6dof-ios // // CubeProgram.h // CubeHunt // // Created by <NAME> on 3/16/19. // Copyright © 2019 <NAME>. All rights reserved. // #import "Program.h" @interface CubeProgram : Program @property (assign, nonatomic) GLint transform; @property (assign, nonatomic) GLint position; @property (assign, nonatomic) GLboolean focused; @property (assign, nonatomic) GLint vertex; @property (assign, nonatomic) GLint color; @end
JMDMobileSolutions/vr6dof-ios
CubeHunt/Renderer.h
<filename>CubeHunt/Renderer.h // // Renderer.h // CubeHunt // // Created by <NAME> on 3/16/19. // Copyright © 2019 <NAME>. All rights reserved. // #import <GVRKit/GVRKit.h> NS_ASSUME_NONNULL_BEGIN @interface Renderer : GVRRenderer -(void)updateTransform:(simd_float4x4)transform isTracking:(BOOL)isTracking; @end NS_ASSUME_NONNULL_END
JMDMobileSolutions/vr6dof-ios
CubeHunt/FloorProgram.h
// // FloorProgram.h // CubeHunt // // Created by <NAME> on 3/16/19. // Copyright © 2019 <NAME>. All rights reserved. // #import "Program.h" @interface FloorProgram : Program @property (assign, nonatomic) GLint vertex; @property (assign, nonatomic) GLint color; @property (assign, nonatomic) GLint transform; @property (assign, nonatomic) GLint position; @end
JMDMobileSolutions/vr6dof-ios
CubeHunt/Buffer.h
<filename>CubeHunt/Buffer.h // // Buffer.h // CubeHunt // // Created by <NAME> on 3/16/19. // Copyright © 2019 <NAME>. All rights reserved. // #import <GLKit/GLKit.h> @interface Buffer : NSObject @property (assign, nonatomic) GLuint buffer; @property (assign, nonatomic) GLuint length; -(GLuint)createWithData:(GLfloat*)data andLength:(GLsizeiptr)length; @end
JMDMobileSolutions/vr6dof-ios
CubeHunt/CubeColorBuffer.h
<filename>CubeHunt/CubeColorBuffer.h // // CubeColorBuffer.h // CubeHunt // // Created by <NAME> on 3/16/19. // Copyright © 2019 <NAME>. All rights reserved. // #import "Buffer.h" NS_ASSUME_NONNULL_BEGIN @interface CubeColorBuffer : Buffer @end NS_ASSUME_NONNULL_END
JMDMobileSolutions/vr6dof-ios
CubeHunt/Program.h
// // Program.h // CubeHunt // // Created by <NAME> on 3/16/19. // Copyright © 2019 <NAME>. All rights reserved. // #import <GLKit/GLKit.h> @interface Program : NSObject @property (assign, nonatomic) GLuint program; -(GLuint)loadShader:(GLenum)type withSource:(const char*)source; -(GLuint)linkVertexShader:(GLuint)vertexShader andFragmentShader:(GLuint)fragmentShader; @end
JMDMobileSolutions/vr6dof-ios
CubeHunt/FloorBuffer.h
<filename>CubeHunt/FloorBuffer.h // // FloorBuffer.h // CubeHunt // // Created by <NAME> on 3/16/19. // Copyright © 2019 <NAME>. All rights reserved. // #import "Buffer.h" NS_ASSUME_NONNULL_BEGIN @interface FloorBuffer : Buffer @end NS_ASSUME_NONNULL_END
JMDMobileSolutions/vr6dof-ios
CubeHunt/FloorColorBuffer.h
<gh_stars>0 // // FloorColorBuffer.h // CubeHunt // // Created by <NAME> on 3/16/19. // Copyright © 2019 <NAME>. All rights reserved. // #import "Buffer.h" NS_ASSUME_NONNULL_BEGIN @interface FloorColorBuffer : Buffer @end NS_ASSUME_NONNULL_END
JMDMobileSolutions/vr6dof-ios
CubeHunt/CubeBuffer.h
<filename>CubeHunt/CubeBuffer.h<gh_stars>0 // // CubeBuffer.h // CubeHunt // // Created by <NAME> on 3/16/19. // Copyright © 2019 <NAME>. All rights reserved. // #import "Buffer.h" NS_ASSUME_NONNULL_BEGIN @interface CubeBuffer : Buffer -(BOOL)isFocusedInDirection:(GLKVector4)direction atPosition:(GLKVector4)position andCubePosition:(GLKVector3)cubePosition; @end NS_ASSUME_NONNULL_END
j00v/ZENZO-Core
src/denomination_functions.h
<gh_stars>1-10 /** * @file denominations_functions.h * * @brief Denomination functions for the Zerocoin library. * * @copyright Copyright 2019 PIVX Developers * @license This project is released under the MIT license. **/ // Copyright (c) 2015-2019 The PIVX developers #include "reverse_iterate.h" #include "util.h" #include "libzerocoin/Denominations.h" #include "primitives/zerocoin.h" #include <list> #include <map> void listSpends(const std::vector<CZerocoinMint>& vSelectedMints);